var totalResults = 0;
var containerWidth = 0;
var colCount = 0;
var currentCol = 0;

$(document).ready(initWindow);

function initWindow(){
	bindArrows();
	setContainerWidth();
	initRollovers();
	
	for(var i=0; i < $('.appCheckBox').length; i++){
		$('.appCheckBox').eq(i).bind('click', function(){getProductsFromApp(this);});		
	}
	
	var ProductLoadingImg = $("#ProductLoadingImg");
	ProductLoadingImg.animate({opacity: 0.0},0);
	//alert(ProductLoadingImg.attr("title"));
}
/*
================================
WINDOW SCROLL
================================
*/
function bindArrows(){
	$("#leftArrow").bind("click", function(){scrollResults('left');});
	$("#rightArrow").bind("click", function(){scrollResults('right');});
}
function unbindArrows(){
	$("#leftArrow").unbind();
	$("#rightArrow").unbind();
}

function setContainerWidth(){
	colCount = (totalResults/2);
	containerWidth = Math.ceil(colCount) * 108;
	if(colCount >= 4){
		currentCol = 4;	
	}
	else{
		currentCol = colCount;
	}
	$('#resultColContainer').css('marginLeft','0');
	if(containerWidth !== 0){
		$("#resultColContainer").css("width", containerWidth+"px");
	}else{
		$("#resultColContainer").css("width", "250px");
	}
}

function scrollResults(direction){
	var currMargin = parseFloat($('#resultColContainer').css("marginLeft"));
	var newFirst = parseInt($('#resultSetFirst').html());
	var newLast = parseInt($('#resultSetLast').html());
	switch (direction){
		case 'left':
			if(currMargin !== 0){
				unbindArrows();
				$('#resultColContainer').animate({marginLeft:"+=" + 108 + "px"}, 300, function(){bindArrows();});
				newFirst -=2;
				newLast -=2;
				currentCol -=1;
			}
			break;
		case 'right':
			//(containerWidth - ((-1)*(currMargin))) !== 432
			if(currentCol < colCount && colCount > 4){
				unbindArrows();
				$('#resultColContainer').animate({marginLeft:"-=" + 108 + "px"}, 300, function(){bindArrows();});
				newFirst +=2;
				newLast +=2;
				currentCol +=1;
			}
			break;
	}
	
	$('#resultSetFirst').html(newFirst);
	if(newLast >= totalResults){
		$('#resultSetLast').html(totalResults);
	}
	else{
		$('#resultSetLast').html(newLast);
	}
}

/*
===================
Tab Events
===================
*/
var that;
function initRollovers(){
	$("#detailsnavigation li").bind("mouseenter", function(){
		rollOver(this);	
	});
	$("#detailsnavigation li").bind("mouseleave", function(){
		rollOut(this);	
	});
}
function rollOver(obj){
	if ($(obj).hasClass('current')){
		that = obj;
		return;
	}
	$(obj).addClass('current');
}
function rollOut(obj){
	if ($(that).hasClass('current')){
		that = null;
		return;	
	}
	$(obj).removeClass('current');
}

var currProdDiv = '#OverviewDiv';
var currProdDetailTab = '#OverviewTab';
function showProdTab(tabContent, tabID){
	if(currProdDiv != tabContent){
		$(currProdDetailTab).removeClass("current");
		$(tabID).addClass("current");
		rollOver(tabID);
		$(currProdDiv).fadeOut('fast', function(){
			$(tabContent).fadeIn('fast');
			
		});
		currProdDiv = tabContent;
		currProdDetailTab = tabID;
	}
}

/*
=========================
Check Boxes
=========================
*/
function catCheckBox(img, checkbox, label){
	var catInputLength = $("#cateogrySearchContent input").length;
	var catContentImg = $("#cateogrySearchContent img");
	var catContentInput = $("#cateogrySearchContent input");
	if($(checkbox).attr("checked")){
		checkBox(img, checkbox);
		$("#cateogrySearchCriteria").html('');
	} else{
		unCheckAll(catInputLength, catContentImg, catContentInput);
		checkBox(img, checkbox);
		$("#cateogrySearchCriteria").html($(label).html());
	}
	
	var appInputLength = $("#applicationSearchContent input").length;
	var appContentImg = $("#applicationSearchContent img");
	var appContentInput = $("#applicationSearchContent input");
	unCheckAll(appInputLength, appContentImg, appContentInput);
	
	killEmptyApps();
	runSearch();
}

