/* $Id: simple_ajax.js 586 2008-08-11 14:03:05Z plegagneur $ */

/**
* @file
* A really bare-bones, simple ajax impl which acts as a wrapper to the drupal.js ajax calls.
*/

//ajax actions
var AJAX_GET_CATEGORIES		= 10;
var AJAX_GET_BRANDS			= 20;
var AJAX_GET_PRODUCT_LINES	= 30;
var AJAX_GET_COLORS			= 40;

//ajax vars (try to minimise these until this is rewritten - bad enough we have all these global vars...
var SimpleAjax; //will hold ajax object.
var AJAX_brandCatForm = '';
var PR_origCategoryOptions;
var PR_flatOptions;
var PR_searchopt = '';
var PR_isIE6 = false;

//IE6 has a dumass problem with accented characters
function checkIE6()
{                
	if(navigator.appName.indexOf("Internet Explorer") != -1)
	{
		var temp=navigator.appVersion.split("MSIE");
		var version=parseFloat(temp[1]);
		if (version == 6)
		{
			PR_isIE6 = true;
		}
	}
}

function ajaxObject()
{
	//we need to keep track of when we're already busy so we can abort; this is needed to stop IE from hanging.
	var updating = false;
	this.update = function (uri, callbackFunction, callbackParameter, object)
	{
		if(updating == true) return false;
		updating = true;

		//wrapper call to drupal ajax impl
		HTTPPost(uri, callbackFunction, callbackParameter, object);
	}
	
	this.release = function ()
	{
		updating = false;
	}
}


//drupal.js requires following prototype:
//callbackFunction(xmlHttp.responseText, xmlHttp, callbackParameter)
function ajaxResponse(responseText, xmlHttpObj, action)
{
	if(action == AJAX_GET_CATEGORIES)
	{
		var arr = cleanBrandCatResponse(responseText);
		rebuildOptions(arr, 'category');
	}
	else if(action == AJAX_GET_BRANDS)
	{
		var arr = cleanBrandCatResponse(responseText);	
		rebuildOptions(arr, 'brand');
	}
	else if(action == AJAX_GET_PRODUCT_LINES)
	{
		var arr = cleanBrandCatResponse(responseText);
		rebuildOptions(arr, 'product_line');
	}
	else if(action == AJAX_GET_COLORS)
	{
		var arr = cleanBrandCatResponse(responseText);
		rebuildOptions(arr, 'title');
	}
	else
	{
		//alert("not implemented");
	}

	//cleanup and release resources
	delete xmlHttpObj;
	SimpleAjax.release();
}

function cleanBrandCatResponse(responseStr)
{
	var errpos = responseStr.lastIndexOf('&');
	var tempstr = responseStr.substring(0,errpos);
	return ( tempstr.split(";") );
}

//================== GENERAL utilities ===================================================
function setBrandCategoryForm(fname)
{
	//for use by product review
	AJAX_brandCatForm = fname;
	
	//instantiate single ajax object
	SimpleAjax = new ajaxObject();

	//make sure we handle data being sent from IE6 appropriately
	checkIE6();

	//cache category entries:
	try
	{
		//PR_origCategoryOptions = new Array();
		PR_flatOptions = new Array();
		var ddlb = document.getElementById(AJAX_brandCatForm).elements['category'];
		var optGrps = ddlb.getElementsByTagName("optgroup");
		var numGrps = optGrps.length;
		
		//var alertstr ='';
		for(i=0;i<numGrps;i++)
		{
			//var selectedOption = ddlb.options[ddlb.selectedIndex].value;
			var grpName = optGrps[i].label;
			var numOptions = optGrps[i].childNodes.length;
			//PR_origCategoryOptions[grpName] = new Array();
			//PR_flatOptions[grpName] = new Array();

			for(j=0;j<numOptions;j++)
			{
				//PR_origCategoryOptions[grpName].push(optGrps[i].childNodes[j].innerHTML);
				//alertstr += grpName + "[" + PR_origCategoryOptions[grpName][j] + "]\n";
				var optname = optGrps[i].childNodes[j].innerHTML;
				PR_flatOptions[optname] = grpName;
				//alertstr += optname + "[" + PR_flatOptions[optname] + "]\n";
			}
		}
		//alert(alertstr);
	}
	catch(e)
	{
		//alert("exception caught in setBrandCategoryForm");
	}
}

function setSearchOptsColor(value)
{
	//for use by product review
	document.getElementById('search').elements['showcolor_option'].value = value;
	document.getElementById('search').submit();
}

function showProduct(nid)
{
	//for use by product review
	document.getElementById('colors').action = "/node/" + nid;
	document.getElementById('colors').submit();
}

function toggleBrand(val)
{
	if(val != '')
	{
		document.getElementById(AJAX_brandCatForm).elements['brand'].disabled = true;
		document.getElementById(AJAX_brandCatForm).elements['product_line'].disabled = true;
		document.getElementById(AJAX_brandCatForm).elements['title'].disabled = true;
	}
	else
	{
		document.getElementById(AJAX_brandCatForm).elements['brand'].disabled = false;
		document.getElementById(AJAX_brandCatForm).elements['product_line'].disabled = false;
		document.getElementById(AJAX_brandCatForm).elements['title'].disabled = false;
	}
}

function toggleProductLine(val)
{
	var theForm = document.getElementById(AJAX_brandCatForm);
	if(val != '' )
	{
		theForm.elements['product_line'].disabled = true;
		theForm.elements['title'].disabled = true;
	}
	else if(theForm.elements['brand'].disabled == false)
	{
		document.getElementById(AJAX_brandCatForm).elements['product_line'].disabled = false;
		document.getElementById(AJAX_brandCatForm).elements['title'].disabled = false;
	}
}

