/*start klick specific code*/
/*make sure all layouts (including printer-friendly pages) declare a <meta id="klick-siteroot" name="klick-siteroot" value="~/" /> in their <head> */
var siteroot = document.getElementById("klick-siteroot").getAttribute("value") || "";
try {document.execCommand('BackgroundImageCache',false,true);} catch (e) {}
var gotoPage=function(page) {alert(siteroot+page);location.href=siteroot+page;};

if (navigator.userAgent.indexOf("KHTML") > -1) Element.addClassName(document.documentElement, "safari");

Function.prototype.closure=function(obj) {//use this to prevent memory leaks
	if (!window.__objs) {
		window.__objs = [];
		window.__funs = [];
	}
	var fun = this;
	var objId = obj.__objId;
	if (!objId) __objs[objId = obj.__objId = __objs.length] = obj;
	var funId = fun.__funId;
	if (!funId) __funs[funId = fun.__funId = __funs.length] = fun;
	if (!obj.__closures) obj.__closures = [];
	var closure = obj.__closures[funId];
	if (closure) return closure;
	obj = null;
	fun = null;
	return __objs[objId].__closures[funId] = function () {
		return __funs[funId].apply(__objs[objId], arguments);
	};
}
Event.observe(window,"unload",function() {
	window.__objs=null;
	window.__funs=null;
});

//prototype's document.getElementsByClassName is unbelievably slow. Here's a faster version.
OptimizeSpeed={
	getElementsByClassName:function(needle) {
		if (document.evaluate) {
			var q = ".//*[contains(concat(' ', @class, ' '), ' " + needle + " ')]";
			var results=[];
			var query = document.evaluate(q, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			for (var i = 0, length = query.snapshotLength; i < length; i++) results.push(query.snapshotItem(i));
			return results;
		}
		else {//compressing to make it faster. Things are the way they are for a good reason, don't poke around.
			var a = document.getElementsByTagName("*"),l=a.length,r=[],i,j;
			for (i=j=0;i<l;i++) {
				var ai=a[i],c = " " + ai.className + " ";
				if (c.indexOf(" " + needle + " ") != -1) {r[j++] = ai;}
			}
			return r;
		}//end
	}
};
/*end klick specific code*/

/**
 *  Modal Dialog Configuration
 *  Displayes the modal dialog forms while denying access to the underlying html
 */
var sony={modalDialog:{},tooltip:{}};

/**
 *  Object to store rendered dialogs so we don't render them more than once
 */
var renderedDialogs = {};

/**
 *  Function to handle opening a modal dialog
 *  fixes some display quirks when these steps are done in the init function
 *
 *  @param string el name of the dialog box to display
 */
var modalMask=null;
function showModalDialog(el,w,h)
{
	if(renderedDialogs[el] === undefined) {
		renderedDialogs[el]=$(el);
		el=$(el);
		var c=document.createElement("div");
		Element.addClassName(c, "modalbody");
		var mask = $("mask") == null ? document.createElement("div") : $("mask");
		mask.id="mask";
		c.appendChild(el);
		Element.addClassName(c, "modalbody")
		document.body.appendChild(c);
		document.body.appendChild(mask);
		/*@cc_on
			var iframe=document.createElement("iframe");
			mask.appendChild(iframe);
			iframe.src="javascript:document.write('<body bgcolor=black></body>');";
			iframe.style.filter="alpha(opacity=0)"
			iframe.frameBorder=0;
			Object.extend(iframe.style,{position:"absolute",left:"0px",top:"0px",width:"100%",height:"100%",zIndex:80,display:"block"});
		@*/
		Object.extend(c.style,{position:"absolute",left:"0px",top:"0px",width:"100%",zIndex:100});
		Object.extend(el.style,{display:"block",margin:"20px auto",zIndex:100});
		var height = document.documentElement.offsetHeight || document.body.offsetHeight;
		Object.extend(mask.style,{position:"absolute",left:"0px",top:"0px",width:"100%",zIndex:80});
		var buttons = document.getElementsByClassName(elName_button,el);
		for(var i = 0,l=buttons.length; i < l; i++) {initButton(buttons[i]);}
	}
	el = $(el);
	Element.show($(el).parentNode);
	Element.show(modalMask=document.getElementById("mask"));

	try {
		var scrollTop = (document.body.scrollTop||window.pageYOffset||document.documentElement.scrollTop);
		var top = parseInt(scrollTop + (document.viewport.getHeight() / 2) - ($(el).parentNode.offsetHeight / 2));
		if (top < scrollTop) top = scrollTop;
		$(el).parentNode.style.top = top + "px";
		var mask = $("mask");
		if (mask) {
			var offsetBottom = top + $(el).offsetHeight;
			if (offsetBottom < document.body.offsetHeight) offsetBottom = document.body.offsetHeight;
			var finalHeight = mask.offseHeight > offsetBottom + 100 ? mask.offsetHeight : offsetBottom + 100;
			if (isNaN(finalHeight)) finalHeight = 0;
			
			mask.style.height = finalHeight + "px";
		}
	}
	catch (e) {}
}

/**
 *  Function to handle opening a modal dialog with an element to ajax into
 *
 *  @param string el name of the dialog box to display
 *  @param string url to ajax into el
 */
function showAjaxedModalDialog(el,url,w,h)
{
	var x=new Ajax.Updater(el,url,{method: 'GET',evalScripts:true,onComplete:function() {showModalDialog(el,w,h);initTooltips();}});
}

/**
 *  Function to handle closing a modal dialog
 *
 *  @param string el name of the dialog box to close
 */
function closeModalDialog(el)
{
	el=$(el);
    Element.hide(el.parentNode);
    if ($A(document.getElementsByClassName("modalbody")).reject(function(el) {return el.style.display == "none"}).length == 0) {
		Element.hide(modalMask);
	}
}


var resetField = function(field){
	$(field).observe('click', function(){
	$(field).writeAttribute("value", "");      
		 $(field).setStyle({
            color: '#666'
        });
    });
}

/**
 *  Changes cell color for an entire table row on mouseover
 */
function hiliteRowOn(el) {
    var cells = $(el).getElementsByTagName("td");
    for(var c=0,l=cells.length; c < l; c++) {
		var cellsc=cells[c];
        Element.removeClassName(cellsc,"lo");
        Element.addClassName(cellsc,"hi");
    }
}

/**
 *  Changes cell color for an entire table row on mouseout
 */
function hiliteRowOff(el) {
    var cells = $(el).getElementsByTagName("td");
    for(var c=0,l=cells.length; c < l; c++) {
		var cellsc=cells[c];
        Element.removeClassName(cellsc,"hi");
        Element.addClassName(cellsc,"lo");
    }
}

function showTourMovie(movie,title) {
	document.getElementById('tourMovieTitle').innerHTML = title;
	var flashTour = new SWFObject(siteroot+"local/richmedia/flash/tour.swf", "flashTour", "204", "204", "7", "#efefef");
	flashTour.addVariable("videoFile",movie);
	flashTour.addVariable("videoLabel","");

	if((navigator.appName.indexOf("Microsoft") != -1)) {
		showModalDialog('tourMovie',350);
		flashTour.write('tourMovieContainer');
	} else {
		flashTour.write('tourMovieContainer');
		showModalDialog('tourMovie',350);
	}
}

function showTourMovie2(movie,title) {

	document.getElementById('tourMovieTitle').innerHTML = title;
	var flashTour = new SWFObject(siteroot+"local/richmedia/flash/"+movie, "flashTour", "204", "204", "8", "#efefef");
	flashTour.addVariable("videoFile",movie);
	flashTour.addVariable("videoLabel","");

	if((navigator.appName.indexOf("Microsoft") != -1)) {
		showModalDialog('tourMovie',350);
		flashTour.write('tourMovieContainer');
	} else {
		flashTour.write('tourMovieContainer');
		showModalDialog('tourMovie',350);
	}
}



function closeTourMovie() {

	document.getElementById('tourMovieContainer').innerHTML = "&nbsp;";
	closeModalDialog('tourMovie');
}

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;
}