function killEmptyApps(){
	$.ajax({
		type: "POST",
		url: "/_commongoal/cg_content/Products_ajax.cfc",
		dataType: "json",
		data: {
		   method: 'getApplicationsByCategory',
		   category: $("input[name='categoryCk']:checked").val()
		   //currentlySelectedApplications: $("input[@name='applicationsSelected']:checked").getValue()
		},
		success: processAppList
	})	
}

var processAppList = function(results){
	//receives apps with associated products from checked category
	//disable ones that don't have associated products
	$('.appLabel').removeClass('disabled');
	$('.appLabel').removeClass('enabled');
	updateApplicationSearchCriteria();
	enableAppClicks();
	
	$.each(results, function(i, currentApplication) {
		$('#app'+currentApplication.ID+'Lab').addClass('enabled');
		$('#app'+currentApplication.ID+'Img').addClass('enabled');
	});
	disableAppClicks();
}

function enableAppClicks(){
	$('.appLabel').removeClass('disabled');
	$('.appLabel').removeClass('enabled');
	$('.appImg').removeClass('disabled');
	$('.appImg').removeClass('enabled');
	//ADD LABEL CLICKS
	for(var i=0; i<$('.appLabel').length; i++){
		var currentID = $('.appLabel:eq('+i+')').attr('id');
		//$('#'+currentID+'').bind('click', function(){getProductsFromApp(this);});	
		$('#'+currentID+'').show();
	}
	//ADD IMAGE CLICKS
	for(var i=0; i<$('.appImg').length; i++){
		var currentID = $('.appImg:eq('+i+')').attr('id');
		//$('#'+currentID+'').bind('click', function(){getProductsFromApp(this);});
		$('#'+currentID+'').show();
	}
}

function disableAppClicks(){
	for(var i=0; i<$('.appLabel').length; i++){
		var currentID = $('.appLabel:eq('+i+')').attr('id');
		if($('#'+currentID).hasClass('enabled') == false){
			$('#'+currentID+'').addClass('disabled');
			//$('#'+currentID+'').unbind();
			$('#'+currentID+'').hide();
		}
	}
	for(var i=0; i<$('.appImg').length; i++){
		var currentID = $('.appImg:eq('+i+')').attr('id');
		if($('#'+currentID).hasClass('enabled') == false){
			$('#'+currentID+'').addClass('disabled');
			//$('#'+currentID+'').unbind();
			$('#'+currentID+'').hide();
		}
	}
	
}


function getProductsFromApp(evt){
	var appId = $(evt).attr('appId');
	var img = '#app'+appId+'Img';
	var checkbox = '#app'+appId+'Ck';	
	var parentID = $(evt).attr('parentID');
	var label = '#app'+appId+'Lab';												   
	appCheckBox(img, checkbox, parentID, label);				
}