//================== CALLING utilities ===================================================
function getCategoriesByBrand(brandval)
{
	if(PR_isIE6 == true)
	{
		brandval = encodeURIComponent(brandval);
	}

	SimpleAjax.update('/pr_brandcats.php?brand='+ brandval, ajaxResponse, AJAX_GET_CATEGORIES, '');
}

function getBrandsByCategory(catval)
{
	if(PR_isIE6 == true)
	{
		catval = encodeURIComponent(catval);
	}

	SimpleAjax.update('/pr_brandcats.php?category='+ catval, ajaxResponse, AJAX_GET_BRANDS, '');
}

function getProductLines()
{
	var brandform =document.getElementById(AJAX_brandCatForm).elements['brand'];
	var catform =document.getElementById(AJAX_brandCatForm).elements['category'];
	var linebrand = brandform.options[brandform.selectedIndex].value;
	var linecat = catform.options[catform.selectedIndex].value;

	if(PR_isIE6 == true)
	{
		linebrand = encodeURIComponent(linebrand);
		linecat = encodeURIComponent(linecat);
	}
	SimpleAjax.update('/pr_brandcats.php?linebrand='+ linebrand +'&linecat='+ linecat, ajaxResponse, AJAX_GET_PRODUCT_LINES,'');
}

function getColorTypes(lineval)
{
	if(PR_isIE6 == true)
	{
		lineval = encodeURIComponent(lineval);
	}

	SimpleAjax.update('/pr_brandcats.php?product_line='+ lineval, ajaxResponse, AJAX_GET_COLORS, '');
}


//================== RESPONSE utilities ===================================================
function rebuildOptions(optsArr, selectBoxId)
{   
	//kill current entries only if we definitely have a new list, else leave well alone
	if(optsArr.length > 0)
	{   
		var ddlb = document.getElementById(AJAX_brandCatForm).elements[selectBoxId];
		var selectedOption = ddlb.options[ddlb.selectedIndex].value;

		if(PR_isIE6 == true)
		{
			ddlb.innerHTML = "";
		}
		else
		{
			ddlb.options.length=0;
		}
		
		//the categories ddlb needs to be rebuilt differently - because of optgroup tags:
		//also, we don't do any of this if on the product review submission page as it's pointless.
		if(selectBoxId == 'category' && (AJAX_brandCatForm != 'prodinfo') )
		{
			ddlb.innerHTML='';//kill the optgroups as well.
			var oglist = new Array(); //store ogs we're going to render
			var ogcheck = new Array();

			//collate new entries into groups
			try
			{
				for(i=0;i<optsArr.length;i++)
				{
					//nb: Option(text, value, defaultSelected, selected)
					var optname = optsArr[i];
					var ogname = PR_flatOptions[optname];
					var opt;
					
					if( ! oglist[ogname] )
					{
						oglist[ogname] = new Array(); //array to store opts
						ogcheck[ogcheck.length] = ogname; //just track which og names we've encountered so far
					}
					
					//create the option
					if(selectedOption == optsArr[i])
					{
						opt = new Option(optsArr[i], optsArr[i], true, true);
					}
					else
					{
						opt = new Option(optsArr[i], optsArr[i]);
					}
					
					opt.innerHTML = optsArr[i]; //for poxy IE
					oglist[ogname].push(opt);					
				}
				
				//if nothing had been selected, go back to default of '(please select one)'
				var ogAll = "All Categories";
				if(selectedOption == 'all')
				{
					opt = new Option('(please select one)','all',true,true);
				}
				else
				{
					 opt = new Option('(please select one)','all');
				}
				opt.innerHTML = '(please select one)'; //for poxy IE
				oglist[ogAll] = new Array();
				oglist[ogAll].push(opt);
				ogcheck[ogcheck.length] = ogAll;

			}
			catch(e)
			{
				//alert ("exception in rebuildOptions - 1");
			}

			//render
			try
			{
				for(i=0;i<ogcheck.length; i++)
				{
					var ogname = ogcheck[i];
					if( (ogname == undefined) || (ogname == '') ) continue;
	
					//create the optgroup
					var og = document.createElement("OPTGROUP");
					og.label = ogname;
					
					//append the options
					for(j=0;j<oglist[ogname].length;j++)
					{
						og.appendChild( oglist[ogname][j] );
					}
					
					//append to ddlb
					ddlb.appendChild(og);
				}				
			}
			catch(e)
			{
				//alert ("exception in rebuildOptions - 2");
			}
		}//end if rebuilding categories
		else
		{
			//new entries
			var hasOverall = false;
			for(i=0;i<optsArr.length;i++)
			{
				//nb: Option(text, value, defaultSelected, selected)
				if(selectedOption == optsArr[i])
				{
					ddlb.options[i] = new Option(optsArr[i], optsArr[i], true, true);
				}
				else
				{
					ddlb.options[i] = new Option(optsArr[i], optsArr[i]);
				}
				if( (selectBoxId == 'title') && (optsArr[i] == 'Overall') ) hasOverall = true;
			}
			
			//if nothing had been selected, go back to default of '(please select one)',
			//except in the case of color (we want to show 'Overall' as the default
			if(selectBoxId != 'title')
			{
				if(selectedOption == 'all')	ddlb.options[i] = new Option('(please select one)','all',true,true);
				else ddlb.options[i] = new Option('(please select one)','all');
			}
			else
			{
				if(hasOverall == false) ddlb.options[i] = new Option('Overall','Overall');
			}
		}//end else rebuild list box which is NOT categories.
	}//end if we have new opts back from the server
}
