/* Common General Use Functions */
/*
function getElements(name)
function getElement(name)
function getValue(name)
function setElement(elem,value)
function setValue(name,value)
function setClass(name,value)
function setAllValues(name,value)
function setSelectOptions(name,newOptions)
function addTableRow(theTable,newName,offset)
function addTableCell(tableRow,innerStuff)
function textareaAutoSize(theElem,stepSize,minSize,maxSize)
function toggleSection(sectionName)
function testPost(theFrm)
*/

/* PHP Functions */
/*
function array_search(needle,haystack)
function explode(str_separator,str_string)
function implode(str_glue,arr_pieces)
function in_array(needle,haystack)
function join(str_glue,arr_pieces)
function str_replace(str_search,str_replace,str_subject)
function round(num_val,num_precision)

*/

/* Common Data Related Functions */
/*
function convertCurrency(price,fromCurrency,toCurrency)
function generic_insert(name,tag,extras)
function formatMETA(theString,type)
function my_trim(array)
function open_win(url)
function isValidEmail(email_address)
*/

function getElements(name)
{
	var	elemList=document.getElementsByName(name);
	if(document.all!=null && elemList.length==0)
	{
		elemList=new Array();
		for(var key in document.all)
			if(document.all[key].name==name)
				elemList[elemList.length]=document.all[key];
	}
	var idElem=document.getElementById(name);
	if(idElem!=null) elemList[elemList.length]=idElem;
	return elemList;
}

function getElement(name,fail_safe)
{
	if(fail_safe==null) fail_safe=true;
	var elem=document.getElementById(name);
	if(elem) return elem;
	elem=document.getElementsByName(name);
	if(elem.length>0) return elem[0];
	if(document.all!=null && fail_safe)
	{
		for(var key in document.all)
		{
			if(document.all[key].id==name) return document.all[key];
			if(document.all[key].name==name) return document.all[key];
		}
	}
	return null;
}

function getValue(name)
{
	var elem=getElement(name);
	if(elem==null) return null;
	if(elem.value!=null) return elem.value;
	if(elem.innerHTML!=null) return elem.innerHTML;
	return null;
}

function is_array(obj)
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function setElement(elem,value)
{
	if(elem.tagName=='SELECT')
		for(var i=0;i<elem.options.length;i++)
			if(elem.options[i].value==value)
			{
				elem.options[i].selected=true;
				elem.selectedIndex=i;
			}
			else
				elem.options[i].selected=false;
	if(elem.tagName=='SPAN' || elem.tagName=='DIV')
	{
		elem.innerText=value;
		elem.innerHTML=value;
	}
	if(elem.value!=null) elem.value=value;
	else if(elem.innerHTML) elem.innerHTML=value;
}

function setValue(name,value)
{
	var elem=getElement(name);
	if(elem!=null) setElement(elem,value);
}

function setClass(name,value)
{
	var elem=getElement(name);
	if(elem!=null) elem.className=value;
}

function setAllValues(name,value)
{
	var elemList=getElements(name);
	if(elemList.length>0)
		for(var i=0;i<elemList.length;i++)
			setElement(elemList[i],value);
}

function setSelectOptions(name, newOptions, append, appendGroup)
{
	if(append == null) append=false;
	var elem=getElement(name);
	if(elem==null) return;	
	if(!append)
	{
		elem.options.length=0;
		// also have to remove any optgroups the select menu might have..
		var optGrps = elem.getElementsByTagName("optgroup");
		var olength=optGrps.length;
		if(olength>0) for (var i=0; i<olength; i++) elem.removeChild(optGrps[0]);
	}

	for(var key in newOptions)
	{
		if(is_array(newOptions[key]))
		{
			optGroup=document.createElement('optgroup');
			optGroup.label=key;
			elem.appendChild(optGroup);
			setSelectOptions(name, newOptions[key], true, optGroup);
		}
		else
		{
			var newOption=new Option(newOptions[key],key)
			elem.options[elem.options.length]=newOption;
			if(appendGroup != null) appendGroup.appendChild(newOption);
		}
	}
}

function addTableRow(theTable,newName,offset)
{
	if(offset==null) offset=theTable.rows.length;
	if(offset<0) offset=theTable.rows.length+offset+1;
	var newRow=theTable.insertRow(offset);
	newRow.name=newName;
	newRow.id=newName;
	return newRow;
}

function addTableCell(tableRow,innerStuff)
{
	var newCol=document.createElement('td');
	newCol.innerHTML=innerStuff;
	tableRow.appendChild(newCol);
	return newCol;
}