function appCheckBox(img, checkbox, parentID, label){
	var appInputLength = $("#applicationSearchContent input").length;
	var appContentImg = $("#applicationSearchContent img");
	var appContentInput = $("#applicationSearchContent input");
	
	$("#applicationSearchCriteria").html('');
	
	var parentClicked = false;
	if($(checkbox).attr('parentID') !== '0' && $(checkbox).attr('parentID') !== undefined){
		parentClicked = true;
	}
	var childClicked = false;
	if($(checkbox).hasClass("child"+parentID+"")){
		childClicked = true;
		
	}
	//this means it was just a regular application clicked
	var appClicked = false;
	if(childClicked == false && parentClicked == false){
		appClicked = true;
	}
	
	if(parentClicked){
		var currentParent = $(""+checkbox+"").attr("parentid");
		//check to see if this parent is on, if it's already on, turn off all it's childrene
		if($(checkbox).attr("checked")){
			checkBox(img, checkbox);
			toggleChildren('off', currentParent);
		}
		else{
			checkBox(img, checkbox);
			toggleChildren('on', currentParent);	
		}
	}
	else if(childClicked){
		//check the child
		checkBox(img, checkbox);
		//if parent is off - check it.
		if($("input[parentid='"+parentID+"']").attr("checked")){
			
		}
		//if parent is on - do nothing
	}
	else if(appClicked){
		checkBox(img, checkbox);	
	}
	
	/*if(childClicked){
		$("#app"+parentID+"Img").attr("src", "/graphics/"+currentLang+"/Global/checkBoxOn.gif");	
		$("#app"+parentID+"Ck").attr("checked", true);		
		var childLength = $("input.child"+parentID+"").length;
			var childApplicationList = new Array();
			for(var i=0; i<childLength; i++){
				if($("input.child"+parentID+"").eq(i).attr("checked")){
					if(i !== childLength -1){
						$("#applicationSearchCriteria").append( $("label.child"+parentID+"").eq(i).html() +", " );
					} else{
						$("#applicationSearchCriteria").append( $("label.child"+parentID+"").eq(i).html() );
					}
				}
			}
		
	}*/
	
	
	//checkBox(img, checkbox);
	updateApplicationSearchCriteria();
	runSearch();


	/*//it's a parent
	if(parentClicked){
		var currentParent = $(""+checkbox+"").attr("parentid");
		//is the parent on?
		if($(checkbox).attr("checked")){
			//yes it's on - turn everything off
			unCheckAll(appInputLength, appContentImg, appContentInput);
			$("#applicationSearchCriteria").html('');
		} else{
			//no, uncheck everything turn it on and its children
			unCheckAll(appInputLength, appContentImg, appContentInput);
			$("img.child"+currentParent+"").attr("src", "/graphics/"+currentLang+"/Global/checkBoxOn.gif");	
			$("input.child"+currentParent+"").attr("checked", true);
			checkBox(img, checkbox);
			//update application search criteria
			var childLength = $("input.child"+currentParent+"").length;
			var childApplicationList = new Array();
			for(var i=0; i<childLength; i++){
				if(i !== childLength -1){
					$("#applicationSearchCriteria").append( $("label.child"+currentParent+"").eq(i).html() +", " );
				} else{
					$("#applicationSearchCriteria").append( $("label.child"+currentParent+"").eq(i).html() );
				}
			}
		}
	}
	else if(childClicked){
		if(childClicked){
			//yes
			//is it a different parent?
			if($("input[parentid='"+parentID+"']").attr("checked")){
				//no - check child
				checkBox(img, checkbox);
			} else{
				//yes - uncheck them all, check new parent, check child
				unCheckAll(appInputLength, appContentImg, appContentInput);
				$("#app"+parentID+"Img").attr("src", "/graphics/"+currentLang+"/Global/checkBoxOn.gif");	
				$("#app"+parentID+"Ck").attr("checked", true);
				checkBox(img, checkbox);
			}
			var childLength = $("input.child"+parentID+"").length;
			var childApplicationList = new Array();
			for(var i=0; i<childLength; i++){
				if($("input.child"+parentID+"").eq(i).attr("checked")){
					if(i !== childLength -1){
						$("#applicationSearchCriteria").append( $("label.child"+parentID+"").eq(i).html() +", " );
					} else{
						$("#applicationSearchCriteria").append( $("label.child"+parentID+"").eq(i).html() );
					}
				}
			}
		}
		
	}
	if(appClicked){
		if($(checkbox).attr("checked")){
			checkBox(img, checkbox);
			$("#applicationSearchCriteria").html('');
			
		} else{
			unCheckAll(appInputLength, appContentImg, appContentInput);
			checkBox(img, checkbox);
			$("#applicationSearchCriteria").html($(label).html());
		}
	}
	*/

}

function toggleChildren(onOff, currentParent){
	switch(onOff){
		case 'off':
			$("img.child"+currentParent+"").attr("src", "/graphics/"+currentLang+"/Global/checkBoxOff.gif");	
			$("input.child"+currentParent+"").attr("checked", false);
			break;
		case 'on':
			$("img.child"+currentParent+"").attr("src", "/graphics/"+currentLang+"/Global/checkBoxOn.gif");	
			$("input.child"+currentParent+"").attr("checked", true);
			break;
	}
}