/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;

/*sony specific*/

var isIE = (navigator.appName.indexOf("Microsoft") != -1);

var imgPath_spacer = siteroot + "local/images/global/spacer.gif";

/* element names */

var elName_button = "button";
var elName_filler = "filler";
var elName_username = "username";
var elName_password = "password";
var elName_error = "error";
var elName_dropdown = "dropdown";
var elName_png = "pngFix";

var elName_tabCurrent = "tabNavCurrent";
var elName_tabShow = "tabShow";
var elName_tabHide = "tabHide";

/* flash tour parameters */

var flashPath_flashTour = siteroot+"local/richmedia/flash/tour.swf";

var elId_flashTourDiv = "boxTour";
var elId_tourButton = "tourButton";

var imgPath_showTourButton = siteroot+"local/images/global/buttons/btn_showtour_up.gif";
var imgPath_hideTourButton = siteroot+"local/images/global/buttons/btn_hidetour_up.gif";

var altText_showTourButton = "SHOW TOUR";
var altText_hideTourButton = "HIDE TOUR";

/* button parameters */

var buttonExt_up = "up";
var buttonExt_over = "ov";
var buttonExt_down = "dn";
var buttonExt_disabled = "ds";


/* utility functions */

function getScrollY() {
	if(typeof window.pageYOffset != 'undefined')
		return window.pageYOffset;
	else if(document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	else if(document.body.scrollTop)
		return document.body.scrollTop;
	else
		return 0;
}

function initFaqs() {
	var faqs = OptimizeSpeed.getElementsByClassName("faq");

	for(var i = 0,l=faqs.length; i < l; i++) {
		var faqsi=faqs[i];
		faqsi.href = "javascript:;";
		Event.observe(faqs[i],"click",function() {toggleElement('a'+this.id.substr(1));}.closure(faqsi));
	}
}

function initButton(el) {
	Event.observe(el,"mouseover",function() {
		var buttonSrc = el.src.substr(0,el.src.length-6);
		var buttonExt = el.src.substr(el.src.length-4);
		if (this.src.indexOf("_ds.")<0) this.src = buttonSrc+buttonExt_over+buttonExt;
	}.closure(el));
	Event.observe(el,"mouseout",function() {
		var buttonSrc = el.src.substr(0,el.src.length-6);
		var buttonExt = el.src.substr(el.src.length-4);
		if (this.src.indexOf("_ds.")<0) this.src = buttonSrc+buttonExt_up+buttonExt;
	}.closure(el));
	Event.observe(el,"mouseup",function() {
		var buttonSrc = el.src.substr(0,el.src.length-6);
		var buttonExt = el.src.substr(el.src.length-4);
		if (this.src.indexOf("_ds.")<0) this.src = buttonSrc+buttonExt_up+buttonExt;
	}.closure(el));
	Event.observe(el,"mousedown",function() {
		var buttonSrc = el.src.substr(0,el.src.length-6);
		var buttonExt = el.src.substr(el.src.length-4);
		if (this.src.indexOf("_ds.")<0) this.src = buttonSrc+buttonExt_down+buttonExt;
	}.closure(el));
}

/**
 * fix PNG images for IE
 */

function initPNGs() {
	var pngs = OptimizeSpeed.getElementsByClassName(elName_png);

	for(var i = 0,l=pngs.length; i < l; i++) {
		var pngsi=pngs[i], pngSrc = pngsi.src;
		pngsi.src = imgPath_spacer;
		pngsi.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+pngSrc+"', sizingMethod='scale')";
	}
}

/**
 * form field filler
 */

function initFillers() {
	var fillers = OptimizeSpeed.getElementsByClassName(elName_filler);

	for(var i = 0,l=fillers.length; i < l; i++) {
		if(fillers[i].type == "text") {
			var fillerText = fillers[i].value;
			if(fillerText != null & fillerText != "") {
				Event.observe(fillers[i],"focus",function() {if(this.value == fillerText) this.value = '';}.closure(fillers[i]));
				Event.observe(fillers[i],"blur",function() {if(this.value == '') this.value = fillerText;}.closure(fillers[i]));
			}
		}
	}
	
	//IE7 onchange bug workaround - there's voodoo magic going on, do not touch
	window.jscript/*@cc_on=@_jscript_version@*/
	if (window.jscript==5.7) {//if IE7
		var inputs = document.getElementsByTagName("input"), i=-1, l=inputs.length;
		while (++i!==l) {
			var inputs_i=inputs[i];
			if ((inputs_i.type=="checkbox")&&inputs_i.onchange) {
				inputs_i._onchange=inputs_i.onchange;
				inputs_i.onchange=null;
				Event.observe(inputs_i,"propertychange",function() {if (event.propertyName=='checked') this._onchange();}.closure(inputs_i));
			}
		}
	}
}

function initUsernames() {
	var usernames = OptimizeSpeed.getElementsByClassName(elName_username);
	for(var i = 0,l=usernames.length; i < l; i++) {
		Event.observe(usernames[i],"focus",function() {Element.removeClassName(this,'username');}.closure(usernames[i]));
		Event.observe(usernames[i],"change",function() {Element.removeClassName(this,'username');}.closure(usernames[i]));
		Event.observe(usernames[i],"blur",function() {if (this.value.length == 0) Element.addClassName(this,'username');}.closure(usernames[i]));
		if (usernames[i].value.length > 0) {
			Element.removeClassName(usernames[i],'username');
		}
	}
}

function initPasswords() {
	var passwords = OptimizeSpeed.getElementsByClassName(elName_password);
	for(var i = 0,l=passwords.length; i < l; i++) {
		if(passwords[i].type == "password") {
			Event.observe(passwords[i],"focus",function() {Element.removeClassName(this,'password');}.closure(passwords[i]));
			Event.observe(passwords[i],"change",function() {Element.removeClassName(this,'password');}.closure(passwords[i]));
			Event.observe(passwords[i],"blur",function() {if (this.value.length==0) Element.addClassName(this,'password');}.closure(passwords[i]));
		}
	}
}

/**
 * form field error states
 */

function initErrors() {
	var errors = OptimizeSpeed.getElementsByClassName(elName_error);
	for(var i = 0,l=errors.length; i < l; i++) {
		if(errors[i].tagName == "SELECT" || (errors[i].tagName == "INPUT" & errors[i].type == "text") || (errors[i].tagName == "INPUT" & errors[i].type == "file")) {
			Event.observe(errors[i],"focus",function() {this.style.backgroundColor = '#fff'; this.style.color = '#666';}.closure(errors[i]));
		}
	}
}

/**
 * hide/show flash tour
 */

function toggleTour(file,label) {
	var tourButton = document.getElementById(elId_tourButton);
	if(document.getElementById(elId_flashTourDiv).style.display != "block") {
		if(tourButton) {
			tourButton.src = imgPath_hideTourButton;
			tourButton.altText = altText_hideTourButton;
			tourButton.title = altText_hideTourButton;
			initButton(tourButton);
		}
		var flashTour = new SWFObject(flashPath_flashTour, "flashTour", "204", "204", "7", "#efefef");
		flashTour.addVariable("videoFile",file);
		flashTour.addVariable("videoLabel",label);
		flashTour.write(elId_flashTourDiv);
		document.getElementById(elId_flashTourDiv).style.display = "block";
	} else {
		if(tourButton) {
			tourButton.src = imgPath_showTourButton;
			tourButton.altText = altText_showTourButton;
			tourButton.title = altText_showTourButton;
			initButton(tourButton);
		}
		document.getElementById(elId_flashTourDiv).style.display = "none";
		document.getElementById(elId_flashTourDiv).innerHTML = "&nbsp;";
	}
}

function hideTour() {

	document.getElementById(elId_flashTourDiv).style.display = "none";
	document.getElementById(elId_flashTourDiv).innerHTML = "&nbsp;";
}

/**
 * hide/show a page element
 */

function toggleElement(elId) {
	if($(elId).style.display == "block")
		$(elId).style.display = "none";
	else
		$(elId).style.display = "block";
}

/**
 * hide/show two page elements
 */

function toggleElements(elOne,elTwo) {
	if($(elOne).style.display == "block" || $(elOne).style.display == "") {
		$(elOne).style.display = "none";
		$(elTwo).style.display = "block";
	} else {
		$(elOne).style.display = "block";
		$(elTwo).style.display = "none";
	}
}

function toggleSubmit(el) {

	var button = OptimizeSpeed.getElementsByClassName("buttonSubmit")[0];

	if(el.checked) {

		button.disabled = "";
		button.src = siteroot+"local/images/global/buttons/btn_submit_up.gif";
		initButton(button);

	} else {

		button.src = siteroot+"local/images/global/buttons/btn_submit_disabled.gif";
		button.disabled = "disabled";
	}
}

/**
 * forms
 */

 function submitForm(id) {
	 $(id).submit();
	 return false;
 }

 function submitAjaxForm(id) {
	 $(id).onsubmit();
	 return false;
 }

 function doRedirect(url) {
	 window.location = siteroot + url;
 }
 
 function doRedirectNoRoot(url) {
	 window.location = url;
 }
 
/**
 * tabbed elements
 */

function openTab(tab,el) {
    var ul = el.parentNode.parentNode;
    var lis = ul.getElementsByTagName('li');
	for(i=0; i<lis.length; i++) {
		Element.removeClassName(lis[i],elName_tabCurrent);
	}
    Element.addClassName(el.parentNode,elName_tabCurrent);
    el.blur();
    var tabContents = OptimizeSpeed.getElementsByClassName(elName_tabShow)[0];
    Element.removeClassName(tabContents,elName_tabShow);
    Element.addClassName(tabContents,elName_tabHide);
    Element.addClassName(tab,elName_tabShow);
	

	//fix for IE redraw
	var boxTabbedDetails = $(tab).up(".boxTabbedDetails")
	if (boxTabbedDetails) boxTabbedDetails.select(".bb div,.tabNav").each(function(e) {e.style.zoom = 0;e.style.zoom = 1;});

	for(i=0; i<lis.length; i++) {
		if (lis[i].firstChild.id != null) {
			sname = lis[i].firstChild.id.substr(0,lis[i].firstChild.id.length-3);
			if(document.getElementById(sname+"Intro"))
				document.getElementById(sname+"Intro").style.display = "none";
		}
	}
	var sname = el.id.substr(0,el.id.length-3);
	if(document.getElementById(sname+"Intro"))
		document.getElementById(sname+"Intro").style.display = "block";
}

/**
 *  CREATE TOOLTIPS DYNAMICALLY
 *  HOWTO: <a href="javascript:;" class="tooltip" title="text to appear in tooltip">Link Text</a>
 */

/**
 * makeTooltipText
 * @param string text text to insert into the tooltip look and feel
 * @return string HTML Tooltip
 */
function makeTooltipText(text) {
    if(text.length > 100)
		ttclass = 'tooltipLarge';
	else
		ttclass = 'tooltip';

	return tooltipBody = ' \
        <div class="'+ttclass+'"> \
            <div class="ttt">&nbsp;</div> \
            <div class="ttm">'+ text +'</div> \
            <div class="ttb">&nbsp;</div> \
        </div>';
}

/**
 * showTooltip
 * onMouseOver event handler for tooltip links
 * @param object e the event object
 */
function showTooltip(e) {
   this.title=new String();
   var t=$(this.id+"Body");
   Element.show(t);
   var offset = $(this).cumulativeOffset();
   t.style.left = offset[0] + "px";
   t.style.top = offset[1] - t.offsetHeight + "px";
}

/**
 * hideTooltip
 * onMouseOut event handler for tooltip links
 * @param object e the event object
 */
function hideTooltip(e) {
	Element.hide(this.id+"Body");
}

/**
 * initTooltips
 * Initializes the tooltip links on the page.  This is run after the document has fully loaded.
 */
function initTooltips()
{
    var tooltips = OptimizeSpeed.getElementsByClassName("tooltip");
    for(var t=0; t<tooltips.length; t++) {
        // grab the id of the tooltip
		var id = "srToolTip" + t;
		tooltips[t].id = id;
        var el = $(id);
        // only process tooltips with text in the title attribute
        if(el.getAttribute("title")) {
            var tooltipText = makeTooltipText(el.getAttribute("title"));
			var c = document.createElement("div");
			document.body.appendChild(c);
			Object.extend(tooltips[t].style,{position:"relative"});
			Object.extend(c,{id:id+"Body",innerHTML:tooltipText})
			//var s="";for (var i in el) if (i.match(/top/gi)) s+=i+"\n";alert(s);
			Object.extend(c.style,{position:"absolute",top:el.offsetTop-c.offsetHeight+"px",left:el.offsetLeft+"px",display:"none",zIndex:10000});
            $(id).onmouseover=showTooltip;
            $(id).onmouseout=hideTooltip;
        }
    }
}

/**
 * Add the window.onload event handler to init the tooltips on the page
 */


/**
 * initProductThumbs
 * Initializes the product thumbnail links on the page.  This is run after the document has fully loaded.
 */
function initProductThumbs()
{
    var tooltips = OptimizeSpeed.getElementsByClassName("prodThumb");
    for(var t=0; t<tooltips.length; t++) {
        // grab the id of the tooltip
        var id = "srProdThumb" + t;
		tooltips[t].id=id;
        var el = $(id);
        var tooltipText = el.getAttribute("title");
		var c = document.createElement("div");
		document.body.appendChild(c);
		Object.extend(tooltips[t].style,{position:"relative"});
		Object.extend(c,{id:id+"Body",innerHTML:tooltipText})
		Object.extend(c.style,{position:"absolute",top:el.offsetTop+15+"px",left:el.offsetLeft+"px",display:"none"});
        Event.observe(id,"mouseover",showTooltip.closure(el));
        Event.observe(id,"mouseout",hideTooltip.closure(el));
    }
}
/**
 * Add the window.onload event handler to init the tooltips on the page
 */

function initForms() {
	var inputs=document.getElementsByTagName("input"),u=$("topLoginUsername");
	for (var i=0,l=inputs.length;i<l;i++) {
		if (inputs[i].type=="text"||inputs[i].type=="password") {
			Event.observe(inputs[i],"focus",function() {this.select();}.closure(inputs[i]));
		}
	}
	eval('if (u) u.onfocus=function() {if (this.value=="Username") this.value=""; else this.select();}.closure(u)');
}

/*init homepage affinity options*/
var currentProfile=null;
function initHomeProfiles() {
	var profiles=document.getElementsByClassName("homeProfile");
	for (var i=0,l=profiles.length;i<l;i++) {
		if (profiles[i].getElementsByTagName("img")[0].src.indexOf("_sel")>-1) currentProfile=profiles[i];
		profiles[i].onclick=function() {
			var current=currentProfile.getElementsByTagName("img")[0];
			var next=this.getElementsByTagName("img")[0];
			if (next.src.indexOf("_sel")<0) {
				current.src=current.src.replace("_sel","");
				next.src=next.src.substring(0,next.src.length-4)+"_sel"+next.src.substring(next.src.length-4);
				currentProfile=this;
			}
		}.closure(profiles[i]);
	}
}

function setRotatingOffers() {
	var time=5;//in seconds
	var current=0;

	var banners = document.getElementsByClassName("banner");
	var length = banners.length;
	var swap = function() {
		banners[current].style.display = "none";
		current = current + 1 == banners.length ? 0 : current + 1;
		banners[current].style.display = "block";
	}
	setInterval(swap, time * 1000);
}

function setRotatingAds(rotation_time_s) {
	var current=0;
	var banners = document.getElementsByClassName("adbanner");
	var length = banners.length;
	var swap = function() {
		banners[current].style.display = "none";
		current = current + 1 == banners.length ? 0 : current + 1;
		banners[current].style.display = "block";
	}
	setInterval(swap, rotation_time_s * 1000);
}

var initSubNav = function() {
	if ($("subNavScrollable")&&$("subNavContainer")&&$("subNavScrollLeft")&&$("subNavScrollRight")) {
		var subNavScrolling = {
			position:0,
			guid:null,
			start:function(speed) {
				var scrollable = $("subNavScrollable");
				if (!this.guid) {
					this.guid = setInterval(function() {
						this.position = this.position + speed > 0 || this.position + speed < $("subNavContainer").offsetWidth - $("subNavScrollable").offsetWidth ? this.position : this.position + speed;
						scrollable.style.left = this.position + "px"
						$("subNavContainer").offsetWidth - $("subNavScrollable").offsetWidth
					}.bind(this),1);
				}
			},
			stop:function() {
				clearInterval(this.guid);
				this.guid = null;
			}
		};
		Event.observe($("subNavScrollLeft"),"mouseover",function() {subNavScrolling.start(1);});
		Event.observe($("subNavScrollLeft"),"mouseout",function() {subNavScrolling.stop();});
		Event.observe($("subNavScrollRight"),"mouseover",function() {subNavScrolling.start(-1);});
		Event.observe($("subNavScrollRight"),"mouseout",function() {subNavScrolling.stop();});
		$("subNavContainer").offsetWidth +","+ $("subNavScrollable").offsetWidth
		if ($("subNavContainer").offsetWidth < $("subNavScrollable").offsetWidth) {
			$("subNavScrollLeft").style.display="inline"
			$("subNavScrollRight").style.display="inline"
		}
	}
}
var initCollapserTables = function() {
	var collapsers = document.getElementsByClassName("collapser");
	for (var i = 0, l = collapsers.length; i < l; i++) {
		Element.cleanWhitespace(collapsers[i]);
		var titles = collapsers[i].getElementsByTagName("th");
		for (var j = 0, m = titles.length; j < m; j++) {
			Event.observe(titles[j], "click", function() {
				if (Element.hasClassName(this.parentNode, "expanded")) {
					Element.removeClassName(this.parentNode, "expanded")
					Element.addClassName(this.parentNode, "collapsed")
					Element.removeClassName(this.parentNode.parentNode.nextSibling, "expanded")
					Element.addClassName(this.parentNode.parentNode.nextSibling, "collapsed")
				}
				else {
					Element.removeClassName(this.parentNode, "collapsed")
					Element.addClassName(this.parentNode, "expanded")
					Element.removeClassName(this.parentNode.parentNode.nextSibling, "collapsed")
					Element.addClassName(this.parentNode.parentNode.nextSibling, "expanded")
				}
			}.bind(titles[j]));
		}
	}
}


/* page load */
var hasTooltips=hasThumbnails=hasButtons=hasFillers=hasErrors=hasPNGs=hasUsernames=hasPasswords=hasForms=hasSubNav=true;
var hasFAQs=hasHomeProfiles=false;
function pageInit(event) {
	if (hasTooltips) initTooltips();
	if (hasThumbnails) initProductThumbs();
	if (hasButtons) {
		var buttons = OptimizeSpeed.getElementsByClassName(elName_button);
		for(var i = 0,l=buttons.length; i < l; i++) initButton(buttons[i]);
	}
	if (hasFillers) initFillers();
	if (hasErrors) initErrors();
	if (hasPNGs && isIE) initPNGs();
	if (hasFAQs) initFaqs();
	if (hasUsernames) initUsernames();
	if (hasPasswords) initPasswords();
	if (hasForms) initForms();
	if (hasHomeProfiles) initHomeProfiles();
	if (hasSubNav) initSubNav();
	initCollapserTables();
}

Event.observe(window,"load",pageInit);//onDOMReady doubles the load time =(
/*cart specific*/

ShoppingCartDivURL = "/elements/widgets/shopping_cart/";

var UpdateShoppingCartBanner = function () {
	if ($("ShoppingCartDiv") != null) {
		var fixIE = function() {document.getElementsByClassName("boxRightRailHolder")[0].innerHTML = document.getElementsByClassName("boxRightRailHolder")[0].innerHTML;};
		new Ajax.Updater($("ShoppingCartDiv").parentNode, ShoppingCartDivURL, {onComplete:fixIE});
	}
	
	refreshpanels();
}

/* Shopping Cart Object */

/**
 *  Cart object/functionality
 */
var Cart =
{
    /**
     *  Configuration Variables
     */
    items: [],
    result: {},
    caller: {},

	cartEl: "cartContents",

	busyText: "Adding item to cart.",

	tooltipEl: "tooltip",
	tooltipId:0,

	buttonPath: null,
	buttonOnmouseover: null,
	buttonOnmouseout: null,
	buttonOnkeyup: null,
	buttonOnkeydown: null,

    /**
     *  handleAddSuccess
     *  Handles the succes state from the XHR object
     *  @param object o XHR object
     */
    handleAddSuccess: function(o,el) {
		UpdateShoppingCartBanner();
        el.onclick=el.oldonclick;
		if(o.responseText !== undefined) {
            var result = o.responseText;
            this.processResult(result,false,el);
        }
    },
    /**
     *  handleFailure
     *  Handles the failure state from the XHR object
     *  @param object o XHR object
     */
    handleFailure: function(o,el) {
        var result = o.status + " " + o.statusText;
        this.processResult(result,true,el);
    },
    /**
     *  processResult
     *  Processes the results from the success or failure handlers
     *  @param object data JSON Object encapsulating the returning data from the cart functionality call
     *  @param boolean isFailure is true, will trigger error handling
     */
    processResult: function(data, isFailure, el) {
        if(isFailure) {
            //alert("Transaction failed: " + data);
        } else {
			try {
				this.result = eval("(" + data + ")");
				if (this.result.successMsg != undefined) var msg=this.result.successMsg;
				else if (this.result.errorMsg != undefined) var msg=this.result.errorMsg;
				else {location.href=siteroot+"en/login/?u="+escape(location.href);}
				
				if(this.result.loginRedirect) {
					location.href=siteroot+"en/login/?u="+escape(location.href);
				}else{
					this.displayMessage(el,msg);
				}
				
				if(this.result.extraJavascript) {
					try {eval(this.result.extraJavascript);} catch (e) { }
				}
			} catch (e) {
				//alert(e.toString()+" on Ajax response"); alert(data)
			}
		}
		refreshpanels();
    },
    /**
     *  add
     *  Adds the item to the user's cart
     *  @param string path Path to the backend script that handles the actual heavy lifting
     *  @param object el the object calling this function
     */
	add: function(path,el, gotologin) {
		//this.displayMessage(el,this.busyText);
		////passing the querystring to bypass IE's caching. Make sure to send no-cache headers with the ajax response too please
		var append = path.indexOf("?") > -1 ? "&" : "?";
		el.oldonclick=el.onclick;
		el.onclick="";
        new Ajax.Request(path+append+"cachebypass="+Math.random() + "&gotologin=" + (gotologin ? "true" : "false"),{method:"GET",onSuccess:function(o) {Cart.handleAddSuccess(o,el)}});
    },
    /**
     *  displayMessage
     *  trigger function for the tooltip population function
     *  @param object el the object calling this function
     *  @param string msg The message to show
     */
    displayMessage: function(el,msg) {
		if (el.tooltipId) var e=$(el.tooltipId); else {e=$(this.tooltipEl).cloneNode(true);e.id=el.tooltipId="cartTooltip"+this.tooltipId++;}
		Element.addClassName(e,"tooltipClone");
		Element.cleanWhitespace(e);
		var b=e.firstChild.nextSibling;
		b.replaceChild(document.createTextNode(msg),b.firstChild);
		el.parentNode.insertBefore(e,el);
		e.style.visibility="hidden";//hide temporarily
		e.style.position="absolute";
		e.style.display="block";
		Object.extend(e.style,{position:"absolute",marginTop:-e.offsetHeight+"px",zIndex:110});
		e.style.visibility="inherit";//once everything is in the right place, show it
		setTimeout(function() {Element.hide(e);e=null;},4000);
    },
    /**
     *  unlock
     *  unlocks the elements on the page to ready them for user interaction
     */
    unlock: function() {
		this.locked = false;
		this.caller.firstChild.src = this.buttonPath;
		this.caller.firstChild.onmouseover = this.buttonOnmouseover;
		this.caller.firstChild.onmouseout = this.buttonOnmouseout;
		this.caller.firstChild.onkeydown = this.buttonOnkeydown;
		this.caller.firstChild.onkeyup = this.buttonOnkeyup;
    },
    /**
     *  lock
     *  locks the elements on the page to deny user interaction until the XHR has completed
     */
    lock: function() {
        this.locked = true;
		this.buttonPath = this.caller.firstChild.src;
		this.buttonOnmouseover = this.caller.firstChild.onmouseover;
		this.buttonOnmouseout = this.caller.firstChild.onmouseout;
		this.buttonOnkeydown = this.caller.firstChild.onkeydown;
		this.buttonOnkeyup = this.caller.firstChild.onkeyup;
		this.caller.firstChild.src = this.buttonPath.substr(0,this.buttonPath.length-6)+"gr.gif";
		this.caller.firstChild.onmouseover = "";
		this.caller.firstChild.onmouseout = "";
		this.caller.firstChild.onkeydown = "";
		this.caller.firstChild.onkeyup = "";
    }
};

/*wishlist specific*/

function refreshWishList(url,el,doRefreshInfographic) {
	if ($('WishListDiv')!=null)
		new Ajax.Updater('WishListDiv', url, {evalScripts:true, method:'GET'});
	if (el) Wishlist.displayMessage(el,Wishlist.removeText)
	if (doRefreshInfographic)
		refreshinfographic();
}

function refreshWishListInfographic(currenttotal, maxtotal) {
	var info = $('info_wishlist');
	if (info != null) {
		if (currenttotal > 0) {
			var msg = currenttotal + " of " + maxtotal + " max items";
			var METER_WIDTH = 180;
			var width = Math.ceil(METER_WIDTH * currenttotal/maxtotal);
			if ($('infographic_message'))
				$('infographic_message').innerHTML = msg;
			if ($('infographic_bar'))
				$('infographic_bar').style.width = width+"px";
			info.removeClassName('boxHide');
			if ($('infoOther_wishlist')) $('infoOther_wishlist').addClassName('boxHide');
		} 
		else {
			if ($('infoOther_wishlist')) $('infoOther_wishlist').removeClassName('boxHide');
			info.addClassName('boxHide');
		}
	}
}

/* Wishlist Object */

/**
 *  Wishlist object/functionality
 */
var Wishlist =
{

    /**
     *  Configuration Variables
     */
    items: [],
    result: {},
    caller: {},

	busyText: "Adding item to wish list.",
	removeText: "Removing item from wish list.",

	linkClass: "linkInWish",
	linkText: "In Your Wish List",
	linkHref: "#",

	tooltipEl: "tooltip",
	tooltipId:0,
    /**
     *  handleAddSuccess
     *  Handles the succes state from the XHR object
     *  @param object o XHR object
     */
    handleAddSuccess: function(o,el) {
        el.onclick=el.oldonclick;
        if(o.responseText !== undefined) {
            var result = o.responseText;
			el.linkText = "In Your Wish List";
            this.processResult(result,false,el);
        }
    },
	/**
     *  handleRemoveSuccess
     *  Handles the succes state from the XHR object
     *  @param object o XHR object
     */
    handleRemoveSuccess: function(o,el) {
        if(o.responseText !== undefined) {
            var result = o.responseText;
			el.linkText = "Item Removed";
            this.processResult(result,false,el);
        }
    },
    /**
     *  handleFailure
     *  Handles the failure state from the XHR object
     *  @param object o XHR object
     */
    handleFailure: function(o,el) {
        var result = o.status + " " + o.statusText;
        this.processResult(result,true,el);
    },
    /**
     *  processResult
     *  Processes the results from the success or failure handlers
     *  @param object data JSON Object encapsulating the returning data from the wishlist functionality call
     *  @param boolean isFailure is true, will trigger error handling
     */
    processResult: function(data, isFailure, el) {
		var result;
        if(isFailure) {
            alert("Transaction failed: " + data);
        } else {
            try {
			result = eval("(" + data + ")")} catch (e) {alert(e.toString()+" on Ajax response");}
			if (result.successMsg != undefined) var msg=result.successMsg;
			else if (result.errorMsg != undefined) var msg=result.errorMsg;
			else {location.href=siteroot+"en/login/?u="+escape(location.href);}
			if (msg) this.displayMessage(el,msg);
			if(result.successMsg) el.innerHTML = el.linkText;
			else if (result.errorMsg) el.innerHTML = "Your Wish List is Full"
			if(result.extraJavascript) {
				try {eval(result.extraJavascript);} catch (e) { }
			}
			if (result.maxtotal) {
				refreshWishListInfographic(result.currenttotal, result.maxtotal);
			}
		}
    },
    /**
     *  add
     *  Adds the item to the user's wishlist
     *  @param string path Path to the backend script that handles the actual heavy lifting
     *  @param object el the object calling this function
     */
    add: function(path,el,onCompleteFunction) {
		//this.displayMessage(el,this.busyText);
		el.oldonclick = el.onclick;
		el.onclick = "";
		if (onCompleteFunction) new Ajax.Request(path,{method:"GET",onSuccess:function(o) {Wishlist.handleAddSuccess(o,el)},onComplete:onCompleteFunction});
		else new Ajax.Request(path + (path.indexOf("?") < 0 ? "?" : "&") + "cachebypass="+Math.random(),{method:"GET",onSuccess:function(o) {Wishlist.handleAddSuccess(o,el)}});
    },
	/**
     *  remove
     *  Removes the item from the user's wishlist
     *  @param string path Path to the backend script that handles the actual heavy lifting
     *  @param object el the object calling this function
     */
    remove: function(path,el) {
		this.displayMessage(el,this.removeText);
        new Ajax.Request(path,{method:"GET",onSuccess:function(o) {Wishlist.handleRemoveSuccess(o,el)}});
    },
    /**
     *  displayMessage
     *  trigger function for the tooltip population function
     *  @param object el the object calling this function
     *  @param string msg The message to show
     */
    displayMessage: function(el,msg) {
		if (el.tooltipId) var e=$(el.tooltipId); else {e=$(this.tooltipEl).cloneNode(true); e.id=el.tooltipId="wishlistTooltip"+this.tooltipId++; }
		Element.addClassName(e,"tooltipClone");
		Element.cleanWhitespace(e);
		var b=e.firstChild.nextSibling;
		b.replaceChild(document.createTextNode(msg),b.firstChild);
		el.parentNode.insertBefore(e,el);
		e.style.visibility="hidden";//hide temporarily
		e.style.position="absolute";
		e.style.display="block";
		Object.extend(e.style,{position:"absolute",marginTop:-e.offsetHeight+"px",zIndex:110});
		e.style.visibility="inherit";//once everything is in the right place, show it
		setTimeout(function() {Element.hide(e);e=null;},4000);
    }
};

/* cookie utility function */
var Cookie={
	set:function(c_name,value,expiredays,cookiepath) {
		if(expiredays){
			var exdate=new Date();
			exdate.setDate(exdate.getDate() + expiredays);
		}
		var cookieval=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : "; expires="+exdate)+
		((cookiepath==null)?"":"; path="+cookiepath);
		document.cookie=cookieval;
	},
	get:function(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return "";
	},
	remove:function(c_name) {this.set(c_name,"",-1);}
}

