var isPopup = false;
var aInitFunctions = new Array();
var ie6 = false;
var cookiesDomain;
var currentLocation = null;
var tunnelID = null;
var proxyID = "swfProxy";
var flashvars = {
	tunnelID: tunnelID
};
var openPopup;

function _getParams(str)
{
	if(str == null) return null;
	var paramsAlpha = str.split(',');
	var params = new Object();
	var i = 0;
	
	for(i=0; i < paramsAlpha.length; i++)
	{
		var tempParam = paramsAlpha[i].split('=');
		params[tempParam[0]] = tempParam[1];
	}
	params['length'] = i;
	return params;
}
function getTunnelIDParam()
{
	return "tunnelID="+getTunnelID();
}
function createTunnelID()
{
	eraseCookie("tunnelID");
	var rand = Math.random()*50000;
	tunnelID = "nos_tunnel_"+Math.floor(rand);
	rand = Math.random()*10000;
	tunnelID += "_"+Math.floor(rand);
	createCookie("tunnelID",tunnelID,1);
}
function getFromParam(param)
{
	var str = window.location.search;
	var paramsAlpha = str.substr(1).split('&');
	var params = new Array();
	var newQuery = "";	
	
	for(i=0; i < paramsAlpha.length; i++)
	{
		tempParam = paramsAlpha[i].split('=');
		params[tempParam[0]] = tempParam[1];
	}
	return params[param];
}
function getTunnelIDFromParam()
{
	return getFromParam("tunnelID");
}

function getTunnelID()
{
	if(tunnelID != null)
	{
		createCookie("tunnelID",tunnelID,1);
	}
	else
	{
		tunnelID = getTunnelIDFromParam();
		if(tunnelID != null)
		{
			eraseCookie("tunnelID");
			createCookie("tunnelID",tunnelID,1);
		}
		else
		{
			tunnelID = readCookie("tunnelID");
		}
	}

	return tunnelID;
}

function startProxyDiv()
{
	var obj = document.getElementById(proxyID);
	if(obj)
	{
		obj.parentNode.removeChild(obj);
	}
	obj = document.body.appendChild(document.createElement("div"));
	obj.setAttribute("id",proxyID);
}

function startReceiver()
{
	if(ie6)
	{
		startProxyDiv();
	}
	swfobject.embedSWF(homeBase+"swf/swfTunnel_receiver.swf", proxyID, "1", "1", "9.0.0", homeBase+"swf/expressinstall.swf",{},{bgcolor: '#000000', menu: 'false', wmode: 'opaque', allowScriptAccess:"always"},{id:proxyID,name:proxyID});
}

function startSender(isRoot)
{
	if(ie6)
	{
		startProxyDiv();
	}
	var path = (isRoot == true)?"":"../../";
	swfobject.embedSWF(homeBase+"swf/swfTunnel_sender.swf", proxyID, "1", "1", "9.0.0", homeBase+"swf/expressinstall.swf",{},{bgcolor: '#000000', menu: 'false', wmode: 'opaque', allowScriptAccess:"always"},{id:proxyID,name:proxyID});
}