function updateApplicationSearchCriteria(){
	var appCriteriaHTML = '';
	var currentHost = window.location.host;
	
	
	for(var i = 0; i< $('input.appCheckBox[type=checkbox]:checked').length; i++){
		var cBox = $('input.appCheckBox[type=checkbox]:checked').eq(i);
		var checkedID = cBox.attr('id');
		var checkedIDNum = checkedID.match(/\d{1,}/);
		var applicationsPage = cBox.attr("applicationsPageMenuDisplay");
		var parentLinkPath = cBox.attr("parentLinkPath");
		
		var menuDisplay = cBox.attr('menuDisplay');
		
		menuDisplay = menuDisplay.replace(/&/g, 'and');
		menuDisplay = menuDisplay.replace(/ /g, '');
		menuDisplay = menuDisplay.replace(/,/g, '');
		menuDisplay = menuDisplay.replace(/\//g, '');
		/*menuDisplay = menuDisplay.replace(/�/g, 'a');
		menuDisplay = menuDisplay.replace(/�/g, 'u');
		alert(menuDisplay);
		menuDisplay = menuDisplay.replace('�', 'O');
		
		//if(menuDisplay
		//alert(menuDisplay.search('&Otilde;'));
		//alert(menuDisplay);
		//� - a - �*/
		
		var pre_linkHref = '<a href="' + '/' + applicationsPage +'/' + parentLinkPath + menuDisplay + '" title="">';
		var post_linkHref = '</a>';
		appCriteriaHTML += pre_linkHref + $('#app'+checkedIDNum+'Lab').html() + post_linkHref;
		
		
		if(i !== $('input.appCheckBox[type=checkbox]:checked').length -1){
			appCriteriaHTML += ', ';
		}	
	}
	$('#applicationSearchCriteria').html(appCriteriaHTML);
	//alert(appCriteriaHTML);
}

	
function unCheckAll(appInputLength, appContentImg, appContentInput){
	for(i=0; i<appInputLength; i++){
		$(appContentImg).eq(i).attr("src", "/graphics/"+currentLang+"//Global/checkBoxOff.gif");
		$(appContentInput).eq(i).attr("checked", false)
	}
}

function unCheckAllOtherParentChildren(appInputLength, appContentImg, appContentInput){
	for(i=0; i<appInputLength; i++){
		if($(appContentImg).eq(i).attr("parentid", currentParent)){ 
			$(appContentImg).eq(i).attr("src", "/graphics/"+currentLang+"//Global/checkBoxOff.gif");
			$(appContentInput).eq(i).attr("checked", false)
		}
	}
}

function markParent(parentID){
	$('#app'+parentID+'Ck').attr('parentID', parentID);
	$('#app'+parentID+'Img').attr('parentID', parentID);
}

/*
=======================
Product Overview
=======================


function showOverview(productID, resultNum){
	$('#searchProductDetail').fadeIn('fast');
	$('#searchDetailsContentContainer').addClass('loading');
	$('.resultItem').removeClass('itemSelected');
	$('#result'+resultNum+'').addClass('itemSelected');
	
	$("#productQuickDetails").show("fast", function() { 
		$.ajax({
				type: "POST",
				url: "/_commongoal/cg_content/Products_ajax.cfc",
				dataType: "json",
				data: {
				   method: 'getProductOverview', 
				   productID: productID
				},
			success: processProductDetail_Overview
			});
	});
}

var processProductDetail_Overview = function(results) {
	var ourProduct = results[0];
	$('#overviewName').html(ourProduct.PRODUCTNAME);
	$('#overviewDesc').html(ourProduct.DESCRIPTIONTEXT);
	$('#overviewDesc').truncate(410);
	$('#overviewImg').attr('src','/graphics/userUploads/products/' + ourProduct.PRODUCTIMAGE);
	if($("#productSearch").val() != "Search by Name"){
		var searchString_val = $("#productSearch").val();
	}
	else {
		var searchString_val = "";
	}
	
	var switchToURL = "/Products&productId=";
	switchToURL += ourProduct.PRODUCTID;
	
	switchToURL += "&category=";
	if($("input[name='categoryCk']:checked").val() == null){
		switchToURL += '';
	}
	else{
		switchToURL += $("input[name='categoryCk']:checked").val();
	}
	switchToURL += "&applications=";
	//just getting Checked on Applications will return the parent if one of it's children is selected - get the parent, and children in 	comma seperated list
	switchToURL += generateAppList($("input[name='appCk']:checked").length);
	switchToURL += "&searchString=";
	switchToURL += searchString_val;
	$('#viewCompleteResultsBtn').attr('href',switchToURL);
	
	$('#searchDetailsContentContainer').removeClass('loading');
	$("#overviewContent").fadeIn("fast");
	
}
*/
function resetSearch(){
	var appInputLength = $("#applicationSearchContent input").length;
	var appContentImg = $("#applicationSearchContent img");
	var appContentInput = $("#applicationSearchContent input");
	
	var catInputLength = $("#cateogrySearchContent input").length;
	var catContentImg = $("#cateogrySearchContent img");
	var catContentInput = $("#cateogrySearchContent input");
	
	var cateogrySearchCriteria = $("#cateogrySearchCriteria");
	var applicationSearchCriteria = $("#applicationSearchCriteria");
	
	unCheckAll(catInputLength, catContentImg, catContentInput);
	unCheckAll(appInputLength, appContentImg, appContentInput);
	
	$('#productSearch').val('Search by Name');
	
	$('.checkRow img').css('display', '');
	$('.checkRow label').css('display', '');
	
	cateogrySearchCriteria.html("");
	applicationSearchCriteria.html("");
	
	$('.appLabel').removeClass('disabled');
	runSearch();
}

/*
==================
Search
==================
*/
var runSearch = function(){
	if($("#productSearch").val() != "Search by Name" && $("#productSearch").val() != "" && $("#productSearch").val() != "Suche nach Produktname" && $("#productSearch").val() != "产品名称搜寻"){
		var searchString_val = $("#productSearch").val();
		$.ajax({
			type: "POST",
			url: "/_commongoal/cg_content/Products_ajax.cfc",
			dataType: "json",
			data: {
			   method: 'searchProducts',
			   searchString: searchString_val
			},
			success: processRes
		});
	}
	//if cat is undefined and apps are - submit just apps
	else if($("input[name='categoryCk']:checked").val() == null && $("input[name='appCk']:checked").val()){
		$.ajax({
			type: "POST",
			url: "/_commongoal/cg_content/Products_ajax.cfc",
			dataType: "json",
			data: {
			   method: 'searchProducts',
			   applications: generateAppList($("input[name='appCk']:checked").length)
			},
			success: processRes
		});
	}
	
	//if apps are undefined, and cat is - submit just cats
	else if($("input[name='appCk']:checked").val() == null && $("input[name='categoryCk']:checked").val()){
		$.ajax({
			type: "POST",
			url: "/_commongoal/cg_content/Products_ajax.cfc",
			dataType: "json",
			data: {
			   method: 'searchProducts',
			   category: $("input[name='categoryCk']:checked").val()
			},
			success: processRes
		});
	}
	//if nothing is defined 
	else if($("input[name='categoryCk']:checked").val() == null && $("input[name='appCk']:checked").val() == null){
		$.ajax({
			type: "POST",
			url: "/_commongoal/cg_content/Products_ajax.cfc",
			dataType: "json",
			data: {
			   method: 'searchProducts'
			},
			success: processRes
		});
	}
	//if both are defined, submit both
	else if($("input[name='categoryCk']:checked").val() !== null && $("input[name='appCk']:checked").val() !== null){
		$.ajax({
			type: "POST",
			url: "/_commongoal/cg_content/Products_ajax.cfc",
			dataType: "json",
			data: {
			   method: 'searchProducts',
			   category: $("input[name='categoryCk']:checked").val(),
			   applications: generateAppList($("input[name='appCk']:checked").length)
			},
			success: processRes
		});
	}
}

var processRes = function(results){	
	
	var retProducts = "";
	var newHTML = '';
	var currentRow = 0;
	var currCount = 0;
	
	if(results.length > 0){
		$.each(results, function(i, retProducts){
			
			var switchToURL = "/Products&productId=";
			switchToURL += retProducts.PRODUCTID;
			
			
			
			if($("#productSearch").val() != "Search by Name" && $("#productSearch").val() != "Suche nach Produktname" && $("#productSearch").val() != "产品名称搜寻" ){
				var searchString_val = $("#productSearch").val();
			}
			else {
				var searchString_val = "";
			}
			
			switchToURL += "&category=";
			if($("input[name='categoryCk']:checked").val() == null){
				switchToURL += '';
			}
			else{
				switchToURL += $("input[name='categoryCk']:checked").val();
			}
			switchToURL += "&applications=";
			//just getting Checked on Applications will return the parent if one of it's children is selected - get the parent, and children in 	comma seperated list
			switchToURL += generateAppList($("input[name='appCk']:checked").length);
			switchToURL += "&searchString=";
			switchToURL += searchString_val;
			
			
			var modRes = ((i+1) % 3);
			if( modRes == 1){
				newHTML += '<div class="resultCol">';
				newHTML += '<div class="resultItem" id="result'+i+'">';
				
				newHTML += '<div class="resultImgContainer"><a href="'+switchToURL+'"><img src="/graphics/userUploads/products/'+retProducts.IMAGE_THUMB+'" alt="'+retProducts.PRODUCTNAME+'" class="productResultImg" /></a></div>';
				newHTML += '<p class="productName"><a href="'+switchToURL+'">'+retProducts.PRODUCTNAME+'</a></p>';
				newHTML += '</div>';
			}
			else if( modRes == 2){
				newHTML += '<div class="resultItem" id="result'+i+'">';
				
				newHTML += '<div class="resultImgContainer"><a href="'+switchToURL+'"><img src="/graphics/userUploads/products/'+retProducts.IMAGE_THUMB+'"alt="'+retProducts.PRODUCTNAME+'" class="productResultImg" /></a></div>';
				newHTML += '<p class="productName"><a href="'+switchToURL+'">'+retProducts.PRODUCTNAME+'</a></p>';
				newHTML += '</div>';
			}
			else if( modRes == 0){
				newHTML += '<div class="resultItem" id="result'+i+'">';
				
				newHTML += '<div class="resultImgContainer"><a href="'+switchToURL+'"><img src="/graphics/userUploads/products/'+retProducts.IMAGE_THUMB+'"alt="'+retProducts.PRODUCTNAME+'" class="productResultImg" /></a></div>';
				newHTML += '<p class="productName"><a href="'+switchToURL+'">'+retProducts.PRODUCTNAME+'</a></p>';
				newHTML += '</div>';
				newHTML += '</div>';
			}
		});
		$('#resultColContainer').html(newHTML);
		updateShowingDisplay(results.length);
	}
	else{
		newHTML+='<div id="resultColContainer" style="margin-left: 0pt; width: 216px;">No products found matching your search.</div>';
		$('#resultPane').html(newHTML);
		updateShowingDisplay(results.length);
	}
	totalResults = results.length;
	setContainerWidth();
}



function generateAppList(length){
	var list ='';
	for(j = 0; j < length; j++){
		list += $("input[name='appCk']:checked").eq(j).val();
		if(j !== length-1){
			list += ',';
		}
	}	
	return list;
}

function updateShowingDisplay(total){
	$('#totalResults').html(total);
	$('#resultSetFirst').html('1');
	if(total < 13 && total !==0){
		$('#resultSetLast').html(total);
	}
	else{
		$('#resultSetLast').html('12');	
	}
	if(total == 0){
		$('#totalResults').html('0');	
		$('#resultSetFirst').html('0');
		$('#resultSetLast').html('0');
	}
}

function prodSearchBtn() {
	runSearch();
}
function searchInputEnterKey(evt, inputVal){
	evt = (evt) ? evt : ((event) ? event : null);
	if (evt) {
		if(evt.keyCode == 13){
			runSearch();
		}
	}
}

function populateSearchCriteriaCat(id){
	$("#cateogrySearchCriteria").html($("#cat"+id+"Lab").html());
	killEmptyApps();
}

function populateSearchCriteriaApp(id){
	var values = new Array;
	values = id.split(',');
	for(var i=0; i<values.length; i++){
		if(i !== values.length -1){
			$("#applicationSearchCriteria").append( $("#app"+values[i]+"Lab").html() +", " );
		} else{
			$("#applicationSearchCriteria").append( $("#app"+values[i]+"Lab").html() );
		}
	}
}
