/* 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.type!=null&&elem.type=='radio')
	{
		elem=getElements(name);
		for(var i=0;i<elem.length;i++) if(elem[i].checked) return elem[i].value;
		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 ['ADP','AED','AFN','ALL','AMD','ANG','ARS','AUD','AWG','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','IRR','ISK','JMD','JOD','JPY','KES','KGS','KHR','KMF','KRW','KWD','KYD','KZT','LAK','LBP','LKR','LRD','LSL','LTL','LVL','LYD','MAD','MDL','MGA','MMK','MNT','MOP','MRO','MTL','MUR','MVR','MWK','MXN','MYR','NGN','NIC','NOK','NPR','NZD','OMR','PAB','PEN','PGK','PHP','PKR','PLN','PYG','QAR','RON','RSD','RUB','RWF','SBD','SCR','SDD','SEK','SGD','SKK','SLL','SOS','SRD','STD','SVC','SYP','SZL','THB','TND','TRY','TTD','TWD','TZS','UAH','UGX','USD','UYU','UZS','VEF','VND','VUV','XAF','XCD','XPF','ZAR'];
	var exRate=new ['0.008400','0.272300','0.021200','0.010000','0.002700','0.558700','0.209650','1.068960','0.558700','0.500000','0.013500','0.672870','2.652500','0.000800','1.000000','0.801020','0.143500','0.579580','1.000000','0.021600','0.138800','0.000200','0.503700','0.997800','1.092110','0.002090','0.158470','0.000560','0.001900','1.000000','0.012700','2.401500','0.057200','0.005600','0.177040','0.026200','0.013700','0.167300','0.089200','0.058400','1.316000','0.570700','1.581350','0.601100','0.649800','1.601000','0.035000','0.000100','0.127300','0.005000','0.128930','0.053100','0.173510','0.024800','0.004500','0.000110','0.269770','0.020480','0.000080','0.008100','0.011700','1.411400','0.013120','0.010700','0.022200','0.000200','0.002900','0.000890','3.602300','1.219500','0.006720','0.000100','0.000700','0.008770','0.013700','0.139400','0.381130','1.880260','0.517490','0.123800','0.087000','0.000500','0.155300','0.000800','0.124500','0.003500','3.252000','0.034430','0.064900','0.006000','0.077910','0.332180','0.006400','0.044200','0.172160','0.012740','0.831380','2.600780','1.000000','0.366800','0.447000','0.023500','0.011050','0.329200','0.000300','0.274720','0.302630','0.013800','0.033050','0.001700','0.134600','0.082100','0.003700','0.148730','0.802380','0.046300','0.000200','0.000600','0.303000','0.266600','0.114300','0.021100','0.139400','0.032380','0.713000','0.569400','0.156460','0.033910','0.000600','0.125100','0.000400','1.000000','0.052800','0.000600','0.232880','0.000200','0.010900','0.002100','0.370400','0.011800','0.131240'];
	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)
{
	//var regex = /^("[^"]{1,62}"|[a-zA-Z_-][a-zA-Z0-9_+.-]{0,64})\@(\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]|[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,6})$/;
	//var regex = /^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,6}$/;
	var regex = /.+@.+\..+/;
	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"), "");
}

if(!String.prototype.trim) String.prototype.trim=function()
{
	var	str=this.replace(/^\s\s*/,''), ws=/\s/, i=str.length;
	while(ws.test(str.charAt(--i)));
	return str.slice(0,i+1);
}

