/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function setEqualHeightColumns(columnClassName) {
	var divs = $$("."+columnClassName);

	// Let's determine the maximum height out of all columns specified
	var maxHeight = 400;
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].getHeight() > maxHeight) {maxHeight = divs[i].getHeight()};
	}

	// Let's set all columns to that maximum height
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.height = maxHeight + 'px';
	}

}

function setEqualHeightColumnsArea(columnClassName,area) {
	var divs = $$("."+columnClassName);

	// Let's determine the maximum height out of all columns specified
	var maxHeight = 400;
	for (var i = 0; i < divs.length; i++) {

		if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
	}

	// Let's set all columns to that maximum height
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.height = maxHeight + 'px';

		// Now, if the browser's in standards-compliant mode, the height property
		// sets the height excluding padding, so we figure the padding out by subtracting the
		// old maxHeight from the new offsetHeight, and compensate!  So it works in Safari AND in IE 5.x
		if (divs[i].offsetHeight > maxHeight) {
			divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
		}
	}
	$(area).style.height = maxHeight + 'px';

}

function setEqualHeightArea(columnClassName,area) {
	var divs = $$("."+columnClassName);
	
	// Let's determine the maximum height out of all columns specified
	var maxHeight = 400;
	for (var i = 0; i < divs.length; i++) {

		if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
	}
	$(area).style.height = maxHeight + 'px';
}

/**
 * Toggles the tree branch open/closed depending on it's current state.
 * The actual toggle is accomplished by setting the list's style
 * to 'display: none' to hide it or 'display:' to show it.
 */

function togglelayerdisplay(area){

	if ($(area).style.display == "none")
		todo = "";
	else
		todo = "none";

	$(area).style.display = todo;
}

/**
 * Toggles the tree branch open/closed depending on it's current state.
 * The actual toggle is accomplished by setting the list's style
 * to 'display: none' to hide it or 'display:' to show it.
 */

function pagebackkeepinsite(siteaddress,returnaddress){

	var refURL = document.referrer;

	if(refURL.match(siteaddress))
		history.back();
	else
		location.href = returnaddress;
}

function searchnow(form,value)
{
	$(form).searchnowfield.value = value;
	$(form).submit();
}

function rewviewuseful(reviewid,useful)
{
	if($('usefulbuttons'+reviewid)){
		$('usefulbuttons'+reviewid).update('Thank you.');
	}
	var pars = 'reviewid=' + reviewid + '&useful=' + useful;
	new Ajax.Request('/modules/datacode/reviewuseful.php', { method:'get', parameters: pars, onSuccess: rewviewusefuldisplay});
	return void(0);
}

function rewviewusefuldisplay(transport)
{
	totals = transport.responseText.evalJSON();

	if($('usefultotal'+totals.reviewid)){
		$('usefultotal'+totals.reviewid).update(totals.usefultotal);
	}
	if($('usefulyestotal'+totals.reviewid)){
		$('usefulyestotal'+totals.reviewid).update(totals.usefulyestotal);
	}
}

function preloadImages() {
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function alternantRowStyles(styleon,styleoff,groupname,rowson,rowsoff) {
	var divs,count = 0;
	var countstring = sprintf(groupname+"%02d",count);
	var test = rowsoff;
	var newstyle = styleoff;
	while((divs = $$("."+countstring)) != false){
		var stylelook = 0;
		for (var i = 0; i < divs.length; i++) {
			divs[i].className += " "+newstyle;
			divs[i].onmouseover = rowFocusOn;
			divs[i].onmouseout = rowFocusOff;
			stylelook ++;
			if(stylelook == test){
				if(newstyle == styleon){
					newstyle = styleoff;
					test = rowsoff;
				}
				else {
					newstyle = styleon;
					test = rowson;
				}
				stylelook = 0;
			}
		}
		count ++;
		countstring = sprintf("groupname%02d",count);
	}
}

function rowFocusOn()
{
	this.className += " admin_rowhidhlightfocus";
}


function rowFocusOff()
{
	currentClassName = new String(this.className);
	this.className = currentClassName.replace(" admin_rowhidhlightfocus","");
}

function focueeditbuttons(button){
	var button = document.getElementById(button);
	button.style.display = "block";
}

function removefocueeditbuttons(button){
	var button = document.getElementById(button);
	button.style.display = "none";
}

function setFixedMenuOn(menuRef,menuOn,onStyle){
	var mainmenuid = $(menuRef+menuOn);
	if(mainmenuid)
		mainmenuid.className = mainmenuid.className + " "+onStyle;
}

function flexibleLayoutArrange(footer,startPoistion,minLength) {

	var divs = new Array();
	for (var i = 3; i < arguments.length; i++) {
		divs.push($(arguments[i]))
	}

	// Let's determine the maximum height out of all columns specified
	var maxHeight = minLength;
	for (i = 0; i < divs.length; i++) {
		if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
	}

	// Let's set all columns to that maximum height
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.height = maxHeight + 'px';

		// Now, if the browser's in standards-compliant mode, the height property
		// sets the height excluding padding, so we figure the padding out by subtracting the
		// old maxHeight from the new offsetHeight, and compensate!  So it works in Safari AND in IE 5.x
		if (divs[i].offsetHeight > maxHeight) {
			divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
		}
	}
	maxHeight += startPoistion;
	$(footer).style.top = maxHeight  + 'px';
}

