//================================================================
// Returns obj arr for elemenets with specified class name
// Byron Matto 8/10/2009
//================================================================
var currentPage;
var totalPages;

function getElemsByClass(tag, name){
	 var elemArr = new Array();
	 var classArr = new Array();
	 elemArr = document.getElementsByTagName(tag);
	
	 for(var i=0; i<elemArr.length; i++){
		 if(elemArr[i].className.indexOf(name) > -1){
			 classArr.push(elemArr[i]);
		 }
	 }
	 return classArr;
}

function intialize(){
		
	/*-- START MENUS --*/
	
	var $MenuTitle = $(".selected");
	var $Menu = $(".select");
	var $FilterItem = $(".FilterItem");
	var queryArr = new Object();
	var timeoutID;
	
	$MenuTitle.hover(
		function(){
			$(this).find('.select').stop(true,true).slideDown(250, 'easeInOut')
		},
		function(){
			$(this).find('.select').stop(true,true).slideUp(250, 'easeInOut')
		}
	);
	$MenuTitle.each(function(){
		if($(this).children('span').html()!='Select' && $(this).children('span').html() != null ){
			
			if($(this).prev().html() == 'filter items:'){
				var $Key = "category";
				var $Value = $(this).children('span').html();
			}else{
				var $Key = $(this).prev().html().substring(0,$(this).prev().html().length-1);
				var $Value = $(this).children('span').attr('id');
				
			}
			
			queryArr[$Key] = $Value;
		}
		
	});
	
	$FilterItem.click(function(e){
		$(this).closest('.selected').children('.SelectedCategory').html($(this).contents().html());
		
		var $Key = $(this).children('span').attr('class');
		var $Value = $(this).attr('id');
		var queryCount = 0;
		var addKey = false 
		
		var tempQuery = new Object();
		
		var clicked = $(e.target).closest('.selected').prev().html().substring(0,$(e.target).closest('.selected').prev().html().length-1) ;
		
		for(n in queryArr){
			
			tempQuery[n] = queryArr[n];
			
			if(clicked == n ) break;
			
		}
		
		tempQuery[$Key]=$Value;
		
		queryArr = tempQuery;
		
		//console.log($.param(queryArr));
		window.location = 'results.php?'+$.param(queryArr);
		/*
		$.post('filterResults.php', queryArr, function(data){
			var dataArr = data.split('#ilikeapples#');
			
			$("#header").html(dataArr[0]);
			$("#results").html(dataArr[1]);
			intialize();
			
		});
		*/
		 
	});
	
	/*-- END MENUS --*/
	
	/*-- START TABS --*/
	
	var $Tab = $(".tab");
	var $BodyId = $("body").attr('id');
	
	$Tab.each(function(){
		if(!$(this).hasClass($BodyId)){
			$(this).hover(function(){
				$(this).stop().animate({"marginTop": "14px"}, 250, "easeInOut");
			},function(){
				$(this).stop().animate({"marginTop": "28px"}, 250, "easeInOut");
			});	
		}
	});
	
	/*-- END TABS --*/
	
	/*-- START SEARCH--*/
	
	var $Search = $('#search');
	
	$Search.focus(function(){
		if(this.value=='' || this.value=='search') this.value='';
	})
	
	$Search.blur(function(){
		if(this.value.length == 0)this.value='search';
	});
	
	/*-- END SEARCH--*/
	
	/*-- START HIGHLIGHT HOVERS --*/
	
	var $Highlight = $('.highlight .img');
		
	$Highlight.each(function(){
		$(this).hover(function(){				   
			$('.highlighted', $(this).parent().parent()).animate({"width":"150"}, {queue:false, duration:200, easing:"easeInOut"});
			$('.highlighted', $(this).parent().parent()).animate({"opacity": "1"}, {queue:false, duration:200, easing:"easeInOut"});
		},function(){
			$('.highlighted', $(this).parent().parent()).animate({"width":"75"}, {queue:false, duration:200, easing:"easeInOut"});
			$('.highlighted', $(this).parent().parent()).animate({"opacity": "0"}, {queue:false, duration:200, easing:"easeInOut"});
		});
	});
	
	/*-- END HIGHLIGHT HOVERS --*/
	
	/*-- START PAGING --*/
	var $paginationList = $(".pagination ul");
	var $left = $('.pagination .left img');
	var $right = $('.pagination .right img');
	
	for(var i=1; i<=totalPages; i++){
		if(currentPage == i){
			$paginationList.append('<li>'+i+'</li>');
		}else{
			$paginationList.append('<li class="page-number">'+i+'</li>');
		}
	}
	
	if(currentPage == 1) $left.attr('src', 'images/chevron-left-grey.png').addClass('disabled');
	if(currentPage > 1) $left.attr('src', 'images/chevron-left.png').removeClass('disabled');
	if(currentPage == totalPages) $right.attr('src', 'images/chevron-grey.png').addClass('disabled');
	if(currentPage < totalPages) $right.attr('src', 'images/chevron.png').removeClass('disabled');
	if(location.search.indexOf('search') > -1){
		var searchArr =location.search.slice(1).split("=");
		queryArr[searchArr[0]] = searchArr[1]
	}
	
	var $paginationItem = $(".pagination ul li");
	$paginationItem.each(function(index){
		if(currentPage != index+1){
			$(this).click(function(){
				queryArr['page'] = index+1;
				//console.log(queryArr);
				window.location = 'results.php?'+$.param(queryArr);
				/*$.post('filterResults.php', queryArr, function(data){
					var dataArr = data.split('#ilikeapples#');
					$("#header").html(dataArr[0]);
					$("#results").html(dataArr[1]);
					intialize();
				});	*/			   
			});
		}
	});
	
	$left.click(function(){
		if($(this).attr('class') == "disabled"){
			//console.log('no');
			return
		}
		queryArr['page'] = currentPage-1;
		//console.log(queryArr);
		window.location = 'results.php?'+$.param(queryArr);
		/*$.post('filterResults.php', queryArr, function(data){
			var dataArr = data.split('#ilikeapples#');
			$("#header").html(dataArr[0]);
			$("#results").html(dataArr[1]);
			intialize();
		});	*/
	});
	
	$right.click(function(){
		if($(this).attr('class') == "disabled"){
			//console.log('no');
			return
		}
		var newPage = currentPage+1;
		queryArr['page'] = newPage;
		//console.log(queryArr);
		window.location = 'results.php?'+$.param(queryArr);
		/*$.post('filterResults.php', queryArr, function(data){
			var dataArr = data.split('#ilikeapples#');
			$("#header").html(dataArr[0]);
			$("#results").html(dataArr[1]);
			intialize();
		});*/	
	});
	
	/*-- END PAGING --*/

}