/* extract query string variables with js */
var QueryString={
	get:function(q_name) {
		if (window.location.search && window.location.search != "") {
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			for (var i=0;i<vars.length;i++) {
				var pair = vars[i].split("=");
				if (pair[0] == q_name)
					return pair[1];
			}
		}
		return "";
	}
}

refreshdashboard=function(id,action) {
	var url = window.location.pathname;
	var homepageAffinity = 'base';
	if (url.indexOf('/en/home/') == 0) {
		homepageAffinity = url.replace('/en/home/','');
		var i = homepageAffinity.indexOf('/');
		if (i > -1) homepageAffinity = homepageAffinity.substring(0,i);
	}
	else {
		homepageAffinity = Cookie.get("HomepageAffinity").toLowerCase();
	}
	new Ajax.Updater(id, '/elements/widgets/dashboard/'+homepageAffinity+'/'+action, { method: 'GET', evalScripts: true });
}

refreshinfographic = function() { refreshdashboard('DashboardInfographic', '_infographic'); }

refreshpanels = function() { refreshdashboard('DashboardPanels', '_panels'); }

// function to read the points amounts from cookies and update the html in the header
function refreshpoints() {
	if ($('totalpoints') != null)
		$('totalpoints').innerHTML = addCommas(Cookie.get("PointsBalance"));
	if ($('onholdpoints') != null)
		$('onholdpoints').innerHTML = addCommas(Cookie.get("PointsOnHold"));
	if ($('availablepoints') != null)
		$('availablepoints').innerHTML = addCommas(Cookie.get("PointsAvailable"));
}

