// JavaScript Document

var searchresults,productCount,currentProduct;
productCount = -1;

window.onload = init;

function init()
{
	
	var searchinput = document.getElementById('smart');
	searchresults = document.getElementById('ssresults');
	
	if(searchinput){
		searchinput.onfocus =  function()
		{
			searchinput.value = "";
		}
		
		searchinput.onkeyup =  function()
		{
			sendsmartSearch(searchinput.value);
		}
		
		searchresults.onblur = searchinput.onblur = function()
		{
			//$('#ssresults' ).hide("slow");
			setTimeout("$('#ssresults' ).hide('slow');", 2000)
			
		}
	}
}

$(document).ready(function(){
						   
	$("#pageflip").hover(function() { //On hover...
	$("#pageflip img , .msg_block").stop()
		.animate({ //Animate and expand the image and the msg_block (Width + height)
			width: '165px',
			height: '163px'
		}, 500);
	} , function() {
	/*$("#pageflip img").stop() //On hover out, go back to original size 50x52
		.animate({
			width: '50px',
			height: '49px'
		}, 220);
	$(".msg_block").stop() //On hover out, go back to original size 50x50
		.animate({
			width: '47px',
			height: '46px'
		}, 200); //Note this one retracts a bit faster (to prevent glitching in IE)*/
	});	
	
	$('div[class^=openSideComment]').hover(
		function() {
			var $this = $(this);
			var x = $this.attr("id");
			$('#sideComment_'+x ).show("slow");
			
		},
		function() {
			var $this = $(this);
			var x = $this.attr("id");
			$('#sideComment_'+x ).hide("slow");
		}
	);
	
	
	
	
	
	
	
	
	
	
	
	var $menu = $('ul.facebookOptions');
			var $open = $('a.trigger');
			
			//create an emtpy object to keep track of the timeouts
			var menuTimeouts = {};
			
			//hide all of the menus
			$menu.hide();
			$("#facebookIcons").hide();
			
			$open.each(function(index) {				
				$(this).click(function() {
					//identify the clostest menu
					$nextMenu = $(this).next($menu);
					if ($nextMenu.is(":visible")) {
						$nextMenu.fadeOut('fast').css('z-index', '50');
						if (menuTimeouts[$id]) {
							clearTimeout(menuTimeouts[$nextMenu.attr('id')]);
							menuTimeouts[$nextMenu.attr('id')] = undefined;
						}
					} else {
						$menu.hide(); //close all other open menus
						$nextMenu.show().css('z-index', '500'); //z-index for good measure
						
						//start a unique setTimeout for this menu
						menuTimeouts[$nextMenu.attr('id')] = setTimeout(function () {
							//fade the menu out after 2 seconds
							$nextMenu.fadeOut('slow');
						}, 2000)
					}
			
					return false;
				});
			});
			
			$menu.find('li').mouseenter(function (event) {
				//store the ID of this trigger's closest menu
				var $id = $(this).parents('ul').attr('id');
				
				//cancel the timeOut when the mouse is over the menu
				if (menuTimeouts[$id]) {
					clearTimeout(menuTimeouts[$id]);
					menuTimeouts[$id] = undefined;
				}
			}).mouseleave(function () {
				var $this = $(this).parents('ul');
				
				//start another time when the mouse leaves the menu
				menuTimeouts[$this.attr('id')] = setTimeout(function () {
					$this.fadeOut('slow');
				}, 2000);
			});
	
	
	
	
	
	
	
	
	
	
	
	
 });

function pullsmartSearch()
{
	if( xmlHttp.readyState == 4 )
	{
		searchresults = document.getElementById('ssresults');
		var seeall = document.getElementById('smart')
		var results = ''
		var matches = ''
		var sMatch = ''
		 matches = xmlHttp.responseText.split('*|*');
		 
		for( i=0;i<(matches.length-1);i++ )
			{	
				sMatch = matches[i].split("||");
				results += '<div><a href="'+sMatch[0]+'">'+sMatch[1]+'</a></div>'
			}
		results += '<div><a href="/Scripts/Admin/Sys/sysmsg.asp?ssphrase='+seeall.value+'">See all results</a></div>'
		searchresults.innerHTML = results
		
		if( results.value != '' )
		{
			$('#ssresults' ).show("slow");
		}
	}
}