function textareaAutoSize(theElem,stepSize,minSize,maxSize)
{
	if(theElem==null || theElem.rows==null || theElem.cols==null || theElem.value==null) return;
	if(stepSize==null || stepSize<1) stepSize=5;

	var rowContent=theElem.value.split('\n');
	var rowCount=rowContent.length;

	for(i=0;i<rowContent.length;i++)
		rowCount+=Math.floor(rowContent[i].length/60);

	rowCount=Math.floor(rowCount/stepSize)*stepSize+stepSize;

	if(minSize!=null && minSize>rowCount) rowCount=minSize;
	if(maxSize!=null && maxSize>minSize && maxSize<rowCount) rowCount=maxSize;

	theElem.rows=rowCount;
}

function toggleSection(sectionName,force)
{
	var theSect=getElement(sectionName);
	var hideNote=getElement(sectionName+'_hideNote',false);
	if(theSect==null) return;
	var newDisplay=(theSect.style.display=='none');
	if(force!=null) newDisplay=force;
	theSect.style.display=(newDisplay)?'':'none';
	if(hideNote!=null) hideNote.style.display=(newDisplay)?'none':'';
}

function testPost(theFrm)
{
	var oldact=theFrm.action;
	var oldtrg=theFrm.target;
	theFrm.action="testpost.php";
	theFrm.target="_blank";
	theFrm.submit();
	theFrm.action=oldact;
	theFrm.target=oldtrg;
}

function array_search(needle,haystack)
{
	if(needle==null || haystack==null) return null;
	for(var i=0;i<haystack.length;i++)
		if(needle==haystack[i])
			return i;
	return null;
}

function explode(str_separator,str_string)
{
	return str_string.split(str_separator);
}

function implode(str_glue,arr_pieces)
{
	return arr_pieces.join(str_glue);
}

function in_array(needle,haystack)
{
	if(needle==null || haystack==null) return false;
	for(var i=0;i<haystack.length;i++)
		if(needle==haystack[i])
			return true;
	return false;
}

function join(str_glue,arr_pieces)
{
	return implode(str_glue,arr_pieces);
}

function str_replace(str_search,str_replace,str_subject)
{
	return implode(str_replace,explode(str_search,str_subject));
}

function round(num_val,num_precision)
{
	if(num_precision==null || num_precision<1)
		num_precision=0;
	return Number(num_val).toFixed(num_precision);
}