// read the member name (profile info) from cookies and update the header
function refreshmembername() {
	if ($('headerMemberWelcome') != null) {
		var mname =  Cookie.get("UserDisplayName");
		if (mname != null) {
			if (mname.length > 15)
				mname = mname.substring(0,15);
			$('headerMemberWelcome').innerHTML = "Welcome, " + mname;
		}
	}
}

// flash calls update cookie to refresh points
function updatecookies() {
	refreshpoints();
}

// functions for redeem and category pages
function doredirect(tiers){
	var url = location.href.replace(/\.ssx/, '');
	var firsturl = String(url).replace(/^(.*\/)([^?]*)(\?.*)?$/, '$1');
	var querystring = String(url).replace(/^.*(\?.*)?$/, '$3');
	if(url.match(/index$/))
		location.href=(firsturl + "/" + tiers + querystring);
	else
		location.href=(firsturl + "/index/" + tiers + querystring);
}

function getredirect(origurl, tiers){
	var split = getsplit(origurl);
	var tierstring = "/";
	for(var i=0; i<tiers.length; i++){
		if(String(tiers[i]) != ""){
			tierstring += String(tiers[i]);
			tierstring += "/";
		}
	}
	var returnurl;
	if(String(split[0]).match("index\/?$"))
		returnurl =   split[0] + "/" +  tierstring + "/" + split[2];
	else
		returnurl =   split[0] + "/index/" +  tierstring + "/" + split[2];

	returnurl = returnurl.replace(/([^:])\/+/g, '$1/');
	return returnurl;
}