$(document).ready(function(){
		/*-- START LEFT NAV --*/
		
		var iconArr = new Array();
		iconArr = getElemsByClass('li', 'navicon');
		
		var $NavText = $(".text");
		var $NavIcons = $(".icons");
		
		for(var i = 0; i<iconArr.length; i++){
			//alert('');
			if(iconArr[i].className.indexOf('selected') < 0){
				iconArr[i].onmouseover = function(){
					$(this).stop().animate({"marginRight": "-30px"}, 250, "easeInOut");
					$('.text .'+$(this).attr('id')).css("background", "transparent url('images/links_bg.png') repeat-y");
				}
				iconArr[i].onmouseout = function(){
					$(this).stop().animate({"marginRight": "-51px"}, 250, "easeInOut");
					$('.text .'+$(this).attr('id')).css("background", "");
				}
			}
		}
		
		$("li",$NavText).mouseover(function(){
			$('.'+$(this).attr('class')+'.navicon').stop().animate({"marginRight": "-30px"}, 250, "easeInOut");
			$(this).css("background", "transparent url('images/links_bg.png') repeat-y");
		});
		$("li",$NavText).mouseout(function(){
			$('.'+$(this).attr('class')+'.navicon').stop().animate({"marginRight": "-50px"}, 250, "easeInOut");
			$(this).css("background", "");					   
		});			  	
	
		
		/*-- END LEFT NAV --*/
	
	intialize();
	
});

function searchItems(query){
	
	$.get('search.php', {q:query}, function(data){
	
		$("#results").html(data);
	
	});
	
}

function detailMenu(string, product_code){
	
	var query = string.split('#');
	
	var queryObj = new Object;
	for(n in query){
		var temp = query[n].split(':');
		if(temp[1]!=''){
			queryObj[temp[0]]=temp[1];
		}
	}
	
	$.post('detailMenu.php?product_code='+product_code, queryObj, function(data){
		var dataArr = data.split('#ilikeapples#');
		
		$("#header").html(dataArr[0]);
		$("#productCode").html(dataArr[1]);
		
		intialize();
		
	});
	
}

function emailFriend(product_code){
	$("#emailForm").dialog({
		modal:true,
		height:325,
		width:500,
		draggable:false,
		resizable:false,
		title: "Email "+product_code+" to a Friend"
	});

}