function convertCurrency(price,fromCurrency,toCurrency)
{
	var exKeys=new Array('ADP', 'AFN', 'ALL', 'AMD', 'ANG', 'ARS', 'AUD', 'AWG', 'AZM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYR', 'BZD', 'CAD', 'CHF', 'CLP', 'CNY', 'COP', 'CRC', 'CUP', 'CVE', 'CYP', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'ECS', 'EEK', 'ETB', 'EUR', 'FJD', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTL', 'LVL', 'LYD', 'MAD', 'MDL', 'MGA', 'MNT', 'MOP', 'MRO', 'MTL', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZM', 'NGN', 'NIC', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SBD', 'SCR', 'SEK', 'SGD', 'SKK', 'SLL', 'SOS', 'SRD', 'STD', 'SVC', 'SYP', 'SZL', 'THB', 'TMM', 'TND', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'XAF', 'XAG', 'XAU', 'XCD', 'XEU', 'XPF', 'XPT', 'ZAR');
	var exRate=new Array('0.0076', '0.0192', '0.0102', '0.0033', '0.5587', '0.2919', '0.6423', '0.5587', '0.0002', '0.5', '0.0146', '0.6449', '2.6532', '0.0008', '1', '0.6539', '0.1425', '0.4045', '1', '0.0201', '0.1231', '0.0005', '0.5089', '0.7917', '0.8229', '0.0015', '0.146', '0.0004', '0.0019', '1', '0.0115', '2.1556', '0.0491', '0.0056', '0.1693', '0.0283', '0.0138', '0.1811', '0.0807', '0.1002', '1.2617', '0.5388', '1.4586', '0.6061', '0.8162', '1.4586', '0.0372', '0.0002', '0.1308', '0.0049', '0.129', '0.0529', '0.1754', '0.0249', '0.0048', '0.0001', '0.2504', '0.0201', '0.0009', '0.0072', '0.0129', '1.413', '0.0108', '0.0126', '0.0254', '0.0002', '0.0026', '0.0007', '3.6245', '1.2195', '0.0083', '0.0001', '0.0007', '0.0091', '0.0158', '0.0973', '0.3654', '1.7787', '0.7666', '0.1141', '0.0961', '0.0005', '0.0008', '0.1252', '0.0039', '2.9386', '0.0314', '0.0781', '0.0071', '0.0736', '0.275', '0.1558', '0.0078', '0.0506', '0.1389', '0.0125', '0.5332', '2.6008', '1', '0.3224', '0.39', '0.0202', '0.0127', '0.3261', '0.0002', '0.2746', '0.3282', '0.0142', '0.0357', '0.0018', '0.1334', '0.061', '0.1193', '0.6546', '0.0418', '0.0003', '0.0007', '0.3643', '0.2665', '0.1143', '0.0217', '0.0973', '0.028', '0.2723', '0.7115', '0.6369', '0.1605', '0.0298', '0.0008', '0.1329', '0.0005', '1', '0.0416', '0.0007', '0.4657', '0.0002', '0.0083', '0.0019', '9.3809', '769.2308', '0.3824', '1.2617', '0.0106', '833.3333', '0.0973');
	fromCurrency=array_search(fromCurrency.slice(0,3).toUpperCase(),exKeys);
	toCurrency=array_search(toCurrency.slice(0,3).toUpperCase(),exKeys);
	if(fromCurrency==null || toCurrency==null || fromCurrency==toCurrency)
		return Number(price).toFixed(2);
	var newP=price*(exRate[fromCurrency]/exRate[toCurrency]);
	return newP.toFixed(2);
}

function generic_insert(name,tag,extras)
{
	var theElem=getElement(name);
	if(theElem==null) return;

	if(extras==null) extras='';

	if(theElem.selectionStart!=null && theElem.selectionEnd!=null)
	{
		var a=theElem.selectionStart;
		var b=theElem.selectionEnd;
		theElem.value=theElem.value.substring(0,a)+'<'+tag+extras+'>'+theElem.value.substring(a,b)+'</'+tag+'>'+theElem.value.substring(b);
		theElem.selectionStart=a+2+tag.length+extras.length;
		theElem.selectionEnd=2+tag.length+extras.length+b;
		theElem.focus();
	}
	else
	{
		var repltext=null;
		var seltext=(document.all)?document.selection.createRange():document.getSelection();
		var selit=(document.all)?document.selection.createRange().text:document.getSelection();
		if(seltext!=null && selit.length>=1)
			seltext.text='<'+tag+extras+'>'+seltext.text+'</'+tag+'>';
		else
			theElem.value+='<'+tag+extras+'>TEXT</'+tag+'>';
	}
}

function formatMETA(theString,type)
{
	theString=str_replace('"',"'",theString);
	theString=str_replace(';',"",theString);
	if(type=='keyword')
	{
		theString=str_replace(","," ",theString);
		theString=str_replace("-"," ",theString);
		var words=theString.split(' ');
		words=my_trim(words);
		var keywords='';
		for(i=0;i<50 && i<words.length;i++)
		{
			if(words[i].replace(" ","")!='')
			{
				var let=words[i].charAt(0);
				let=let.toUpperCase();
				keywords+=let+words[i].substring(1,words[i].length)+", ";
			}
		}
		return keywords;
	}
	return theString;	
}

function generateURLKeys(product_name)
{
	var pr_ar=explode(' ',product_name);
	var new_words=Array();
	var count=0;
	for(i=0;i<pr_ar.length;i++)
	{
		if(isNaN(pr_ar[i]) && pr_ar[i].length>2 && count<3)
		{
			new_words[i]=pr_ar[i];
			count++;
		}
	}
	return implode(' ',new_words);	
}

function my_trim(array)
{
	for(i=0;i<array.length;i++)
	{
		var word=array[i]+"";
		array[i]=word.replace(" ","");
	}
	return array;
}

function open_win(url)
{
	window.open(url,'','scrollbar=yes,width=400,height=400');
}

function isValidEmail(email_address)
{
	regex=/^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,6}$/;
	return regex.test(email_address);
}


function openWindow(url,w,h,centered,features)
{
	if(features==null) features='';
	if(features!='') features+=',';
	if(centered == null) centered = false;
	features += 'width='+w+', height='+h;
	if(centered) features += ', top='+((screen.height - h) / 2)+', left='+((screen.width  - w)  / 2);
	window.open(url,'',features);
}

function changeOpac(opacity, name, obj)
{
	var object=getElement(name);
	if(obj!=null) object=obj;
	object.style.opacity = (opacity / 100);
	object.style.MozOpacity = (opacity / 100);
	object.style.KhtmlOpacity = (opacity / 100);
	object.style.filter = "alpha(opacity=" + opacity + ")"; 
}