function getsplit(url){
	var datasplit = String(url).replace(/(^.*(redeem|\/subcategory|\/category|\/product|index)\/?)([^\?]*)?(\?.*)?$/, '$1|$3|$4');
	return datasplit.split('|');
}

function getHomepageAffinity() {
	var h = Cookie.get("HomepageAffinity");
	var affinityArray = new Array("base", "wof", "spt", "sonycard", "bluray", "patsplace", "playstation", "jeopardy");
	if (h && h != "" && affinityArray.indexOf(h) >= 0) {
		return h;
	}
	return "";
}

function getAffinities(){
	var tiers = Cookie.get("AffinityTiers");
	var	tierarray = [];
	if(tiers != null && tiers != ''){
		tierarray = tiers.split(',');
		return tierarray.join('/');
	}else{
		return '4';
	}
}

function getAffinityArray(){
	var affinity = Cookie.get("Affinities");
	if(affinity == null || affinity == ''){
		affinity = '181';
	}
	return affinity.split(',');
}

function isAffinity(affinityName) {
	var affinity = getAffinityArray();
	var idToLookFor = "";
	if (affinityName == "wof") {
		idToLookFor = "180";
	} else if (affinityName == "spt") {
		idToLookFor = "183";
	} else if (affinityName == "bluray") {
		idToLookFor = "184";
	} else if (affinityName == "card" || affinityName == "sonycard") {
		idToLookFor = "182";
	} else if (affinityName == "base") {
		idToLookFor = "181";
	} else if (affinityName == "patsplace") {
		idToLookFor = "185";
	} else if (affinityName == "playstation") {
		idToLookFor = "186";
	} else if (affinityName == "jeopardy") {
		idToLookFor = "187";
	}
	return affinity.indexOf(idToLookFor) > -1;
}

