/* new attribute array */
var queryString = "";
var sortKey = "RELV";
if (document.cookie.length>0){
	qs = getCookie("qs");
	//alert(qs);
	if (qs == null) {
		
	}
	else{
		if(qs.length > 0){
			queryString = qs;	
		}
	}
}
var GB_ANIMATION = true;

$(document).ready(function(){

	$().ready(function() {
	  $('#dialog').jqm();
	});
	
	
	$("a.greybox").click(function(){
	  var t = this.title || this.innerHTML || this.href;
	  GB_show(t,this.href,500,500);
	  return false;
	});
    
	
	
	timestamp = 0;
	$.post("mccdata.jsp",{
				mtype: $("input[@name=mtype]:checked").val(),	
				time: timestamp,
				query: queryString,
				sortby: sortKey 
			}, function(xml) {
		$("#productlist").empty();
		addAttributes(xml);
		addProducts(xml);
	}, "xml");
	
});
function addProducts(xml) {
	var currency = "$";
	if($("status",xml).text() == "ERROR") {
		$("#productlist").text("");
		$("#productlistheader").text("");
		$("#productlistheader").append("No criteria selected...");
		return;
	}else if($("status",xml).text() == "EMPTY") {
		$("#productlist").text("");
		$("#productlistheader").text("");
		$("#productlistheader").append("No products match the criteria selected...");
		queryString = "";
		return;
	}
	timestamp = $("time",xml).text();
	productsReturned = $("productsReturned",xml).text();
	$("#productlist").text("");
	//$("#productlist").append("<table cellpadding='2' cellspacing='2' border='10'>");	
	
	$("#productlistheader").text(productsReturned + " products returned");	
	
	
	producthtml = "<form action='/controller.jsp' method='post'>";
	producthtml += "<input type='hidden' name='action' id='action' value='CompareMCC' />";
	producthtml += "<table cellpadding='2' cellspacing='2' border='0' width='100%'>";
	producthtml += "<tr><td colspan='2'><input type='submit' value='Compare Products' /></td>";
	producthtml += "<td colspan='2' align='right'>";
	producthtml += "<span class='sortByLabel'>Sort By</span>&nbsp;";
	producthtml += "<select class='sortByDropdown' name='sort' onChange='changeSortKey(this.options[this.selectedIndex].value);'>";
	if($("sortKey",xml).text() == "RELV") {
		producthtml += "<option value='RELV' selected='selected'>Relevance</option>";	
	}else{
		producthtml += "<option value='RELV'>Relevance</option>";
	}
	if($("sortKey",xml).text() == "ALPH") {
		producthtml += "<option value='ALPH' selected='selected'>Alphabetical: A to Z</option>";
	}else{
		producthtml += "<option value='ALPH'>Alphabetical: A to Z</option>";
	}
	if($("sortKey",xml).text() == "PASC") {
		producthtml += "<option value='PASC' selected='selected'>Price: Low to High</option>";
	}
	else{
		producthtml += "<option value='PASC'>Price: Low to High</option>";	
	}
	if($("sortKey",xml).text() == "PDESC") {
		producthtml += "<option value='PDESC' selected='selected'>Price: High to Low</option>";
	}else{
		producthtml += "<option value='PDESC'>Price: High to Low</option>";	
	}
	producthtml += "</select>";
	producthtml += "</td></tr>";
	producthtml += "<tr>";
		producthtml += "<td colspan='4' class='productdivide'>";
		producthtml += "</td>";
		producthtml += "</tr>";
	
	$("product",xml).each(function(id) {
		product = $("product",xml).get(id);
		productCode = $("objectName",product).text();
		producthtml += "<tr>";
		producthtml += "<td width='30'><input type='checkbox' name='pcodes' value='" + productCode + "' /></td>";
		producthtml += "<td rowspan='1' valign='top'><a href='/productid/" + productCode + "/1/0/" + productCode + ".html'><img src='/mcc/photos_85/" + $("thumbnail",product).text() + "' alt='" + productCode + "' border='0'></a></td>";
		producthtml += "<td valign='top' >";
		producthtml += "<img src='/images/clearpixel.gif' width='1' height='2' alt='' border='0'>";
		producthtml += "<br><strong>Product Code: </strong><a href='/productid/" + productCode + "/1/0/" + productCode + ".html'>" + productCode + "</a>";
		producthtml += "<br /><span style='font: normal 11px/14px verdana,helvetica,san-seif;'>" + $("description",product).text() + "</span>";
		producthtml += "</td>";
		producthtml += "<td valign='top' style='padding:0 0 0 10px; font: normal 11px/14px verdana,helvetica,san-seif;'>";
		producthtml += "<strong>";
		producthtml += "Our price: <span style='color:#c00;'>£&nbsp;" + $("price",product).text() + "&nbsp;</span>";
		producthtml += "<br /><span style='font-weight:normal;'>£&nbsp;" + $("priceIncVat",product).text() + "&nbsp;inc. VAT</span>";
		producthtml += "</strong>";
		producthtml += "<br /><a href='/basket/" + productCode + "/1/add" + productCode + ".html'><img src='/images/buyOnline_1.gif' width='180' height='29' border='0' alt=''></a>";
		producthtml += "</td>";
		producthtml += "</tr>";
		producthtml += "<tr>";
		producthtml += "<td colspan='4' class='productdivide'>";
		producthtml += "</td>";
		producthtml += "</tr>";
	});
	producthtml += "</table></form>";
	$("#productlist").append(producthtml);
}
function addAttributes(xml) {
	if($("status",xml).text() == "2") return;
	timestamp = $("time",xml).text();
	var label = "";
	$("#attributelist").text("");
	$("attribute",xml).each(function(id) {
		attribute = $("attribute",xml).get(id);
		removehtml = "";
		var footprint = $("attributeNameID",attribute).text() + ":" + $("attributeValue",attribute).text() + ":" + $("attributeDataTypeID",attribute).text();
		if(queryString.lastIndexOf(footprint) != -1){
			removehtml = " - <a class='removelink' style='color:#ff0000; font-weight:bold' href='javascript:removeAtrributes(" + $("attributeNameID",attribute).text() + ",\"" + $("attributeValue",attribute).text() + "\"," + $("attributeDataTypeID",attribute).text() + ");'><img src='/images/atick.gif' alt='tick' align='absbottom' /></a>";
		}
		attributehtml = "";
		if($("attributeName",attribute).text() != label){
			attributehtml +=  "<div class='attributelabel'>" + $("attributeName",attribute).text() + "</div>";	
			label = $("attributeName",attribute).text();
		}
		attributehtml += "<div class='attribute'>";
		attributehtml += "<a href='javascript:selectAtrributes(" + $("attributeNameID",attribute).text() + ",\"" + $("attributeValue",attribute).text() + "\"," + $("attributeDataTypeID",attribute).text() + ");'>" + $("attributeValue",attribute).text() + "</a> " + removehtml;
		attributehtml += "</div>";
		attributehtml += "<div style='clear:both'></div>";
		$("#attributelist").append(attributehtml);								
	});
}
function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function changeSortKey(newSortKey){
	sortKey = newSortKey;
	$("#productlist").append("<img src='/images/abigrotation2.gif' alt='Progress' width='32' height='32'><h2>Data loading - please wait...</h2>");
	$.post("mccdata.jsp",{
				mtype: $("input[@name=mtype]:checked").val(),	
				time: timestamp,
				query: queryString,
				sortby: sortKey
			}, function(xml) {
		$("#productlist").empty();
		addAttributes(xml);
		addProducts(xml);
	}, "xml");
	setCookie("qs",queryString,1);
}
function selectAtrributes(atrributeNameID, attributeValue, attributeDataType){			
	if(queryString.length > 0){
		queryString += "#" + atrributeNameID + ":" + attributeValue + ":" + attributeDataType;
	}
	else{
		queryString = atrributeNameID + ":" + attributeValue + ":" + attributeDataType;
	}
	$("#productlist").append("<img src='/images/abigrotation2.gif' alt='Progress' width='32' height='32'><h2>Data loading - please wait...</h2>");
	$.post("mccdata.jsp",{
				mtype: $("input[@name=mtype]:checked").val(),	
				time: timestamp,
				query: queryString,
				sortby: sortKey
			}, function(xml) {
		$("#productlist").empty();
		addAttributes(xml);
		addProducts(xml);
	}, "xml");
	setCookie("qs",queryString,1);
}
function selectAndRedirect(atrributeNameID, attributeValue, attributeDataType){			
	queryString = atrributeNameID + ":" + attributeValue + ":" + attributeDataType;
	setCookie("qs",queryString,1);
	document.location.href = "http://directory.adeptscience.co.uk/mcc-daq.jsp";
}
function removeAtrributes(atrributeNameID, attributeValue, attributeDataType){			
	
	tmpString = atrributeNameID + ":" + attributeValue + ":" + attributeDataType;			
	queryString = queryString.replace(tmpString,"");
	
	if(queryString.substr(0,1) == "#"){
		queryString = queryString.substr(1,queryString.length-1);
	}
	
	if(queryString.substr(queryString.length-1,1) == "#"){
		queryString = queryString.substr(0,queryString.length-1);
	}
	
	queryString = queryString.replace("##","");
	
	queryStringChk = queryString;
	queryStringChk.replace("#","");
	if(queryStringChk.length == 0){
		queryString = "";
	}
	
	$("#productlist").append("<img src='/images/abigrotation2.gif' alt='Progress' width='32' height='32'><h2>Data loading - please wait...</h2>");
	
	$.post("mccdata.jsp",{
				mtype: $("input[@name=mtype]:checked").val(),	
				time: timestamp,
				query: queryString,
				sortby: sortKey
			}, function(xml) {
		$("#productlist").empty();
		addAttributes(xml);
		addProducts(xml);
	}, "xml");
	
	setCookie("qs",queryString,1);
}	
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

