//global variables
var pbDid = 633930; //product browse dattributeid

Ajax.Responders.register({
  onCreate: function(){
    Element.show("loading");
  },
  onComplete: function() {
	Element.hide("loading");
  }
});

function getAmpsPath() {
	return ((window.location.pathname.match(/\//g).length >= 1) ? '../../' : '../');
}

function getAbsPath(site) {
	var host = window.location.host;
	
	if (host == "webq1.insidehli.com" || host == "dev.insidehli.com") {
		//now we have to check to see if we're on the dev or test site (dev is our default db connection)
		if (window.location.pathname.match(/_test/g)) {
			//we're on testing site	
			return 'http://' + host + '/' + site + '_test/';						
		} else {
			//we're on dev (or we're defaulting to dev)
			return 'http://' + host + '/' + site + '_dev/';								
		}//if (window.location.pathname.match(/_test/g))		
	} else if (host == "qa.compasslighting.com") { 
		//we're on qa site
		return 'http://qa.compasslighting.com/'; 
	} else if (host == "foobar") {
		//temporary for foobar
		return 'http://foobar/dev/' + site + '_dev/';
	} else {
		//we're on production site
		return 'http://www.compasslightingproducts.com/'; 
	} //if (host == "webq1.insidehli.com" || host == "dev.insidehli.com") 	
}//function getAbsPath()

//main product browse function, occurs on first click of product browse
function productBrowse() {
	var relPath = getAbsPath('compass');
	var ampsPath = getAmpsPath();
	accessCSS('right-pane-browse').display = 'none';
	accessCSS('right-pane').display = 'block';

	var ulstring = ' <ul>' +
	               '  <li class="selected"><a href="javascript: void(0);" onclick="productBrowse();"><span>Product Browse</span></a></li>' +
				   ' </ul>';
		
	document.getElementById('pbrowse').innerHTML = ulstring;

	document.getElementById('right-pane-browse').innerHTML = '';
	document.getElementById('bottomDiv').innerHTML = '';
	document.getElementById('attSearch1').innerHTML = ''; 
	document.getElementById('prodBrowse').innerHTML = '';
	accessCSS('attSearch1').display = 'none';
	
	if (arguments.length == 1) {
		writeProdBrowseDD(pbDid, 'prodBrowse', relPath, ampsPath, arguments[0]); //write DD starting at top of product browse array
	} else {
		writeProdBrowseDD(pbDid, 'prodBrowse', relPath, ampsPath, '');
	}//if (arguments.length == 1)
	
	accessCSS('prodBrowse').visibility = 'hidden';
	accessCSS('prodBrowse').display = 'block';
	accessCSS('prodBrowse').visibility = 'visible';
}//function productBrowse()

function writeProdBrowseDD(did, divid, relPath, ampsPath) { //arguments[4] (the fifth one) is optional and is the passed in did of the category from url
	var nextdiv = nextDiv('prodBrowse', divid);
	var dd = '<h3><span>Browse Product Type</span></h3>' + 
			 '<select class="select" name="pbrowse" onChange="searchChoice(this, \'' + nextdiv + '\', \'pb\',\'' + relPath + '\',\'' + ampsPath + '\');" />\n' +
			 '<option value="' + did + '">-- All --</option>\n';			 

	var choices = listChildren(did, 'pb');
		
	for (var i = 0; i < choices.length; i++) {						
		if (arguments.length == 5 && choices[i] == arguments[4]) {
			dd += '<option value="' + choices[i] + '" selected>' + PBindex[choices[i]][1] + '</option>\n';
		} else {
			dd += '<option value="' + choices[i] + '">' + PBindex[choices[i]][1] + '</option>\n';
		}//if (arguments.length == 5 && choices[i] == arguments[4])
	}//for (i=0; i < choices.length; i++)
	
	dd += '</select>\n<div id="' + nextdiv + '"></div>\n';	
	$(divid).innerHTML = dd;
	
	if (arguments.length == 5 && arguments[4]) {
		//here we need to get our product list for this category
		ajax('includes/ajax.php', 'getProductsByCategory', arguments[4], nextdiv);		
	}//if (arguments.length == 5 && arguments[4])	
}//function writeProdBrowseDD(did, divid, relPath, ampsPath)

function writeProdBrowseList(did, divid, relPath, ampsPath, data) {
	//PBindex: 
	//  0 - Product vs Category
	//  1 - Left Side Product Name
	//  2 - Real Product Name
	//  3 - Product Page File Name
	//  4 - Subtitle
	//  5 - Product Image
	//  6 - Certification Images
	//  7 - Certification Titles
	
	relPath = getAbsPath('compass'); //get our absolute path (necessary because of url rewriting)
	var filenameArray = window.location.pathname.split('/');	
	var filename = filenameArray[filenameArray.length-2];		

	var prodList = '<div id="browse-list"><ul>';
	var children = listChildren(did, 'pb');

	if (data == "") {
		alert("No data available for the selected category. Please try your request again.");
		productBrowse();
		return;
	}
	
	//parse our json string
	var prodData = JSON.parse(data);
	
	for (var j = 0; j < prodData.products.length; j++) {
		if (filename == prodData.products[j].filename) {//on this product page, don't link and no mouseover event
			prodList += '<li><span>' + prodData.products[j].productName + '</span></li>\n';;
		} else {//not on product page, include mouseover and link
			prodList += '<li onMouseOver=\"showProduct(' + prodData.products[j].did + ',\'' + relPath + '\',\'' + ampsPath + '\',\'' + escape(JSON.stringify(prodData.products[j])) + '\');\" onMouseOut=\"hideProduct(); this.className=\'\';\"><a href=\"' + relPath + 'products/' + prodData.products[j].filename + '/?pbid=' + did + '\">' + prodData.products[j].productName + '</a></li>\n';
		}//if (filename == PBindex[children[i]][3]) 
	}
	
	prodList += '</ul></div>\n';
	$(divid).innerHTML = prodList;			
}//function writeProdBrowseList(did, divid, relPath, ampsPath, data)

function showProduct(did, relPath, ampsPath, prodData) {

	if (prodData == "") {
		alert("No data available for the selected product. Please try your request again.");
		productBrowse();
		return;
	}//if (prodData == "")
	
	//set our prodData (parsing our JSON string)
	var prodData = JSON.parse(unescape(prodData));
		
	//check if relPath is empty, if so its coming from xml, build relpath here
	if (relPath == '') {var relPath = getAbsPath('compass');}//if (relPath == '')
	
	//PBindex: 	
	// 0 - product vs category
	// 1 - Left Side Product Name
	// 2 - Real Product Name
	// 3 - product page file name
	// 4 - subtitle
	// 5 - product image
	// 6 - certifications
	// 7 - product description
	// 8 - product id	

	var prod = '<div id="toolbar-contain">' + 
	           ' <div id="headerText">Product Browse</div>' +
			   '</div>' +
			   '<div class="clear"></div>' +
	           '<div id="content">' +
			   ' <div class="clear"></div>' +
			   ' <div class="pbrowse-bar">';
			   
	//product name			   
	if (prodData.realProductName != 'null') {
	    prod += '<div class="headerRollover">' + prodData.realProductName + '</div>';		
	}//if (prodData.realProductName != 'null')	
			   
	prod += '<div class="clear"></div>';


	//product image	
	if (prodData.productImage != '' && prodData.productImage != 'null') {
	    prod += '<img class="img" src="' + relPath + 'products/images/thumb/' + prodData.productImage + '" alt="product image" />';
	}//if (prodData.productImage != '' && prodData.productImage != 'null')
		
	prod += '<div class="clear"></div>' +
	        '</div><div class="clear"></div>' + 
			'<div class="product-content">';

	//certifications	
	if (prodData.certifications != '' && prodData.certifications != 'null') { 
		prod += '<div class="icons">';
		var certification = explodeArray(prodData.certifications, ',');
		
		for (var i = 0; i < certification.length; i++) {
			if (certification[i] != 'null') {
				prod += '<img src="' + relPath + 'images/certification_icons/' + certification[i] + '"   />';				
			}//if (certification[i] != 'null')
		}//for (var i = 0; i < certification.length; i++)
		prod += '</div><!-- end icons -->';
	}//if (prodData.certifications != '' && prodData.certifications != 'null')

	//description
	if (prodData.productDescription != 'null') {
		prod += '<h4><span>Description</span></h4>' +
		        '<p>' + prodData.productDescription + '</p>';
	}//if (prodData.productDescription != 'null')
	prod += '<div class="clear"></div>';
	
	//prod += '</div>';		
	$('right-pane-browse').innerHTML = prod;
	accessCSS('right-pane').display = 'none';
	accessCSS('right-pane-browse').display = 'block';
}//function showProduct(did, relPath, ampsPath, prodData)

function hideProduct() {
	accessCSS('right-pane-browse').display = 'none';
	accessCSS('right-pane').display = 'block';
	document.getElementById('right-pane-browse').innerHTML = '';
}//function hideProduct()

function searchChoice(myselect, divid, relPath, ampsPath) {
	var selval = myselect.options[myselect.selectedIndex].value
	//don't process if they selected the top select list item ('all')
	if (selval == pbDid) {
		document.getElementById(divid).innerHTML = '';
	} else {
		//if this is a non-product link, open a new window with our url
		if (PBindex[selval][0] == "Non-Product Link") {
			//reset our select menu	
			myselect.selectedIndex = 0;
									
			//reset our div
			document.getElementById(divid).innerHTML = '';											
			
			//open our window
			window.open(PBindex[selval][2]);					
			return;
		} else {				
			//here we need to get our product list for this category
			ajax('includes/ajax.php','getProductsByCategory',selval,divid);
		}//if (PBindex[selval][0] == "Non-Product Link")
	}//if (selval == pbDid)	
}//function searchChoice(myselect, divid, relPath, ampsPath)

function nextDiv(prefix, divid) {
	return prefix + (divid.substring(prefix.length) - 0 + 1);
}//function nextDiv(prefix, divid)

function lastDiv(prefix, divid) {
	return prefix + (divid.substring(prefix.length) - 0 - 1);
}//function lastDiv(prefix, divid)

function listChildren(did, type) {
	return ((type == 'as') ? explodeArray(ASplist[did], ',') : explodeArray(PBplist[did], ','));
}//function listChildren(did, type)

function explodeArray(item,delimiter) {
  var tempArray=new Array(1);
  var Count=0;
  var tempString=new String(item);

  while (tempString.indexOf(delimiter)>0) {
    tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
    tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1); 
    Count=Count+1
  }//while (tempString.indexOf(delimiter)>0)

  tempArray[Count]=tempString;
  return tempArray;
  
}//function explodeArray(item,delimiter)

function accessCSS(layerID) {     
	if(document.getElementById) {
		if(!window.document.getElementById(layerID)) {
			return false;
		} else {
			return document.getElementById(layerID).style;
		}//if(!window.document.getElementById(layerID))
	} else if(document.all) {
		return document.all[layerID].style;
	} else if(document.layers) {
		return document.layers[layerID];
	}//if(document.getElementById)
}//function accessCSS(layerID)

function isUndefined(a) {
    return typeof a == 'undefined';
}//function isUndefined(a)

function ajax(url,theFunction,theParams,divid) {
	//clear our previous prod browse list	
	$(divid).innerHTML = '';

	var success = function(t) {if(t.responseText == ''){alert('No data available for the selected category. Please try your request again.');}}
	var failure = function(t) {alert('No data available for the selected category. Please try your request again.');}
		
	var completed = function(t) {
						writeProdBrowseList(theParams, divid, getAbsPath('compass'), getAmpsPath(),t.responseText);							
					}
						
	url = getAbsPath('compass') + url;
	var pars = 'fnc=' + theFunction + '&params=' + escape('&did=' + theParams + '&site=' + aspb)
	var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onSuccess:success, onFailure:failure, onComplete:completed});							
}