function checkaffinities(){
	var tiers = Cookie.get("AffinityTiers");
	var	tierarray = [];
	if(tiers != null)
		tierarray = tiers.split(',');

	$A(tierarray).collect(function(a){
		a = Number(a);
	});
	tierarray.sort();

	var url = location.href.replace(/\.ssx/, '');
	var urlarray = getsplit(url);
	var rawdataarray = String(urlarray[1]).split('/');
	var dataarray = [];
	$A(rawdataarray).each(function(a){
		if(a != '')
			dataarray.push(Number(a));
	});
	dataarray.sort();
	if(dataarray.length == tierarray.length){
		$A(dataarray).each(function(num, index){
				if(String(num) != String(tierarray[index])){
					location.href = getredirect(url, tierarray);
				}
			});
	}else{
		location.href = getredirect(url, tierarray);
	}
}

function createReverseAuctionBid(url) {
	if (confirm("If you add a Reverse Auction item to your cart:\n" +
		"a) Your Shopping Cart will be cleared\n" +
		"b) You will be suspended from participating in this Reverse Auction for an hour if you do not complete the check out process\n" +
		"c) You have 15 minutes to complete the check out process")) {
		window.location = url;
	}
}

function addDealToCashCart(url)
{
	if (confirm("Your shopping cart will be cleared"))
		window.location = url;
}

