var allProjects, arrayCheckInterval, artPage, artProjects, currenLocation, currentPosition, currentChunk, featuredProjects, funcArray, hilites, hilitebarType, hiliteTotWidth, hiliteType, hiliteWidth, numberOfSlides, pageTotal, projArray, relatedIDs, relatedProjects, tagArray, testData, theData;
currenLocation = window.location.hash;

var projectHiliteTemplate = '<div class="hilite" style="width: 198px; height: 175px; background-color: #FFFFFF; float: left; margin-right: 2px; margin-bottom: 2px; text-align: center;" id="hilite{{ id }}"><a href="/work/view/{{ id }}" style="text-decoration: none;"><img src="/assets/asset_thumbnails/height_125/{{ file_name }}" id="hImg{{ id }}"><div class="hiliteInfo">{{ title }}</div></a></div>';

//Div hierarchy
/*
> hilites
  >> hilitecontainer
		 >>> hiliteInner
		     >>>> hilite
*/

projArray = new Array();

$(function(){
	//GETS THE DATA FOR THE ALL PIECES OF FURNITURE
	$.getJSON('/work/index.json', organizeData);
});

//GETS AND ORGANIZES THE INCOMING DATA FOR THE PIECES OF FURNITURE
var organizeData = function(data) {
	$(document).ready(function() { 
		allProjects = data;
	
		sortData();
	
		artProjects = _.select(allProjects, function(project){
			if(project.Art) {
				return project.Art();
			}
		});
	
		if(hilitebarType == "Featured") {
			featuredProjects = _.select(allProjects, function(project){
				if(project.Featured){
					return project.Featured();
				}
			});
		
		}
	
		headerSet();
	});

}

var sortData = function(){
	var projGroupedByNumIntersections = {};
	
	$.each(allProjects, function(i, proj){
		// on this project
		// loop through its tags and set the number of intersections
		var numIntersections = 0;
		$.each(proj.PortfolioTag, function(i, tag){
			if($.inArray(tag.id, currentTags) > -1){
				numIntersections++;
			}
		});
		// if the number of intersections is great enough
		// push it into the array of displayed projects
		if(currentTags.length == 0||numIntersections > 0){
			if(!$.isArray(projGroupedByNumIntersections[numIntersections])){
				projGroupedByNumIntersections[numIntersections] = [];
			}
			projGroupedByNumIntersections[numIntersections].push(proj);
		}
	});
		
	// convert the object to an array
	projArray = [];
	var idx = 0;
	$.each(projGroupedByNumIntersections, function(i, obj){
		projArray[idx] = obj;
		idx++;
	});
	
	
	
	// reverse the list, and output the projects to the page
	projArray.reverse();
	
	$.each(projArray, function(i, obj){
		$.each(obj, function(i, proj){
			proj.Featured = function(){return proj.PortfolioProject.Featured==1?true:false;};
			proj.Art = function(){return proj.PortfolioProject.Art==1?true:false;};
			if(hilitebarType != "Featured") {
				proj.Related = checkRelated(proj.PortfolioProject.id);
			}
			proj.id = proj.PortfolioProject.id;
		  	proj.file_name = proj.Thumb.file_name;
      	  	proj.title = proj.PortfolioProject.title;
          	proj.size = proj.PortfolioProject.Size;
		});
	});
}


var checkRelated = function(value) {
	var checks = false;
	$.each(relatedIDs, function(t, rel){
		if(value == rel.portfolio_related_project_id) {
			checks = true
		}
	});
	return checks;
}