function getCurrentLocationParam()
{
	if(currentLocation == null) getCurrentLocation();
	return "locate="+currentLocation;
}
function getCurrentLocation()
{
	if(currentLocation != null)
	{
		createCookie("currentLocation",currentLocation,1);
	}
	else
	{
		currentLocation = getFromParam("currentLocation");
		if(currentLocation != null)
		{
			eraseCookie("currentLocation");
			createCookie("currentLocation",currentLocation,1);
		}
		else
		{
			currentLocation = readCookie("currentLocation");
		}
	}

	return currentLocation;
}
function saveCurrentLocation(url)
{
	eraseCookie("currentLocation");
	currentLocation = Url.encode(url);
	createCookie("currentLocation",currentLocation,1);
}
function initCurrentLocation()
{
	var str = window.location.href+"";
	saveCurrentLocation(str);
}
function changeCurrentLocationTo(from,to)
{
	var str = window.location.href+"";
	str = str.replace(from,to);
	saveCurrentLocation(str);
}
function changeToSecureLocation()
{
	changeCurrentLocationTo(homeBase,homeSSL);
}
function getParentLocation()
{
	if(getCurrentLocation() != null)
		return Url.decode(getCurrentLocation());
	else
		return homeBase;
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Url = {
 
	encode : function (str) {
		return escape(this._utf8_encode(str));
	},
 
	decode : function (str) {
		return this._utf8_decode(unescape(str));
	},
 
	_utf8_encode : function (str) {
		str = str.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < str.length; n++) {
 
			var c = str.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	_utf8_decode : function (utftext) {
		var str = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				str += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return str;
	}
 
}


/* COOKIES */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";


	var domain = (cookiesDomain && cookiesDomain != '') ? "; domain=" + cookiesDomain : "";
	document.cookie = name+"="+value+expires+domain+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function addBoot(fnc)
{
	if(fnc)
	{
		aInitFunctions.push(fnc);
	}
}
function execBoot()
{
	var i = 0;
	for(i = 0; i < aInitFunctions.length; i++)
	{
		aInitFunctions[i]();
	}
	aInitFunction = new Array();
}

/** JAVA FIELDS - SDK **/
function setCheckBoxAnswer(questionId,answerId,value) {
  if (document.getElementById(questionId+'_'+answerId).checked) {
      document.getElementById(questionId).value = value;  }
  else {    document.getElementById(questionId).value='';
  }
}

function processRadioButtonInfo(questionId,answerId,answerText) {
  document.getElementById(questionId).value= answerText;
  document.getElementById(questionId+'_answer').value= answerId;
}
function setInitialSelectBoxIndex(selectBox,value) {
	var options = selectBox.options;
	for (var i = 0; i < options.length; i++) {
	 if (options[i].value == value) {
	 selectBox.selectedIndex = i;
	  break;
	 }
	}
}

function updateMainPhoneField(name){
	
	  var phone1 = 	completeStringLength(document.getElementById("phone1").value, 3, " ");
	  var phone2 = 	completeStringLength(document.getElementById("phone2").value, 3, " ");
	  var phone3 = 	completeStringLength(document.getElementById("phone3").value, 4, " ");
	  
	  document.getElementById(name).value =  phone1 + phone2 + phone3 ;
	  
	}

	
function completeStringLength(str,size,fill){

	if(str.length < size){
		str = completeStringLength(str+fill,size,fill);
	}
	return str;
}

/** TUNNEL FUNCTIONALITY **/
var tryCallParentFunction = 500;
function getIdFromFrame(obj)
{
	return obj.substring(0, obj.length-6);
}
function proxy_receiver(call)
{
	eval(call);
}
function proxy_error_receiver(call)
{
	setTimeout(function() { callParentFunction(call); }, tryCallParentFunction);
}
function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}
function parentEnabled()
{
	return true;
}
function callParentFunction(call)
{
	callParentFunction_tunnel(call);
}
function callParentFunction_tunnel(call)
{
	try
	{
		if(window.parent != null && window.parent.proxy_receiver != null)
		{
			window.parent.proxy_receiver(call);
			return;
		}
	}
	catch(ev)
	{
	}
	try
	{
/*		var objMovie = thisMovie("swfProxy");
		if(objMovie != null)
		{
			if(objMovie.send != null && objMovie.send(call) == "success") return;
		}*/
		var sUrl = getSenderUrl();
//		sUrl += "?rnd="+Math.floor(Math.random()*999999);
		sUrl += "?task="+encodeURIComponent(call);
		var sFrameID = "tunnel_frame_"+Math.floor(Math.random()*999999);
		$('#tunnel_frame').append('<iframe id="'+sFrameID+'" width="0" height="0" src="'+sUrl+'" style="visibility:hidden;display:none;" ></iframe>'); 
//		jQuery('#tunnel_frame').attr('src',sUrl);
		return;
	}
	catch(ev)
	{
	}
	
	setTimeout(function() { callParentFunction(call); }, tryCallParentFunction);
}

/** SIZE UPDATE **/
function autoUpdateSize()
{
	//document.stopObserving("dom:loaded", autoUpdateSize);
	var obj = document.body;
	var align = (obj.style.backgroundPosition != null && obj.style.backgroundPosition != "")?(",'"+obj.style.backgroundPosition+"'"):"";
	callParentFunction("resizePopup('"+self.name+"',"+obj.offsetWidth+","+obj.offsetHeight+align+")");
}
function callClosePopup()
{
	autoClosePopup(self.name);
	return false;
}


function updatePopup(style,position,autoreload,url,tooltip)
{
	isPopup = true;
	var call = "changePopup_style('"+self.name+"'";
	call += (style != null)?(",'"+style+"'"):",null";
	call += (position != null)?(",'"+position+"'"):",null";
	call += (autoreload != null)?(",'"+autoreload+"'"):",null";
	call += (url != null)?(",'"+url+"'"):",null";
	call += (tooltip != null)?(",'"+tooltip+"'"):",null";
	call += ")";
	callParentFunction(call);
	setForm();
}

function onResizeIframe(size){
	var call = "onResizeParentIframe("+size+"";
	call += ")";
	callParentFunction(call);
}

function autoClosePopup(obj)
{
	var id = getIdFromFrame(obj);
	
	callParentFunction("doClosePopup('"+id+"')");
	return false;
}
function autoRedirect(url)
{
	callParentFunction("changeLocation('"+url+"')");
}
function timerCloseFunction(timer)
{
	setTimeout(function() { autoClosePopup(self.name); }, timer);
}
function timerRedirectFunction(timer,url)
{
	setTimeout(function() { autoRedirect(url); }, timer);
}


function detectBrowser(type)
{
	var user = navigator.userAgent+"";
	return (user.toLowerCase().indexOf(type) >= 0);
}
function changeLocation(url)
{
	if(url.indexOf("#") > 0) url = url.substring(0,url.indexOf("#"));
	var ref = window.location.href+"";
	if(ref.indexOf("#") > 0) ref = ref.substring(0,ref.indexOf("#"));
	if(detectBrowser("safari") && url == ref && window.location.reload != null)
		window.location.reload();
	else if(window.location.assign != null)
		window.location.assign(url);
	else
		window.location.href = url;
}
function printIFrame(name)
{
	window.frames[name].focus();
	window.frames[name].print();
}


function autoOpenPopup(popup,id)
{
	if(id != null && id != 'null' && id != '') doClosePopup(id);
	eval(popup+"()");
}
function onOpenPopup(popup,bClose)
{
	var callFnc = "";
	if(bClose) callFnc = "autoOpenPopup('"+popup+"','"+getIdFromFrame(self.name)+"');";
	else callFnc = popup+"()";
	
	callParentFunction(callFnc);
	return false;
}
function checkRemember()
{
	var user = readCookie("rememberUser");
	if(user != null)
	{
		var obj = document.getElementById("email");
		obj.value = user;
		obj = document.getElementById("remember");
		obj.checked = "checked";
	}
}

function selectRadio(id) {
	var obj = document.getElementById(id);
	obj.checked = true;
}
function initMyFTSetup(id){
	myFTAlign = new Object();
	myFTAlign["motors"] = false;
	myFTAlign["making"] = false;
	myFTAlign["sound"] = false;
	updateMyFTSetup(id);
	if(id != "motors") updateMyFTSetup("motors",false);
	if(id != "making") updateMyFTSetup("making",false);
	if(id != "sound") updateMyFTSetup("sound",false);
	
	selectRadio('default_'+id);
}
function updateMyFTSetup(id,visible) {
	if(visible == null) visible = true;
	var obj;
	var url = "";
	var data = new Object();
	url = homeBase+"viewSwitchContentByCategory.do";
	switch(id)
	{
		case 'motors':
			//url = "viewSwitchContent_1.txt";
			data.categoryId = 1;
			break;
		case 'making':
			//url = "viewSwitchContent_2.txt";
			data.categoryId = 2;
			break;
		case 'sound':
			//url = "viewSwitchContent_3.txt";
			data.categoryId = 3;
			break;
	}
	

	if(data.categoryId != null)
	{
		if(visible)
		{
			document.getElementById("motors_tab").className = "";
			document.getElementById("making_tab").className = "";
			document.getElementById("sound_tab").className = "";
			obj = document.getElementById(id+"_tab");
			obj.className = "selected";
			
			document.getElementById("motors_box").className = "hidden";
			document.getElementById("making_box").className = "hidden";
			document.getElementById("sound_box").className = "hidden";
			obj = document.getElementById(id+"_box");
			obj.className = "visible";
		}
		
		obj = document.getElementById(id+"_content");
		if(obj.innerHTML == "")
		{
			$("#"+id+"_content").load(url, data, function() { if(visible) verticalAlignElements(id) });
			$("#"+id+"_content").click(function(event) {
				var thisID = $(event.target).attr("id");
				var obj = $(event.target);
				while(thisID == "")
				{
					obj = obj.parent();
					thisID = obj.attr("id");
				}
				
				if(thisID != id+"_content")
				{
					var sclass = obj.attr("class");
					if(sclass.indexOf("true") >= 0)
						obj.attr("class","false");
					else
						obj.attr("class","true");
				}
			});
		}
		else verticalAlignElements(id);
	}
}
function verticalAlignElements(id)
{
	if(myFTAlign[id]) return;
	myFTAlign[id] = true;
	var obj = document.getElementById(id+"_content");
	var elements = obj.getElementsByTagName("div");
	for(var i = 0; i < elements.length; i++)
	{
		if(elements[i].className == "item")
		{
			elements[i].style.marginTop = ((parseInt(elements[i].parentNode.offsetHeight)-parseInt(elements[i].offsetHeight))/2)+"px";
		}
	}
	
	if(ie6)
	{
		$("#"+id+"_content a").hover(function(event){
			//OVER
			var aSwitch = $(event.target).find('.item');
			aSwitch.attr("class","item item_over");
		},function(event){
			//OUT
			var aSwitch = $(event.target).find('.item_over');
			aSwitch.attr("class","item");
		});
	}
}
function saveMyFTSetup(btn,logged)
{
	btn.onclick = null;
	var data = new Object();
	var sCat = "";
	if((sCat = saveCategory("motors")) != "")	data.content1 = sCat;
	if((sCat = saveCategory("making")) != "")	data.content2 = sCat;
	if((sCat = saveCategory("sound")) != "")	data.content3 = sCat;
	
	data.favoriteCategory = $('input[@name="default_radio"]:checked').val(); 
	
	var url = homeBase+"switchContent.do";
	//url = "switchContent.txt";
	if(logged)
		$("#response_div").load(url, data, callClosePopup );
	else
		$("#response_div").load(url, data, showNoSaved );
	return false;
}
function showNoSaved()
{
	//changeLocation("nosaved.html");
	changeLocation(homeBase+"jsp/myft/nosaved.jsp");
}

function saveCategory(id)
{
	$('#'+id+'_content').unbind('click');
	var sSave = "";
	var obj = document.getElementById(id+"_content");
	var elements = obj.getElementsByTagName("a");
	for(var i = 0; i < elements.length; i++)
	{
		if(i > 0) sSave += ";";
		sSave += elements[i].id+":"+((elements[i].className.indexOf("true") >= 0)?1:0);
	}
	return sSave;
}


/** GENERIC MESSAGE DECK **/
var oMsgDeck = new Object();
oMsgDeck['default'] = 'Thanks for your interest in Full Throttle!';
oMsgDeck['myacc_success'] = 'Your account has been updated';
oMsgDeck['contact_success'] = 'Thanks for contacting <span class="high">Full Throttle!</span><br />We will get back to you soon.';
var oMsgWin = new Object();
oMsgWin['myacc_success'] = homeSSL+"viewMyAccount.do";
oMsgWin['contact_success'] = homeSSL+"startFullStory.do";

function getMsg(key)
{
	return (oMsgDeck[key] != null)?oMsgDeck[key]:oMsgDeck['default'];
}
function getGenericLocation()
{
	var key = getFromParam('key');
	return (oMsgWin[key] != null)?oMsgWin[key]:getParentLocation();
}
function showMsgDiv(id)
{
	if(id == null) id = 'msg';
	var obj = document.getElementById(id);
	var key = getFromParam('key');
	if(obj) obj.innerHTML = getMsg(key);
}
function setEventDetail(id,eventId) {
	var url = "detail/"+eventId+".jsp";
	var data = new Object();
	shareUrl = homeBase+"shareEvent.do?event="+eventId;
	shareSection = "Events";
	$("#"+id+"_div").load(url, data, autoUpdateSize);	
}

function showSwf(id,url,params,flashvars,attributes,h,w)
{
	if(w == null) w = "100%";
	if(h == null) h = "100%";
	if(params == null) params = new Object();
	if(flashvars == null) flashvars = new Object();
	if(attributes == null) attributes = new Object();
	
	params.quality = "high";
	params.scale = "noscale";
	params.wmode = "transparent";
	params.allowscriptaccess = "always";
	params.allowFullScreen = "true";
	
	flashvars.baseURL = homeBase;
	flashvars.secureURL = homeSSL;
	if(attributes.id == null) attributes.id = id;
	if(attributes.name == null) attributes.name = id;
	if(attributes.align == null) attributes.align = "t";
	swfobject.embedSWF(url,id,w,h,"9.0.1","expressInstall.swf",flashvars,params,attributes);
}

function onRollOver(obj)
{
	if(obj.className.indexOf("_btn_over") < 0 && obj.className.indexOf("_btn") > 0)
	{
		var classSplit = obj.className.split("_btn");
		obj.className = classSplit.join("_btn_over");
	}
}
function onRollOut(obj)
{
	if(obj.className.indexOf("_btn_over") > 0)
	{
		var classSplit = obj.className.split("_btn_over");
		obj.className = classSplit.join("_btn");
	}
}
function jq_onRollOver()
{
	var sClass = $(this).attr('class');
	if(sClass.indexOf("_btn_over") < 0 && sClass.indexOf("_btn") > 0)
	{
		var classSplit = sClass.split("_btn");
		$(this).attr('class',classSplit.join("_btn_over"));
	}
}
function jq_onRollOut()
{
	var sClass = $(this).attr('class');
	if(sClass.indexOf("_btn_over") > 0)
	{
		var classSplit = sClass.split("_btn_over");
		$(this).attr('class',classSplit.join("_btn"));
	}
}
function setForm()
{
	var objs = $('form input[type=submit]');
	$('form input[type=submit]').each(function(intIndex){
		$( this ).hover(
			jq_onRollOver,
			jq_onRollOut
		);
	});
	$('form input[type=button]').each(function(intIndex){
		$( this ).hover(
			jq_onRollOver,
			jq_onRollOut
		);
	});
}

function rememberUser()
{
	var obj = document.getElementById("remember");
	if(obj.checked == true || obj.checked == "true")
	{
		obj = document.getElementById("email");
		createCookie("rememberUser",obj.value);
	}
	else
	{
		eraseCookie("rememberUser");
	}
}
function initFocus()
{
	self.focus();
	document.forms[0].elements[0].focus();
}
function disableButton(btn)
{
	document.getElementById(btn).disabled='disabled';
}

/* ERRORS */
function genericError(type)
{
	if(type != "session")
	{
		type = "error";
	}
	document.location.href = homeBase+"/home.do?deeplink="+type;
}

function callGenericError(type)
{
	callParentFunction("genericError('"+type+"')");
}
function eventPush(obj, event, handler) {
	if (obj.addEventListener) {
		obj.addEventListener(event, handler, false);
	} else if (obj.attachEvent) {
		obj.attachEvent('on'+event, handler);
	}
}
function goToAnchor(name) {
	if(name == null) name = "";
	var currentHref = window.location.href;
	window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#"+name;
}

/** TEXT AREA COUNTER **/
function textCounter(field, id, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else 
		document.getElementById(id).innerHTML = maxlimit - field.value.length;
}
/* MENU HIGHLIGHT */
function returnTrue() { return true; }
function returnFalse() { return false; }
function updateMenu(section)
{
	var obj = document.getElementById("menu_"+section);
	if(obj)
	{
		obj.className = "selected";
		obj.onclick=returnFalse;
		obj.href = "";
	}
	obj = document.getElementById("footer_"+section);
	if(obj)
	{
		obj.className = "selected";
		obj.onclick=returnFalse;
		obj.href = "";
	}
}
function getSenderUrl() {
	var parentLoc = getParentLocation();
	var sUrl = (parentLoc.indexOf(homeBase) >= 0)?homeBase:homeSSL;
	sUrl += "jsp/common/proxyTunnel.jsp";
	return sUrl;
}