function addItemToCashCart(url, activityid)
{
	if (activityid == "deal")
		addDealToCashCart(url);
	else
		createReverseAuctionBid(url);
}
		
function tracklink(el) {
	if (el) {
		var linkid = el.getAttribute("sslinkid");
		if (linkid) {
			var linkname = el.getAttribute("sslinkname");
			var linkcategory = el.getAttribute("sslinkcategory");
			var linktext = el.getAttribute("sslinktext");		
			var arr = [];
			arr.push(linkid);
			arr.push(linkname ? escape(linkname) : '');
			arr.push(linkcategory ? escape(linkcategory) : '');
			arr.push(linktext ? escape(linktext) : '');
			arr.push(document.title ? escape(document.title) : '');
			arr.push(escape(location.href));
			Cookie.set("TrackLink", arr.join('|'), null, "/");
		}
	}
}

function linkclick(desturl, linkname, linkcat, linktext) {
	var arr = [];
	arr.push('');
	arr.push(linkname ? escape(linkname) : '');
	arr.push(linkcat ? escape(linkcat) : '');
	arr.push(linktext ? escape(linktext) : '');
	arr.push(document.title ? escape(document.title) : '');
	arr.push(escape(location.href));
	Cookie.set("TrackLink", arr.join('|'), null, "/");
	if (desturl.indexOf("~") == 0) desturl = desturl.substring(1);
	if (desturl.indexOf("/") == 0) 
		window.location = siteroot + desturl.substring(1);
	else if (desturl.indexOf("http://") != 0 && desturl.indexOf("https://") != 0)
		window.location = siteroot + desturl;
	else
		window.location = siteroot + "elements/click/redirect?url=" + escape(desturl);
}

////////////////////////////////////////////////////////////////////////////////////
// CLIENT-SIDE SORTING

var lvIsSorting = false;
var lvClass1 = "odd"; // the first row (non-header) classname
var lvClass2 = "even"; // the second row (non-header) classname
var lvClassForward = "sortasc";
var lvClassReverse = "sortdesc";
var isMozilla = !(document.all);

function lvSortColumn(td, header)
{
	lvIsSorting = true;
	//td.style.cursor='wait';
	var table = lvGetParent(td, "TABLE");
	// gets the classes to keep the alternating colours
	if (table.rows.length >= 2) lvClass1 = table.rows[1].className;
	if (table.rows.length >= 3) lvClass2 = table.rows[2].className;
	var lvIndex = lvGetTDIndex(td);
	lvSortColumn_(table.id, lvIndex);
	if (header != null) {
		var headercells = header.getElementsByTagName("TH");
		for(var i=0; i < headercells.length; i++) {
			Element.removeClassName(headercells[i], lvClassForward);
			Element.removeClassName(headercells[i], lvClassReverse);
		}
		Element.addClassName(headercells[lvIndex], lvReverseSort[table.id] ? lvClassReverse : lvClassForward);
	}
}

function lvRowBackground(tableID)
{
	// restores the alternating background classes
	var lv = document.getElementById(tableID);
	var b = false;
	for (var i = 1; i < lv.rows.length; i++)
	{
	lv.rows[i].className = (b) ? lvClass2 : lvClass1;
		b = !b;
	}
}

function lvSortColumn_(tableID, tdIndex)
{
	var lv = document.getElementById(tableID);
	var rowCount = lv.rows.length;
	if (rowCount < 2) //don't sort if 1 data row or less
	{
		lv.rows[0].cells[tdIndex].style.cursor = 'pointer';
		return;
	}

	colCount = lv.rows[0].cells.length;

	var lvRows = new Array();
	for (var i = 1; i < rowCount; i++)
		lvRows[i - 1] = lv.rows[i];

	//globals
	lvCurListView = tableID;
	if (typeof lvCurSortCol == "undefined") lvCurSortCol = new Array();
	if (typeof lvReverseSort == "undefined") lvReverseSort = new Array();

	if (tdIndex != lvCurSortCol[tableID]) lvReverseSort[tableID] = false;
	else lvReverseSort[tableID] = !lvReverseSort[tableID];
	lvSortCol = tdIndex; //global

	lvRows.sort(lvSort);
	lvCurSortCol[tableID] = tdIndex;

	for (var i = 1; i < rowCount; i++)
		lv.tBodies[0].appendChild(lvRows[i - 1]);

	lvDisplayArrow(tableID, tdIndex);
	lv.rows[0].cells[tdIndex].style.cursor = 'pointer';
	lvRowBackground(tableID)
	lvIsSorting = false;
}

function lvDisplayArrow(tableID, tdIndex)
{
	var arrows = document.getElementById(tableID).getElementsByTagName("SPAN");
	var td;
	for (var i = 0,l=arrows.length; i < l; i++)
	{
		if (arrows[i].name == 'sortArrow')
		{
			td = lvGetParent(arrows[i], "TD");
			// look for a TH if no TD present
			if (!td || td.id == '')
				td = lvGetParent(arrows[i], "TH");

			if (lvGetTDIndex(td) == tdIndex)
				arrows[i].innerHTML = (lvReverseSort[tableID]) ? "&#9660;" : "&#9650;";
			else
				arrows[i].innerHTML = '';
		}
	}
}

