var isPopup = false;
var aInitFunctions = new Array();
var ie6 = false;
var cookiesDomain;
var currentLocation = null;
var proxyID = "swfProxy";
var mycokeSection = '';
var mycokeOrigin = '';
var interstitialTimer = 3000;
var openPopup;
var sExpressInstall = "/swf/common/expressInstall.swf";

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 getParamNamesFromUrl(str)
{
	var paramsAlpha = str.substr(str.indexOf("?")+1).split('&');
	var params = new Array();
	var newQuery = "";	
	
	for(i=0; i < paramsAlpha.length; i++)
	{
		tempParam = paramsAlpha[i].split('=');
		params.push(tempParam[0]);
	}
	return params;
}
function getParamsFromUrl(str)
{
	var paramsAlpha = str.substr(str.indexOf("?")+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;
}
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 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("locate");
		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(str)
{
	eraseCookie("mycokeOrigin");
	if(str == null) 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()
{
	var url = homeBase;
	if(getCurrentLocation() != null)
		url = Url.decode(getCurrentLocation());

	url = useOrigin(url);
	return url;
}
function getHomeBase(ss)
{
	if(ss == null) ss = "";
	if(ss != "") ss += "/";
//	return homeBase+ss;
	return useOrigin(homeBase+ss);
}

/**
*
*  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+"="+escape(value)+expires+domain+"; path=/";
}

function readCookie(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 null;
}
/*
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 unescape(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;
	var auxA = aInitFunctions.splice(0,aInitFunctions.length);
	aInitFunction = new Array();
	for(i = 0; i < auxA.length; i++)
	{
		auxA[i]();
	}*/
}


/** 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)
{
	var loc = window.location.href+"";
	
	var parentLoc = getParentLocation();
	if((loc.indexOf("https:") == 0 && parentLoc.indexOf("https:") == 0) || (loc.indexOf("http:") == 0 && parentLoc.indexOf("http:") == 0))
	{
		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()
{
}
function doAutoUpdateSize()
{
	//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);
	doAutoUpdateSize();
	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+"')");
	return false;
}
function timerCloseFunction(timer, fnc)
{
	setTimeout(function() { fnc(); 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("#"));

	eraseCookie("mycokeRefer");
	createCookie("mycokeRefer",window.location.href,1);

	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 printObj(obj)
{
	if(obj == null) obj = window;
	obj.focus();
	obj.print();
}
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)
	{
		$(".login #email").val(user);
		$(".login #remember").attr("checked",true);
	}
}

function selectRadio(id) {
	var obj = document.getElementById(id);
	obj.checked = "true";
}
function setHiddenField(id,value)
{
	$("#"+id).each(function() { $(this).val(value) });
}

/** GENERIC MESSAGE DECK **/
var oMsgDeck = new Object();
oMsgDeck['default'] = 'Thanks for your interest in My Coke!';
oMsgDeck['myacc_success'] = 'Your account has been updated';
oMsgDeck['contact_success'] = 'Thanks for contacting <span class="high">My Coke!</span><br />We will get back to you soon.';
var oMsgWin = new Object();
oMsgWin['myacc_success'] = homeBase;
oMsgWin['contact_success'] = homeBase;

function getMsg(key)
{
	return (oMsgDeck[key] != null)?oMsgDeck[key]:oMsgDeck['default'];
}
function _getGenericLocation(key)
{
	return (oMsgWin[key] != null)?oMsgWin[key]:getParentLocation();
}
function getGenericLocation()
{
	return _getGenericLocation(getFromParam('key'))
}
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()
{
	
}

function rememberUser()
{
	var bChecked = $(".login #remember").attr("checked");
	eraseCookie("rememberUser");
	if(bChecked)
	{
		createCookie("rememberUser",$(".login #email").val(),365);
	}
}
function initFocus(ndx)
{
	if(ndx == null) ndx = 0;
	self.focus();
	document.forms[ndx].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?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 setMenuById(obj, section)
{
	if(obj != null && obj.id == section)
	{
		obj.className = "selected";
		obj.onclick=returnFalse;
		obj.href = "";
	}
}
function updateMenu(section)
{
	$('#header_menu a').each(function() { setMenuById(this, section); });
	$('#footer_menu a').each(function() { setMenuById(this, section); });
}
function setMenuByUrl(obj, url)
{
	if(obj != null)
	{
		var shref;
		for(var i = 0; i < obj.length; i++)
		{
			shref = obj[i].href;
			if(shref.indexOf(url) >= 0)
			{
				obj[i].className = "selected";
				/*obj.onclick=returnFalse;
				obj.href = "";*/
				return true;
			}
		}
	}
	return false;
}
function updateMenuByUrl(s,field)
{
	onMyCokeMenu(s);
	if(field == null) field = "menu_section";
	var sUrl = getHiddenShareField($("#"+field));
	if(sUrl == null)
	{
		sUrl = window.location.pathname;
		sUrl = sUrl.substring(sUrl.lastIndexOf("/")+1);
	}
	setMenuByUrl($(s), sUrl);
}
function getSenderUrl() {
	var parentLoc = getParentLocation();
	var sUrl = (parentLoc.indexOf("https:") == 0)?homeSSL:homeBase;
	sUrl += "jsp/common/proxyTunnel.jsp";
	return sUrl;
}
function updateLinksSubsection(obj)
{
	var aClasses = new Array("logout");
	var bUpdate = false;
	for(var i = 0; !bUpdate && i < aClasses.length; i++)
		bUpdate = $(obj).attr("class") == aClasses[i];
/*	if(!bUpdate) bUpdate = !($(obj).parents("#mycoke_header")[0] != null); //NO HEADER
	if(!bUpdate) bUpdate = ($(obj).parents("#mycoke_user")[0] != null);	//NO MYCOKE USER
	if(bUpdate) bUpdate = !($(obj).parents("#mycoke_footer")[0] != null);
	var sClick = obj.onclick;
	bUpdate = (bUpdate && sClick != null)*/
	return bUpdate;
}
function updateLinks()
{
	if(!updateLinksSubsection(this)) return;
	var sSS = '';
	var params = null;
	var sHref = $(this).attr('href');
	if(sHref != null && sHref != "")
	{
		if(sHref.indexOf("#") != 0 && sHref.indexOf("javascript") < 0)
		{
			params = getParamsFromUrl(sHref);
			if(params['ss'] != null)
			{
				sSS = "ss="+params['ss'];
				params = sHref.split(sSS);
				sHref = params.join("ss="+mycokeSection);
			}
			else
			{
				sHref += (sHref.indexOf("?") >= 0)?"&":"?";
				sHref += "ss="+mycokeSection;
			}
			$(this).attr('href', sHref);
		}
	}
}
function setSubsection(ss) {
	mycokeSection = "utc";
	if(ss == null || ss == "" || ss == "null") return;
	mycokeSection = ss;
	$('a.logout').each(updateLinks);
}

function getOrigin(origin)
{
	if(origin == "" || origin == "null")
	{
		//eraseCookie("mycokeOrigin");
		origin = null;
	}
	if(origin != null)
	{
		createCookie("mycokeOrigin",origin,1);
	}
	else
	{
		mycokeOrigin = getFromParam("mycokeOrigin");
		if(mycokeOrigin != null)
		{
			eraseCookie("mycokeOrigin");
			createCookie("mycokeOrigin",mycokeOrigin,1);
		}
		else
		{
			mycokeOrigin = readCookie("mycokeOrigin");
		}
	}

	return mycokeOrigin;
}
function useOrigin(url)
{
	if(url != null)
	{
		var origin = getOrigin();
		if(origin != null)
		{
			if(url.indexOf("?") > 0)
				url = url.substring(0,url.indexOf("?"));
			url += "?deeplink="+origin;
		}
	}
	return url;
}
function reloadCaptcha(id)
{
	if(id == null) id = "captcha_img";
	var src = homeBase+"jsp/utility/kocaptcha.jsp";
	//if(obj.src.indexOf("?") < 0) src += "?";
	src += "?"+Math.random();
	$("#"+id).attr("src",src);
	return false;
}

//Popup

var wMin = 956;
function popupFile(fileName, w, h)
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,resizable=0,menubar=0,toolbar=0,location=0';
	var title = 'MyCoke' + Math.floor(Math.random()*1000000+1);
	var win = window.open(fileName, title, winprops);
	if(win) {
		win.focus();
		if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	}
	return false;
}

function lockAfterClick()
{
	// Find ALL <form> tags on your page
	$('form').submit(function(){
		// On submit disable its submit button
		$('input[type=submit]', this).attr('disabled', 'disabled');
		$('input[type=button]', this).attr('disabled', 'disabled');
	});
	preventInject();
}
function preventInject()
{
	$('input[type=text],textarea').keyup(function () {
        // this.value = this.value.replace(/[^0-9\.]/g,'');  //Numbers Only
		if(this.value.match(/[<>"]/g) != null)
         this.value = this.value.replace(/[<>"]/g,'');  // replacing commas
    });
	$('input[type=text],textarea').change(function () {
        // this.value = this.value.replace(/[^0-9\.]/g,'');  //Numbers Only
		if(this.value.match(/[<>"]/g) != null)
         this.value = this.value.replace(/[<>"]/g,'');  // replacing commas
    });
}

function getHiddenShareField($objShare)
{
	var value = $objShare.attr("title");
	if(value == null || value == "") value = $objShare.val();
	if(value == "") value = null;
	return value;
}

//SWF CALLBACK 
function swfCallback(e)
{
	var playerVersion = swfobject.getFlashPlayerVersion(); // returns a JavaScript object
	var majorVersion = playerVersion.major;
	if(e.success != true || parseInt(majorVersion) < 9)
	{
		$("#"+e.id+" .hidden").each(function(){
			$(this).removeClass("hidden").addClass("visible");
		});
	}
}