function opacity(name, opacStart, opacEnd, millisec)
{
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd)
	{
		for(i = opacStart; i >= opacEnd; i--)
		{
			setTimeout("changeOpac(" + i + ",'" + name + "')",(timer * speed));
			timer++;
		}
	}
	else if(opacStart < opacEnd)
	{
		for(i = opacStart; i <= opacEnd; i++)
		{
			setTimeout("changeOpac(" + i + ",'" + name + "')",(timer * speed));
			timer++;
		}
	}
}

function scrollToElement(elem)
{
	if(elem==null) return;
	var posX=elem.offsetLeft
	var posY=elem.offsetTop;
	elem=elem.offsetParent;
	while(elem != null)
	{
		posX+=elem.offsetLeft 
		posY+=elem.offsetTop;
		elem=elem.offsetParent;
	}
	window.scrollTo(posX ,posY-95);
}

function trim(str, chars)
{
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function freightQuote(product_id,sub_id,qty)
{
	if(product_id == null) return;
	if(sub_id==null) sub_id=0;
	if(qty==null) qty=1;
	var script = '/freight/freight_'+product_id+'_'+sub_id+'_'+qty+'.html';
	openWindow(script,'850','650',true);
}

function updateFreightList()
{
	var val = getValue('display');
	if(val.length > 3) {
		var url = '/freight/freight_list.html?action=domestic&destination='+val;
		if (window.XMLHttpRequest)
		{
			http_request = new XMLHttpRequest();
            if(http_request.overrideMimeType) http_request.overrideMimeType('text/xml');
        }
		else if (window.ActiveXObject)
		{
			try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch (e) {
				try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch (e) {}
			}
	    }
		if (!http_request) {
			alert('Giving up :( Cannot create an XMLHTTP instance');
			return false;
		}
       	http_request.onreadystatechange = function() { alertContents(http_request); };
       	http_request.open('GET', url, true);
       	http_request.send(null);
	}
	else {
		getElement('list').innerHTML = '';
		getElement('list_tr').style.display='none';
	}
}


function alertContents(http_request)
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var elem = getElement('list');
			getElement('list_tr').style.display='';
			elem.innerHTML = ''+http_request.responseText;
		}
		else alert('There was a problem with the request.');
	}
}

function selectDestination(location, state, code)
{
	setValue('display',location+", "+state+" ("+code+")");
	setValue('destination',location);
	setValue('state',state);
	setValue('code',code);
	getElement('list_tr').style.display='none';
	getElement('list').innerHTML = '';
}

function resetData()
{
	setValue('display','');
	setValue('destination','');
	setValue('state','');
	setValue('code','');
}

function freightFormSubmit(form)
{
	if(validateFreightSearch())
		form.submit();
}

function validateFreightSearch()
{
	if(getElement('weight').value <= 0) {
		alert('Weight cannot be less than or equal to 0');
		return false;
	}
	return true;
}

function changePrice(oldPrice,newCurrency,elemCurrency,elemPrice)
{
	oldCurrency = getElement(elemCurrency).innerHTML;
	newPrice = convertCurrency(oldPrice,oldCurrency,newCurrency);
	if(newCurrency == 'AUD') newPrice = new Number(newPrice*1.1).toFixed(2);
	else if(oldCurrency == 'AUD') {
		if(newCurrency == 'JPY') newPrice = new Number(newPrice/1.1).toFixed(0);
		else newPrice = new Number(newPrice/1.1).toFixed(2);
	}
	else if(newCurrency == 'JPY') newPrice = new Number(newPrice).toFixed(0);
	else newPrice = new Number(newPrice).toFixed(2);
	setValue(elemPrice,newPrice);
}

function checkAllCompares(selectElem)
{
	var elem = getElement(selectElem);
	var col = document.getElementsByName('compare[]');
	for(var i=0;i<col.length;i++)
		var obj = col[i].checked = elem.checked;
	for(i=0;i<15;i++) {
		var name='select_all_'+i;
		var obj = getElement(name);
		if(!obj || obj == null) break;
		if(name != selectElem) {
			obj.checked=getElement(selectElem).checked;
		}
	}
}

function compareSubmit(form)
{
	var count = 0;
	var col = document.getElementsByName('compare[]');
	for(var i=0;i<col.length;i++) if(col[i].checked) count++;
	if(count >= 2) getElement(form).submit();
	else { alert('Please select at least 2 products to compare'); return false; }
}