function lvSort(s1, s2)
{
	var tdIndex = lvSortCol;
	var x = lvSetDataType(isMozilla ? s1.cells[tdIndex].textContent : s1.cells[tdIndex].innerText);
	var y = lvSetDataType(isMozilla ? s2.cells[tdIndex].textContent : s2.cells[tdIndex].innerText);
	if (typeof x != typeof y)
	{
		x = String(x);
		y = String(y);
	}
	if (!lvReverseSort[lvCurListView]) return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	else return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function lvSetDataType(val)
{
	// this function figures out the data type and returns the value in alpha/numeric sortable format
	// sorting when in the sort function
	var dt = new Date(val);
	if (!isNaN(dt))
	{
		// value is a date
		var dateString = String(dt.getFullYear())
			+ String(dt.getMonth() + 100).substr(1)
			+ String(dt.getDate() + 100).substr(1)
			+ String(dt.getHours() + 100).substr(1)
			+ String(dt.getMinutes() + 100).substr(1)
			+ String(dt.getSeconds() + 100).substr(1);
		return dateString;
	}
	else
	{
		if (isNaN(val.replace(/[\$\,\%]/g, "")))
			return val.toUpperCase(); // the value is a string
		else
			return Number(val.replace(/[\$\,\%]/g, "")); // value is number or currency
			return Number(val.replace(/[\$\,\%]/g, "")); // value is number or currency
	}
}

function lvGetParent(el, tagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == tagName.toLowerCase())
		return el;
	else
		return lvGetParent(el.parentNode, tagName);
}

function lvGetTDIndex(td)
{
	var tr = lvGetParent(td, "TR");
	if (tr == null) return null;
	for (var i = 0,l=tr.cells.length; i < l; i++)
		if (tr.cells[i] == td) return i;
	return null;
}

function lvSetReverseSort(td, isReverse)
{
	if (typeof lvCurSortCol == "undefined") lvCurSortCol = new Array();
	if (typeof lvReverseSort == "undefined") lvReverseSort = new Array();
	var table = lvGetParent(td, "TABLE");
	lvCurSortCol[table.id] = lvGetTDIndex(td);
	lvReverseSort[table.id] = !isReverse;
}

////////////////////////////////////////
// END CLIENT-SIDE SORTING
///////////////////////////////////////

var startedobservingtoplogin = false;
function beginTopLogin(completeloginurl) {
	if (!startedobservingtoplogin) {
		Event.observe("LoginActor", "load", function () {
			new Ajax.Updater("TopLoginResult", completeloginurl, { method: 'GET', evalScripts: true} );
		});
	}
	startedobservingtoplogin = true;
	return true;
}
function showTopLoginError(err, display_in_div) {
	if ($(display_in_div) != null && $(display_in_div + 'Message') != null) {
		$(display_in_div + 'Message').innerHTML = err;
		Element.show($(display_in_div));
	}
}

var redirectCookie = Cookie.get('user-suspended');
if (redirectCookie && redirectCookie.length > 0 && window.location.href.indexOf('en/register/underage') == -1) window.location=siteroot+'en/register/underage';

/* AjaxPageRequests Object */

/**
 *  Ajax Multiple Page Requests in one call
 */
var AjaxPageRequests = {
	pagelist: [],
	oncompletelist: []
}
AjaxPageRequests.Add = function(id, url, oncomplete) {
	var x = new Object();
	x.ID = id;
	x.URL = url;
	if (oncomplete == null)
		oncomplete = "AjaxPageRequests.Updater";
	this.oncompletelist[id] = oncomplete;
	this.pagelist.push(x);
}
AjaxPageRequests.Updater = function(id, content) {
	if ($(id))
		$(id).innerHTML = content;
}

AjaxPageRequests.Execute = function(method) {
	var requestObj = {"pages":AjaxPageRequests.pagelist};
	var requeststr = $H(requestObj).toJSON();
	var oncompletelistarg = this.oncompletelist;
	this.pagelist = [];
	this.oncompletelist = [];
	new Ajax.Request('/elements/widgets/Ajaxpagerequests/index', { method:(method=="POST"?method:"GET"), parameters: { content: requeststr, r: (new Date()).getTime() }, onComplete: function(o) { AjaxPageRequests._processExecute(o, oncompletelistarg); } });
}

_processAjaxRequest = function(o) {
	if(o.responseText !== undefined) {
		var data = o.responseText;

		var result = {};
		result = eval("(" + data + ")");
		return result;
	}
	return null;
}

_processAjaxRequestData = function(o) {
	return (o!=""?eval("veryhiddenvariable = " + o):null);
}

AjaxPageRequests._processExecute = function(o, oncompletelist)
{
	var result = _processAjaxRequest(o);
	var pages = result.pages;
	for(var i = 0; i < pages.length; i++) {
		var currpage = pages[i];
		try {
			if (typeof (oncompletelist[currpage.ID]) == "string" && oncompletelist[currpage.ID] != "")
			{
				var func = eval(oncompletelist[currpage.ID]);
				if (typeof(func)==="function") {
					func(currpage.ID, currpage.output);
				} else {
					printfire("MISSING for:" + currpage.ID + " executing:" + oncompletelist[currpage.ID]);
				}
			}
		} catch(e) {
			printfire("ERROR for:" + currpage.ID + " executing:" + oncompletelist[currpage.ID] + " message:" + e.message);
		}
	}
	forceRedraw();
}

var forceRedraw = function(){
	/*@cc_on 
	window.setTimeout(function(){				   
		if ($('dashboardcontentloggedout')) {
		$('dashboardcontentloggedout').style.visibility = "hidden";
		$('dashboardcontentloggedout').style.visibility = "visible";
		}
	}, 100);
	@*/		
}

//fixing IE6 draw bug - the following line forcefully redraws an element that IE simply refuses to draw otherwise
//@cc_on new function() {var hack = setInterval(function() {if ($("infographics_link")) $("infographics_link").style.border="0"},100); setTimeout(function() {clearInterval(hack)}, 10000)}()

var CurrentMoreImage = 0;
var openProductModule = function(url)
{
	CurrentMoreImage = 0;
	showAjaxedModalDialog('productModule', url, 560);
}

//hack: FF3 refreshes the flash activity the first time appendChild gets called on a page. Since this doesn't happen after the first call, we're calling it early before the user gets the chance to change the state of the flash activity
Event.observe(window, "load", function() {
	var productModule = $("productModule");
	if (productModule) document.body.appendChild(productModule);
})

function ShowMoreImages() {
	if ($$("#productModule .moreImages").length) {
		$$(".modalbody > .moreImages").each(function(e) {Element.remove(e.parentNode);});
		renderedDialogs["MoreImagesDiv"] = undefined;
	}
	showModalDialog("MoreImagesDiv", 200, 200);
}
function MoveToImage(ImageNumber) {
	var MoreImageCount = $F('MoreImageCount');

	if (ImageNumber == "Previous" && CurrentMoreImage > 0) ShowMoreImage(CurrentMoreImage-1);
	else if (ImageNumber == "Next" && CurrentMoreImage < (MoreImageCount-1)) ShowMoreImage(CurrentMoreImage+1);
	else if (String(ImageNumber).match(/^\d+$/g)) ShowMoreImage(ImageNumber);
	
	if (CurrentMoreImage == 0) $("PreviousButton").style.display = "none";
	if (CurrentMoreImage > 0) $("PreviousButton").style.display = "";
	if (CurrentMoreImage < MoreImageCount-1) $("NextButton").style.display = "";
	if (CurrentMoreImage == MoreImageCount-1) $("NextButton").style.display = "none";
}

function ShowMoreImage(ImageNumber) {
	if ($("thumb_" + CurrentMoreImage))
	  $("thumb_" + CurrentMoreImage).style.border = "1px solid black";
	$("full_" + CurrentMoreImage).style.display = "none";
	CurrentMoreImage = ImageNumber;
	if ($("thumb_" + CurrentMoreImage))
    $("thumb_" + CurrentMoreImage).style.border = "1px solid red";
	$("full_" + CurrentMoreImage).style.display = "";
}