String.prototype.levenshtein=function(t,cost_ins,cost_rep,cost_del)
{
	var s=this;
	if(cost_ins==null) cost_ins=1;
	if(cost_rep==null) cost_rep=1;
	if(cost_del==null) cost_del=1;
	var m=s.length;
	var n=t.length;
	var d=[];
	for(var i=0;i<=m;i++) d[i]=[i];
	for(var j=0;j<=n;j++) d[0][j]=j;
	for(var j=1;j<=n;j++) for(var i=1;i<=m;i++)
	{
		var cost=cost_rep;
		if(s.charAt(i-1)==t.charAt(j-1)) cost=0;
		d[i][j]=Math.min(d[i-1][j]+cost_ins,d[i][j-1]+cost_del,d[i-1][j-1]+cost);
	}
	return d[m][n];
}
var RecaptchaOptions = {"theme":"white"};
$(function() {
	var tab_classes=["glass_tab", "flat_tab", "header_tab", "footer_tab", "header_tab_left", "header_tab_right", "footer_tab_left", "footer_tab_right", "login_tab", "login_tab_active"];
	var button_classes=["shady_button", "search_button", "tool_enable_button", "tool_disable_button", "large_button", "larger_button", "flat_button1", "flat_button2", "glass_button"];

	/**
	 * Add mouseover effects to particular classes
	 */
	$(tab_classes).add(button_classes).each(function() {
		$("."+this).attr("hover_class",this).hover(function() {if(!this.disabled) {
			if($(this).hasClass($(this).attr("hover_class")+"_active")) $(this).toggleClass($(this).attr("hover_class")+"_active_hover",true);
			else $(this).toggleClass($(this).attr("hover_class")+"_hover",true);
		}},function() {
			$(this).toggleClass($(this).attr("hover_class")+"_active_hover",false);
			$(this).toggleClass($(this).attr("hover_class")+"_hover",false);
		});
	});

	/**
	 * Add tab click effects
	 */
	$(tab_classes).each(function() {
		$("."+this).attr("tab_class",this).click(function() {
			$(this).toggleClass($(this).attr("tab_class")+"_active",true);
			$("#"+$(this).attr("name")).fadeIn();
			$("."+$(this).attr("tab_class")+"[tabgroup=\""+$(this).attr("tabgroup")+"\"]").not(this).each(function() {
				$(this).toggleClass($(this).attr("tab_class")+"_active",false);
				$("#"+$(this).attr("name")).hide();
			});
		});
	});

	/**
	 * Add highlighting for required inputs on the page
	 */
	$(".required").change(function() {
		$(this).css("background",(this.value=="")?"#fee":"#efe");
		$(this).css("border","1px solid #ccc");
		//if(this.name=="signup_1[email_address]") $(this).css("background",(isValidEmail(this.value))?"#efe":"#fee");
		//if(this.name=="signup_1[password1]") $(this).css("background",(this.value.length>6)?"#efe":"#fee");
		/*if(this.name=="signup_1[password2]")
		{
			var match=getElement("signup_1[password1]");
			if(match!=null) $(this).css("background",(this.value.length>6 && this.value==match.value)?"#efe":"#fee");
		}*/
	}).css("background","#fee").filter("[value!=\"\"]").css("background","#efe");

	/**
	 * Add highlighting for optional inputs on the page
	 */
	$(".optional").change(function() {
		$(this).css("background",(this.value=="")?"#fff":"#efe");
		$(this).css("border","1px solid #ccc");
	}).css("background","#fff").filter("[value!=\"\"]").css("background","#efe");

	/**
	 * Add automatic row alternating to certain table styles
	 */
	$("table.table_list1").each(function() {$("tr:odd",this).addClass("alt");});
	$("table.table_list2").each(function() {$("tr:even",this).addClass("alt");});

	/**
	 * Load jquery extensions after main parts are loaded...
	 */
	$.ajaxSetup({cache:true});
	$.getScript("/jquery/skip_deps&corner&customselect.js", function() {
		$(".custom_select").customSelect();
		$(".login_box").corner("8px");
	});
	/*
	$.getScript("/jquery/skip_deps&thickbox&alphanumeric&corner.js", function() {
		$(".numeric").numeric();
		$("#header").corner("bevel bottom 12px");
		$("#footer").corner("bevel bottom 12px");
		$(".tools_window .window_noclient").corner("bevel tr 5px");
	});
	*/
	$.ajaxSetup({cache:null});
});

//Iexplore hack for layered backgrounds or something, can't remember
$(window).load(function() {
	try
	{
		document.execCommand("BackgroundImageCache", false, true);
	}
	catch(err)
	{
	}
});