function get_cookies_array() {

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }

    return cookies;
   
}

function checkCookie(productCode){
	if($.cookie('mariasItemCookies: '+productCode)){
		$('.inquire').html('<em>Item has been added to inquery list under <a href="contact.php">"Contact"</a>.</em>')
	}
}

function fillInquery(){
	var cookies = get_cookies_array();
	for(var name in cookies) {	
		if( name.indexOf('mariasItemCookies:') > -1){
	  		$('#inquery').append("<div class='itemListItem'><div class='cookie-name'>"+cookies[name] + "</div><a href='detail.php?id="+cookies[name]+"'>View</a> | <a href='javascript:void(0)' onclick='deleteItem(\""+cookies[name]+"\", event);'>Delete</a></div>" );
	  	}
	}

}

function deleteItem(name, e){
	if(confirm(" Are you sure you would like to remove this item from the inquery list? ")){
		$.cookie('mariasItemCookies: '+name, null);
		
		$(e.target).closest('.itemListItem').html('');
	}
}





//GTS CAROUSEL
function gtsCarousel(count, images, links, sectionIndex){

	function showArrows(){
		$('.left, .right').css('display', 'inline');
	}


	var displayCount = count; /*--- BUILT ON THIS VARIABLE!!! ---*/ //Define INT for state # of Items to be visible
	var right = 1; //List Positition
	var allPhotos = images; //All Photos
	var allLinks = links; //All links
	var photosCount = allPhotos.length; //Count of ALL photos


	if(photosCount<displayCount)displayCount=photosCount; //Display Area Size
	var arrCar = new Array(); //Initiate Carousel Array
	if(photosCount>1) showArrows(); //Show Arrows


	for(n = 0; n<photosCount; n++) //Push Into Carousel Array Needed Photos
	{
		if(n<(displayCount))
		{
			var tempImg = new Image();
			tempImg.src = allPhotos[n];
			arrCar.push(tempImg.src);
		}
	}


	var carCount = arrCar.length;



	/*_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_PRINT_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_*/
	
	for(var i = 0; i<arrCar.length; i++){
		$('.carousel-list').append("<li class='carousel-item'><img src='"+arrCar[i]+"'/></li>");
	}
	
	/*_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_PRINT_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_*/


	var $carouselItem = $('.carousel-item'); //All Items In Carousel
	var $carouselList = $('.carousel-list'); //Whole Carousel List
	var $bigIamge = $('.big-image'); //Big Image
	var clickCount = 0; //Click Counter


	var margin = parseInt($($carouselItem).css('borderRightWidth'))*2; //Border l/r of Item
	var itemW = parseInt($($carouselItem).css('width')); //Width of Item
	var listW = (margin+itemW)*(displayCount); //Width of whole carousel list
	var displayW = ((margin+itemW)*(displayCount))-margin; //Width of display mask


	$('.car-wrap').css('width', displayW+'px'); //Set width of display mask
	$($carouselList).css('width', listW+'px'); //Set width of Carousel list


	/*_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_*/



	/*--- START ADD ITEM ---*/
	function addItem(){
		if(carCount===photosCount) return false; //Due Dillegence
		listW += (itemW+margin); //Increast List Width To Accomodate New Items
		$($carouselList).css('width', listW+'px'); //Set Width
		$($carouselList).append("<li class='carousel-item'><img src='"+allPhotos[carCount]+"' /></li>");
		$carouselItem = $('.carousel-item'); //Reset Items In Carousel
		directClick(); //Reintiate Click Events
		carCount++; //Adjust Car Arr Count
	}
	/*--- END ADD ITEM ---*/


	/*--- START DIRECT CLICK ---*/
	function directClick(){
		$($carouselItem).each(function(index){
		
			$(this).unbind('click'); //Unbind Click Events
			
			$(this).click(function(e){ //Set Click Events
		
				right = (itemW+margin)*index; //Set Right Relative List Index
				clickCount = index //Set Click Count Relative Index
				var displayPos = $(this).data('position'); //Current Display Position
				removeData(); //Remove Relative Position Data
			
				if(clickCount==0){
					$('#leftButton').css("backgroundImage", "url(images/chevron-left-grey.png)");
					if(clickCount == photosCount-1)$('.right').css("cursor", "default");
				}else{
					$('#leftButton').css("backgroundImage", "url(images/chevron-left.png)");
					$('#leftButton').css("cursor", "pointer");
				}
			
			
				if(clickCount == photosCount-1)$('.right').css("backgroundImage", "url(images/chevron-grey.png)");
				if(clickCount == photosCount-1)$('.right').css("cursor", "default");
			
			
			
				if(carCount<photosCount){ //If All Photos Not Loaded
					for(var p=0; p<displayPos; p++){
					addItem(); //Add Items Relative To Display Position
					}
				}
		
		
				/*SET DATA and SET IMAGE*/
				for(var i = 0; i<displayCount; i++){
					$($carouselItem[index+i]).data('position',i);
					if(i===0){
						$($carouselItem[index+i]).addClass('selected');
						
						if(GL_linkArr[sectionIndex][index+i] != "")
							$bigIamge.html('<a href="'+ GL_linkArr[sectionIndex][index+i]+'"><img src="'+ GL_fullArr[sectionIndex][index+i]+'" alt="" /></a>');
						else 
							$bigIamge.html('<img src="'+ GL_fullArr[sectionIndex][index+i]+'" alt="" />');
							
						//$($bigIamge).attr('src', GL_fullArr[sectionIndex][index+i]);
					
					}
				}
		
		
				$($carouselList).animate({"marginLeft":right*(-1)+'px'}, 400); //ANIMATE or MOVE

			});
		});
	}
	directClick();

	/*--- END DIRECT CLICK ---*/



	/*_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_*/



	/*--- START DATA ---*/
	$($carouselItem).each(function(index){ //Intitiate Display Data
		if(index<displayCount) $(this).data("position", index); //Add Display Data
		if(index===0) $(this).addClass('selected'); //Initiate Selected Class
	});


	function removeData(){ //Clear Display Data Function
		$($carouselItem).each(function(){
			$(this).removeData("position"); //Remove Display Data
			$(this).removeClass("selected"); //Remove Selected Class
		});
	}
	
	/*--- END DATA ---*/


	/*_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_*/


	/*--- START LEFT/RIGHT ---*/
	$('.carousel .left ,.carousel .right').each(function(){
		$(this).click(function(){
			if($(this).attr('class')==='left'){ /*LEFT BUTTON*/
				if( clickCount > 0 ){ //AWARENESS CHECK
					right -= (itemW+margin); //RIGHT POSITION MINUS ONE "UNIT"
					clickCount--; //AWARENESS MINUS 1
				}
			
				if(clickCount === 0) $('#leftButton').css("backgroundImage", "url(images/chevron-left-grey.png)");
				if(clickCount === 0) $('#leftButton').css("cursor", "default");
				if(clickCount < photosCount) $('#rightButton').css("backgroundImage", "url(images/chevron.png)");
				if(clickCount < photosCount) $('#rightButton').css("cursor", "pointer");
			
			}else{ /*RIGHT BUTTON*/
				if( clickCount < photosCount-1 ){ //AWARENESS CHECK
					right += (itemW+margin); //RIGHT POSITION PLUS ONE "UNIT"
					clickCount++ //AWARENESS PLUS 1
					//console.log(clickCount);
					//console.log(photosCount);
					if(clickCount == photosCount-1) $('#rightButton').css("backgroundImage", "url(images/chevron-grey.png)");
					if(clickCount == photosCount-1) $('#rightButton').css("cursor", "default");
				}
			
			
				$('#leftButton').css("backgroundImage", "url(images/chevron-left.png)");
				$('#leftButton').css("cursor", "pointer");
				if((carCount)<photosCount) addItem(); //GOING RIGHT? MORE PHOTOS? ADD ONE!
			}
			
			
			
			removeData();
			for(var i = 0; i<displayCount; i++){
				$($carouselItem[clickCount+i]).data('position',i);
				if(i===0){
					$($carouselItem[clickCount+i]).addClass('selected');
					
					if(GL_linkArr[sectionIndex][clickCount+i] != "")
						$bigIamge.html('<a href="'+ GL_linkArr[sectionIndex][clickCount+i]+'"><img src="'+ GL_fullArr[sectionIndex][clickCount+i]+'" alt="" /></a>');
					else 
						$bigIamge.html('<img src="'+ GL_fullArr[sectionIndex][clickCount+i]+'" alt="" />');
					
					//$($bigIamge).attr('src', GL_fullArr[sectionIndex][clickCount+i]);
				}
			}
			
			
			$($carouselList).animate({"marginLeft":right*(-1)+'px'}, 400); //ANITMATE or MOVE
		});
	});
	
	/*--- END LEFT/RIGHT ---*/

}











	