function flexibleLayoutArrangeExtra(footer,startPoistion,minLength,extra) {

	var divs = new Array();
	for (var i = 4; i < arguments.length; i++) {
		divs.push($(arguments[i]))
	}

	// Let's determine the maximum height out of all columns specified
	var maxHeight = minLength;
	for (i = 0; i < divs.length; i++) {
		if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
	}

	maxHeight = maxHeight + extra;

	// Let's set all columns to that maximum height
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.height = maxHeight + 'px';

		// Now, if the browser's in standards-compliant mode, the height property
		// sets the height excluding padding, so we figure the padding out by subtracting the
		// old maxHeight from the new offsetHeight, and compensate!  So it works in Safari AND in IE 5.x
		if (divs[i].offsetHeight > maxHeight) {
			divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
		}
	}
	maxHeight += startPoistion;
	$(footer).style.top = maxHeight  + 'px';
}

function flexibleLayoutArrange2(footer,startPoistion,outerBox,outerBoxIncrease,minLength) {

	var divs = new Array();
	for (var i = 5; i < arguments.length; i++) {
		divs.push($(arguments[i]))
	}

	// Let's determine the maximum height out of all columns specified
	var maxHeight = minLength;
	for (i = 0; i < divs.length; i++) {
		if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
	}

	// Let's set all columns to that maximum height
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.height = maxHeight + 'px';

		// Now, if the browser's in standards-compliant mode, the height property
		// sets the height excluding padding, so we figure the padding out by subtracting the
		// old maxHeight from the new offsetHeight, and compensate!  So it works in Safari AND in IE 5.x
		if (divs[i].offsetHeight > maxHeight) {
			divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
		}
	}
	maxHeight += startPoistion;
	if($(footer)) {
		$(footer).style.top = maxHeight  + 'px';
	}

	maxHeight += outerBoxIncrease;
	$(outerBox).style.height = maxHeight  + 'px';
}

/* Function sprintf(format_string,arguments...)
 * Javascript emulation of the C printf function (modifiers and argument types
 *    "p" and "n" are not supported due to language restrictions)
 *
 * Copyright 2003 K&L Productions. All rights reserved
 * http://www.klproductions.com
 *
 * Terms of use: This function can be used free of charge IF this header is not
 *               modified and remains with the function code.
 *
 * Legal: Use this code at your own risk. K&L Productions assumes NO resposibility
 *        for anything.
 ********************************************************************************/
function sprintf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg);
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg));
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg);
      }
    converters['E'] = function(flags,width,precision,arg)
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);
      }
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg);
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg);
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
/* Function printf() END */

function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;

	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
	   return true;

	else
	   return false;
}

function bookmark()
{
	if (navigator.appName=='Microsoft Internet Explorer')
		window.external.AddFavorite(location.href, document.title);
	else
		alert("CTRL+D to add a bookmark to this site.");
}

function bookmarksite()
{
	if (navigator.appName=='Microsoft Internet Explorer')
		window.external.AddFavorite('http://'+location.hostname, document.title);
	else
		alert("CTRL+D to add a bookmark to this site.");
}

function formatCurrency(num,currency) {
	num = num.toString().replace(/\$|\,/g,"");
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+","+
	num.substring(num.length-(4*i+3));
return (((sign)?"":"-") + currency + num + "." + cents);
}

function popUp(URL,valw,valh)
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=" + valw + ",height=" + valh + "');");
	return false;
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		var relstring = anchor.getAttribute("rel");
		if(relstring){
			if (anchor.getAttribute("href") && relstring.search("/external/"))
 	  			anchor.target = "_blank";
 	  	}
	 }
}
window.onload = externalLinks;
	
function contentRef(id,change) {
	try {
		srCookie = getURLVar('sr');
		srCookie = unescape(srCookie);
		if(srCookie != ''){
			Set_Cookie( 'srCMS', srCookie, 7, '/', document.domain );
		}
		srCookie = Get_Cookie('srCMS');
		if(srCookie != null) {
			if(change) {
				$(id).update(change[srCookie]);
			}
			else {
				$(id).update(srCookie);
			}
		}
	} catch(err) {}
}

function getWebViewSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function getURLVar(urlVarName) {
	//divide the URL in half at the '?' 
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		//load all the name/value pairs into an array 
		var urlVars = urlHalves[1].split('&');
		//loop over the list, and find the specified url variable 
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){
				//load the name/value pair into an array 
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					//I found a variable that matches, load it's value into the return variable 
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}

function Set_Cookie( name, value, expires, path, domain, secure )  {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain.replace(/www./,"") : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( 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;
	}
}				

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain.replace(/www./,"") : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

<!--/* OpenX Javascript Tag v2.8.1 */-->
function OpenXAds(id){
   var m3_u = (location.protocol=='https:'?'https://'+location.hostname+'/openx/www/delivery/ajs.php':'http://'+location.hostname+'/openx/www/delivery/ajs.php');
   var m3_r = Math.floor(Math.random()*99999999999);
   if (!document.MAX_used) document.MAX_used = ',';
   document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u);
   document.write ("?zoneid=" + id);
   document.write ('&amp;cb=' + m3_r);
   if (document.MAX_used != ',') document.write ("&amp;exclude=" + document.MAX_used);
   document.write (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
   document.write ("&amp;loc=" + escape(window.location));
   if (document.referrer) document.write ("&amp;referer=" + escape(document.referrer));
   if (document.context) document.write ("&context=" + escape(document.context));
   if (document.mmm_fo) document.write ("&amp;mmm_fo=1");
   document.write ("'><\/scr"+"ipt>");
}