//creates the hilite bar at the bottom of the page
// Params:
var createHiliteBar = function () {
	  hilitebarType == "Featured" ? theData = featuredProjects : theData = relatedProjects;

		if(theData.length > 0){
			hiliteWidth = 198;//width of the thumbnail
			hiliteSpacer = 2;
			numberOfHilites = theData.length;//number of thumbnails
			totWidth = (hiliteWidth * numberOfHilites) + (hiliteSpacer * numberOfHilites)
			
			//sets the styling on the main hilite bar parent div
			//removes the 45px padding from the footer
			$('#footer')
				.css ({
					'padding-top': 0
			});
	
			$('#footer .content')
				.css ({
					'padding-top': 0
			});
	
			$('#footer_logo') 
				.css ({
					'padding-top': 45
			})
      
			

			//insert left and right arrow controls
		  $("#hilites")
				.append("<div id='barTitle'>"+ hilitebarType +" Works  | </div>")
				.append("<div id='hiliteCount'></div>") 
				.append("<div class='hiliteControl' id='leftControl'></div>")
				.append("<div class='hiliteControl' id='rightControl'></div>")
				.append("<div id='hiliteContainer'></div>");
      
      	//restyles the hiliteContainer
				$("#hiliteContainer")
					.css ({
					  'margin': '0 auto',
					  'width': 798,
					  'height': 200,
					  'overflow':'auto',
					  'position':'relative',
					  'top': 60
					})
				
				
				var noDupArr = RemoveDuplicates(theData);
				
				
				//appends a hilite into hiliteInner using projectHiliteTemplate
				$.each(noDupArr, function(i, obj){
						$("#hiliteContainer").append(Mustache.to_html(projectHiliteTemplate, obj));
				});
				
				// Wrap all .hilite with #hiliteInner div
				$('.hilite').wrapAll('<div id="hiliteInner"></div>');
			  $("#hiliteInner").append("<div class='clear'></div>")
				$("#hiliteInner").width(totWidth); 	
				// Remove scrollbar in JS
				$('#hiliteContainer').css('overflow', 'hidden');
				
				 $("#hilites").show(); 
			
			$('#leftControl') 
				.css ({
					'position': 'relative',
					'top':102,
				  'left':50,
					'height': 29,
					'background':'url(/media/img/arrow_left.gif)',
					'background-repeat': 'no-repeat'
				});
	
			$('#rightControl') 
				.css ({
					'position': 'relative',
					'top': 102,
				  'left': 923,
					'height': 29,
					'background':'url(/media/img/arrow_right.gif)',
					'background-repeat': 'no-repeat'
				});
			currentPosition = 0;//incremented on click
			manageControls(currentPosition);
			pageTotal = Math.ceil((noDupArr.length * hiliteWidth)/800);//Math.round(numberOfHilites/4);
		 
			
      $('.hiliteControl')
			    .bind('click', function(){
			
					var theDir = 1;
	
			    // Determine new position
				  currentPosition = $(this).attr('id') =='rightControl' ? currentPosition+1 : currentPosition-1;
					$(this).attr('id') =='rightControl' ? theDir = -1 : theDir = 1;

		      		// Hide / show controls
		     	manageControls(currentPosition);
    
					var newX = ($('#hiliteInner').margin().left + (800*theDir));
		
					// Move hiliteInner using margin-left
					$('#hiliteInner').animate({
		        		'marginLeft' : newX
		      		});
					paginate();
			});

	
			
			
			 $("#barTitle")
				.css ({
					'position': 'absolute',
					'top': 15,
					'left': 97,
					'color': '#e00b24',
					'font-size': 18
				});
      
      var countSp = 0;
			hilitebarType == "Featured" ? countSp = 255 : countSp = 230;
				
			$("#hiliteCount")
				.css ({
					'position': 'absolute',
					'top': 15,
					'left': countSp,
					'font-size': 18
				});

			
			//places the styling on the controls	
			$('.hiliteControl') 
				 .css ({
				  'display':'block',
				  'width':18,
				  'height':28,
				  'position':'absolute',
				  'cursor': 'pointer'
				});

			$(".hiliteInfo")
				.css ({
					'font-family': 'Helvetica, Arial, Verdana, sans-serif',
					'color': '#fb7d07',
					'font-weight': 'bold',
					'font-size': 12
			 });  

	     
      //CHECKS TO SEE IF THERE IS MORE THAN 4 FEATURED HILITES AND ADJUSTS FOR LESS
			if(numberOfHilites > 4){
				paginate();
			} else {
				$("#barTitle").html(hilitebarType +" Works");
				$('#rightControl').hide();
			}
			if(numberOfHilites==0){
			  $("#hilites").hide();
			}
		}
		$('#leftControl').hide();
		
		if(hilitebarType == "Featured"){
			$("#barTitle")
				.prepend("<img src='/media/img/featured_project_block.gif' style='margin-right: 5px; margin-top: -2px;'>")
  	}
}

var RemoveDuplicates = function(arr){
    //get sorted array as input and returns the same array without duplicates.
    var result=new Array();
    var lastValue="";
    for (var i=0; i<arr.length; i++) {
 	  	var curValue=arr[i];
	 	  if (curValue != lastValue) {
	 		 result[result.length] = curValue;
	 	  }
	 	  lastValue=curValue;
    }
    return result;
}

var paginate = function() {
	currentChunk = (currentPosition+1);
	$("#hiliteCount").html(currentChunk+" of "+ pageTotal);
}

// manageControls: Hides and shows controls depending on currentPosition
var manageControls = function(position){
	// Hide left arrow if position is first slide
  if(position==0){ $('#leftControl').hide() }
  else{ $('#leftControl').show() }
	
	// Hide right arrow if position is last slide
	if(position == (pageTotal-1) || pageTotal == 1){ $('#rightControl').hide() }
  else{ $('#rightControl').show() }
};


//Sets the header to 'Furniture Store" or "Fine Art Gallery
var headerSet = function(){
	$(".page_title").empty();
	if(currenLocation == "#gallery") {
		setUpArtPageTitle();
		constructArtHeader();
		$('body').addClass('fineArt');
	} else {
		setUpFurnPageTitle();
	}
	Cufon.refresh();
}

var setUpFurnPageTitle = function(){
	artPage = false;
	link ="";
	if ($('body').hasClass('portfolio_view')){
		 	var tags = document.location.hash.split("_")[1];
			if(tags == undefined){
				link = "<a href='/work'>&lt; back to results</a>";
			}else{
				link = "<a href='/work/index/tag:"+tags+"'>&lt; back to results</a>";
			}		
	};
	// construct the back to results link
	$(".page_title").append("Furniture Store"+link);
}

var setUpArtPageTitle = function(){
	artPage = true;
	$(".page_title").append("Fine Art Gallery");
	
	$("h2.page_title")
	.css ({
		'padding-top': 25
	});	
	
	$("#tag_list").empty();
}

var constructArtHeader = function(){  
	$('.content_header .content #tag_list').append("<div class='top_block'><p class='block_img'><a href='/21/marcus-studio-gift-cards'><img src='/media/assets/gift_card_block.jpg'></a></p><a href='/21/marcus-studio-gift-cards'><p>Marcus Studio Gift Cards Available</p></a></div><div class='top_block'><p class='block_img'><a href='/21/marcus-studio-gift-cards'></a><!-- <img src='/media/assets/vist_block.jpg'></p><a href='/2/the-studio'><p>Visit Marcus Studio and Get a Look Inside</p></a>--></div><div class='clear'></div>");
	$(".top_block")
		.css({
			'padding-top': 0
		})
		
	$('.content_header .content #tag_list')
		.css({
			'float':'left', 
			'width': 600, 
			'margin-left': -11, 
			'padding-top': 20
		})
}