function sendsmartSearch(searchphrase)
{
	checkAJAX();
	//alert(searchphrase)
	var url = "/Scripts/ajax/smartsearch.ajax.asp";
	url += "?smart="+searchphrase;
	xmlHttp.onreadystatechange = pullsmartSearch;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function showMenu()
{
	searchresults = document.getElementById('ssresults');
	searchresults.style.display = 'block'
}

function hideMenu()
{
	var hide = document.getElementById('smart')
	searchresults = document.getElementById('ssresults');
	
	searchresults.style.display = 'none'
	hide.value = ''
			
}

// find Y position
function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}


function validate(form)
{
	
	var tag=document.body.getElementsByTagName('*');
	var errormsg = document.getElementById('errormsg')
	var txt = ''
	var errorString = "";
	var id = "";
	for(var i=0; i<tag.length; i++) {
		
		switch(tag[i].className){
			
			case "req text":
				errorString += validateInput(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req select":
				errorString += validateInput(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req check":
				errorString += validateCheck(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req checkgroup":
				if(id != tag[i].id){
					id = tag[i].id;
					errorString += validateCheckGroup(form[id],form[tag[i].id + "_err"].value);
				}
				break;
			case "req date":
				errorString += validateDate(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req email":
				errorString += validateEmail(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req phone":
				errorString += validatePhone(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req soc":
				errorString += validateSocial(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "req zip":
				errorString += validateZip(tag[i],form[tag[i].id + "_err"].value);
				break;
			case "":
				break;
			
		}
		
	}
	if(errorString!=""){
		alert(errorString);
		return false;
	}
	return true;
	//sendForm()
}

function getByClass(theClass){
	
	var allDivTags = new Array();
	var allDivTags=document.getElementsByTagName("div");
	var tempArray = new Array();
	var tempCounter = 0;
	
	for (i=0; i<allDivTags.length; i++) {
		if(allDivTags[i].className == theClass){
			tempArray[tempCounter] = allDivTags[i];
			tempCounter++;
		}
	}
	
	return tempArray;
}

var t;


function hideMenu(id){
	var menu = document.getElementById('mainNavMenu_' + id);
	if(menu){
		menu.style.display = 'none';
	}
}

function EmptyField(nam)
{
	var nam = document.getElementById(nam)
	//nam.onfocus =  function()
	//{
		nam.value = '';
	//}
}

function expandRecipeSearch(){
	
	var keyword = document.getElementById("keyword1");
	document.getElementById("keyword2").value = keyword.value;
	keyword.value = '';
	
	var brand = document.getElementById("brand1");
	document.getElementById("brand2").selectedIndex = brand.selectedIndex;
	brand.selectedIndex = 0;
	
	document.getElementById("blockTitle1").style.display = 'none';
	document.getElementById("blockTitle2").style.display = 'block';
	
}

function expandResponse(){
	
	if( xmlHttp.readyState == 4 ){
		var titleDiv = document.getElementById("blockTitle");
		titleDiv.innerHTML = xmlHttp.responseText;
	}
}

function closeRecipeSearch(){
	
	var keyword = document.getElementById("keyword2");
	document.getElementById("keyword1").value = keyword.value;
	keyword.value = '';
	
	var brand = document.getElementById("brand2");
	document.getElementById("brand1").selectedIndex = brand.selectedIndex;
	brand.selectedIndex = 0;
	
	document.getElementById("course").selectedIndex = 0;
	document.getElementById("ingredient").selectedIndex = 0;
	document.getElementById("prepTime").selectedIndex = 0;
	document.getElementById("featured").checked = false;
	
	document.getElementById("blockTitle1").style.display = 'block';
	document.getElementById("blockTitle2").style.display = 'none';
	
}

function printRecipe(id){
	
	window.open("/UserMods/_siteTemplatePrintRecipe.asp?recipe=" + id,"Print Recipe","width=635,height=300,menubar=no,status=no,location=no,toolbar=no,scrollbars=yes");	
	
}

function matchRecipeContainerHeights(){
		/*NOTE TO SELF*/
		/*The offsetHeight property combines the margin,border,and padding of an element but is a read only property*/
		var nutrition = document.getElementById("nutritionContent");
		var main = document.getElementById("recipeContent");
		
		//If both elements are being pushed down
		if(nutrition.offsetHeight > 350 && main.offsetHeight > 420){
		
			//If both elements are being pushed down, the first thing we have to do is determine which element is being pushed down by a greater amount
			var nutritionDif = nutrition.offsetHeight - 350;
			var mainDif = main.offsetHeight - 420;
			
			//If the main container is being pushed down farther, then me must push down the nutrition container to match
			if(mainDif > nutritionDif){
				nutrition.style.height = (120 + (main.offsetHeight - 420)) + "px";
			
			//If the nutrition container is being pushed down farther, then we must push down the main container to match
			}else if(nutritionDif > mainDif){
				main.style.height = (420 + (nutrition.offsetHeight - 350)) + "px";
			}
		
		//If the main container is being pushed down, but not the nutrition container
		}else if(main.offsetHeight > 420){	
			nutrition.style.height = (120 + (main.offsetHeight - 420)) + "px";
			
		//If the nutrition container is being pushed down but not the main container
		}else if(nutrition.offsetHeight > 350){
			main.style.height = (420 + (nutrition.offsetHeight - 350)) + "px";
		}		
	
}

var currentProductBeingViewed = 1;
var currentNumberOfProducts = 3;


function moveProductsLeft(){
	
	if(currentProductBeingViewed > 1){
		currentProductBeingViewed -= 1;
		if(currentProductBeingViewed == 1){
			document.getElementById("leftButton").className = "disabled";
		}
		
		$("#productSlider").animate({"left": "+=90px"}, "slow");
		
		
		
		//If we are able to slide left, then we should be able to slide back to the right, make sure the right button is enabled
		var rightButton = document.getElementById("rightButton");
		//Return the opacity to normal level
		rightButton.className = "";
		//Activate the button
		rightButton.onclick = function(){
			moveProductsRight();	
		}
	}else{
		
	}
}

function moveProductsRight(){
	
	if((currentProductBeingViewed + 2) < currentNumberOfProducts){
		currentProductBeingViewed += 1;
		if((currentProductBeingViewed + 2) == currentNumberOfProducts){
			document.getElementById("rightButton").className = "disabled";
		}
	
		
		$("#productSlider").animate({"left": "-=90px"}, "slow");
		
		
		
		//If we are able to slide right, then we should be able to slide back to the left, make sure the lefts button is enabled
		var leftButton = document.getElementById("leftButton");
		//Return the opacity to normal level
		leftButton.className = "";
		//Active the button
		leftButton.onclick = function(){
			moveProductsLeft();	
		}
	}else{
		
	}
	
}


function moveProductsLeft_old(){
	
	//Slide Left
	$("#productSlider").animate({"left": "+=90px"}, "slow");
	
	//Get the total number of products, if it has not been set already
	if(productCount == -1){
		checkAJAX2();
		var url = "/Scripts/ajax/productCount.ajax.asp";
		url += "?action=total";
		xmlHttp2.onreadystatechange = totalProducts;
		xmlHttp2.open("GET",url,true);
		xmlHttp2.send(null);
	}
	
	checkAJAX();
	
	//Decrement the current product variable by one
	var url = "/Scripts/ajax/productCount.ajax.asp";
	url += "?action=decrement";
	xmlHttp.onreadystatechange = decrement;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	//If we are able to slide left, then we should be able to slide back to the right, make sure the right button is enabled
	var rightButton = document.getElementById("rightButton");
	//Return the opacity to normal level
	rightButton.className = "";
	//Activate the button
	rightButton.onclick = function(){
		moveProductsRight();	
	}
	
	

}

function moveProductsRight_old(){
	
	$("#productSlider").animate({"left": "-=90px"}, "slow");
	
	//Get the total number of products, if it has not been set already
	if(productCount == -1){
		checkAJAX2();
		var url = "/Scripts/ajax/productCount.ajax.asp";
		url += "?action=total";
		xmlHttp2.onreadystatechange = totalProducts;
		xmlHttp2.open("GET",url,true);
		xmlHttp2.send(null);
	}
	
	checkAJAX();
	
	//Increment the current product variable by one
	var url = "/Scripts/ajax/productCount.ajax.asp";
	url += "?action=increment";
	xmlHttp.onreadystatechange = increment;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	//If we are able to slide right, then we should be able to slide back to the left, make sure the lefts button is enabled
	var leftButton = document.getElementById("leftButton");
	//Return the opacity to normal level
	leftButton.className = "";
	//Active the button
	leftButton.onclick = function(){
		moveProductsLeft();	
	}
}


function getProductInfo(productID){
	
	checkAJAX();
	
	var url = "/Scripts/ajax/products.ajax.asp";
	url += "?id="+productID;
	url += "&action=info";
	xmlHttp.onreadystatechange = outputProductInfo;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}

function outputProductInfo(){
	
	if( xmlHttp.readyState == 4 ){	
		document.getElementById("text").innerHTML = xmlHttp.responseText;
	}
	
}

function getProductTips(productID){
	
	checkAJAX();
	
	var url = "/Scripts/ajax/products.ajax.asp";
	url += "?id="+productID;
	url += "&action=tips";
	xmlHttp.onreadystatechange = outputProductTips;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}

function outputProductTips(){
	
	if( xmlHttp.readyState == 4 ){	
		document.getElementById("text").innerHTML = xmlHttp.responseText;
	}
	
}

function getComparisonInfo(productID){
	
	checkAJAX();
	
	var url = "/Scripts/ajax/products.ajax.asp";
	url += "?id="+productID;
	url += "&action=compare";
	xmlHttp.onreadystatechange = outputComparisonInfo;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}

function outputComparisonInfo(){
	
	if( xmlHttp.readyState == 4 ){	
		var tempArray = xmlHttp.responseText.split("/*Roman kicks ass*/")	
		document.getElementById("text").innerHTML = tempArray[0];
		document.getElementById("comparisonBottle").innerHTML = tempArray[1];
	}
}

//Set the total product count
function totalProducts(){
	if( xmlHttp2.readyState == 4 ){
		productCount = xmlHttp2.responseText;
	}
}

//Set the current product
function increment(){
	if( xmlHttp.readyState == 4 ){
		currentProduct = xmlHttp.responseText;
	
		//If the current product has just been incremented, that means that the product viewer just slid right
		//Now we have to determine if the right button should still be enabled or not based on the total product count and the current count
		if(productCount - currentProduct <= 3){
			var rightButton = document.getElementById("rightButton");
			//set opacity
			rightButton.className = "disabled";
			//diable functionality
			rightButton.onclick = "";
		}
	}
}

//Set the current product
function decrement(){
	if( xmlHttp.readyState == 4 ){
		currentProduct = xmlHttp.responseText;
	
		//If the current product has just been decremented, that means that the product viewer just slid left
		//Now we have to determine if the left button should still be enabled or not based on the total product count and the current count
		if((productCount - currentProduct) == productCount){
			var leftButton = document.getElementById("leftButton");
			//set opacity
			leftButton.className = "disabled";
			//diable functionality
			leftButton.onclick = "";
		}
	}
}

function showMapLocation(location){
	
	//Close any popups that are already open
	var tempArray = getByClass("mapLocationPopup")
	for (i=0; i<tempArray.length; i++){
		if(tempArray[i].style.display == "block"){
			//IE can not handle opacity with transparent images, so just hide the popup without the fade out
			if(navigator.appName == "Microsoft Internet Explorer"){
				$(tempArray[i]).hide();
				$(tempArray[i]).width(0);
				
			//Fade Out
			}else{
				$(tempArray[i]).fadeOut("slow");
			}
			break;
		}
	}
	
	//IE can not handle opacity with transparent images, so just use a different animation that doesnt involve opacity
	if(navigator.appName == "Microsoft Internet Explorer"){
		$("#"+location+"Popup").width(0);
		$("#"+location+"Popup").animate({width: '+=351px'}, "slow");
		
	//Fade In
	}else{
		$("#"+location+"Popup").fadeIn("slow");
	}	
	
}

function hideMapLocation(location){
	
	//IE can not handle opacity with transparent images, so just hide the popup without the fade out
	if(navigator.appName == "Microsoft Internet Explorer"){
		$("#"+location+"Popup").hide();
		$("#"+location+"Popup").width(0);
		
	//Fade Out
	}else{
		$("#"+location+"Popup").fadeOut("slow");
	}	
	
}

function viewResults(pageNumber){
	
	var tempArray = getByClass("resultContainer");
	
	for (i=0; i<tempArray.length; i++){
		if(tempArray[i].style.display == "block"){
			tempArray[i].style.display = "none";
			break;
		}
	}
	
	document.getElementById("resultContainer_" + pageNumber).style.display = "block";
	document.getElementById("selectedNavTop").selectedIndex = pageNumber - 1;
	document.getElementById("selectedNavBottom").selectedIndex = pageNumber - 1;
	location.replace('?action=search#'+pageNumber);
}

function viewResultsNext(){
	
	var tempArray = getByClass("resultContainer");
	var currentNum;
	
	for (i=0; i<tempArray.length; i++){
		if(tempArray[i].style.display == "block"){
			innerArray = tempArray[i].id.split("_");
			currentNum = parseInt(innerArray[1]);
			break;
		}
	}
	
	var next = document.getElementById("resultContainer_" + (currentNum + 1));
	
	if(next){
		document.getElementById("resultContainer_" + currentNum).style.display = "none";
		next.style.display = "block";
		document.getElementById("selectedNavTop").selectedIndex = currentNum;
		document.getElementById("selectedNavBottom").selectedIndex = currentNum;
	}
	location.replace('?action=search#'+(currentNum + 1));
	
}

function viewResultsBack(){
	
	var tempArray = getByClass("resultContainer");
	var currentNum;
	
	for (i=0; i<tempArray.length; i++){
		if(tempArray[i].style.display == "block"){
			innerArray = tempArray[i].id.split("_");
			currentNum = parseInt(innerArray[1]);
			break;
		}
	}
	
	var prev = document.getElementById("resultContainer_" + (currentNum - 1));
	
	if(prev){
		document.getElementById("resultContainer_" + currentNum).style.display = "none";
		prev.style.display = "block";
		document.getElementById("selectedNavTop").selectedIndex = currentNum - 2;
		document.getElementById("selectedNavBottom").selectedIndex = currentNum - 2;
	}
	location.replace('?action=search#'+ (currentNum -1) );
	
}

//Initiate AJAX to unsubscribe from email list
function UnsubscribeRecipe(action)
{
	var email = document.getElementById("em").value
	checkAJAX();
	var url = "/Scripts/Ajax/unsubscribe.ajax.asp";
	url += "?email="+email;
	url += "&action="+action;
	xmlHttp.onreadystatechange = UnsubscribeUpdate;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

//Output response based on server request for removal from email list
function UnsubscribeUpdate()
{
	if( xmlHttp.readyState == 4 ){	
		document.getElementById('displayInfo').innerHTML = xmlHttp.responseText;
	}
}

function changeLanguage(language){

	//var tempArray = getByClass("TranslatorText");
//	
//	for (i=0; i<tempArray.length; i++){
//		if(tempArray[i].style.display == "block"){
//			$("#"+tempArray[i]).hide("slow");
//			//tempArray[i].style.display = "none"
//			break;
//		}
//	}
	$("div[class^=TranslatorText]").hide("slow");
	
	switch(language){
	
		case "Chinese":
			//document.getElementById("ChineseText").style.display = "block";
			$("#ChineseText").show("slow");
			break;
		case "English":
			//document.getElementById("EnglishText").style.display = "block";
			$("#EnglishText").show("slow");
			break;
		case "French":
			//document.getElementById("FrenchText").style.display = "block";
			$("#FrenchText").show("slow");
			break;
		case "Japanese":
			//document.getElementById("JapaneseText").style.display = "block";
			$("#JapaneseText").show("slow");
			break;
		case "Korean":
			//document.getElementById("KoreanText").style.display = "block";
			$("#KoreanText").show("slow");
			break;
		case "Spanish":
			//document.getElementById("SpanishText").style.display = "block";
			$("#SpanishText").show("slow");
			break;
		
	}
	
}


function getStores(stateID){
	
	$("#stores").fadeOut("fast");

	
	checkAJAX();
	
	var d = new Date()
	
	var url = "/Scripts/ajax/storeLocator.ajax.asp";
	url += "?stateID="+stateID;
	url += "&time=compare"+d.getTime();
	
	xmlHttp.onreadystatechange = outputStores;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
	document.getElementById("stateSelect").selectedIndex = stateID;
	
}

function outputStores(){
	if( xmlHttp.readyState == 4 ){	
		document.getElementById("stores").innerHTML = xmlHttp.responseText;
		$("#stores").fadeIn("fast");

	}
}

