// set jQuery no conflict
var jq = jQuery.noConflict();

// set custom Disney chrome
var chromeColor = "lightgrey";
var chromeWidth = 996;
//var chromeCategory = "Games";
var legalFooterColor = "#A3A3A3";
var legalFooterCat = "Games"; 

var jsReady = false;
var eiData = {};
var regCallback = '';

var basePath = 'http://a.dolimg.com/worldofcars/websitedevelopment';
var imgPath = basePath+'/images';
var gate = false;
var gateMsg = '';
var gateTimer = '';

jq(function(){
	
	jq('.q_list a').click(helpSwitch);
	
	checkGate();
	gateTimer = setInterval(checkGate,30000);
	//showGate('We are excited to report that new game features are being added. Unfortunately, The World of Cars Online will be unavailable from 12:15AM PST until 2AM PST while we update the game. We appreciate your patience!');
});
/*
window.onbeforeunload = function (evt) {
  var message = 'Are you sure you want to leave?';
  if (typeof evt == 'undefined') {
    evt = window.event;
  }
  if (evt) {
    evt.returnValue = message;
  }
  return message;
}
*/

// Test browser for Version IE
function browserVersion() {
	var version = '';
  if (navigator.appVersion.indexOf("MSIE") != -1)
    version = parseFloat(navigator.appVersion.split("MSIE")[1]);
  return version;
}

var popupStatus = 0;
var activeDiv = '';
var opacity = '0.7';
var access = false;

function loadPopup(div){
	if(popupStatus==0){
		jq("#blk_alpha").css({
			"opacity":opacity
		});
		jq("#blk_alpha").fadeIn("fast");
		jq("#"+div).fadeIn("slow");
		popupStatus = 1;

		if( div != 'regDiv' ) {
			jq("#blk_alpha").click(function(){
				jq('#blk_alpha').fadeOut('fast');
				disablePopup(activeDiv);
			});
		}
	}	
}

function disablePopup(div){
	if(popupStatus==1){
		jq("#blk_alpha").fadeOut("fast");
		jq("#"+div).fadeOut("slow");
		popupStatus = 0;
		jq("#blk_alpha").remove();
		jq("#"+div).remove();
	}	
}

function centerPopup(div){
	activeDiv=div;
	var wWidth = document.documentElement.clientWidth;
	var wHeight = document.documentElement.clientHeight;

	var popupHeight = jq("#"+div).height();
		if( popupHeight == 0 )
			popupHeight = wHeight;
	var popupWidth = jq("#"+div).width();
	var xCenter = (wWidth/2)-(popupWidth/2);
	var yCenter = (wHeight/2)-(popupHeight/2);
	var top = yCenter < 0 ? 0 : yCenter;

	jq( window ).scrollTop( 0 );
	jq("#"+div).css({
		"position":"absolute",
		"top": "30px",
//		"top": yCenter+"px",
		"left": xCenter+"px"
	});

	jq("#blk_alpha").css({
		"height":jq( document ).height()+"px",
		"width":wWidth+"px"
	});
	
	jq(window).bind('resize',resizePopup);
	
	loadPopup(div);
}

function resizePopup(){
	if(popupStatus == 1)
		centerPopup(activeDiv)
}

var errorInt = 0;
function checkGate(){
	jq.ajax( {
		'type'		: 'GET',
		'url'		: whoAmI,
		'dataType'	: 'xml',
		'success'	: function( data ) {
			if( typeof data == 'object' || data != false ) {
				processGate( data );
			}
		},
		'error'		: function() {
			if( errorInt > 3 ){
				var defaultMessage = '<gameClosed>The World of Cars Online is currently unavailable. We apologize for the inconvenience and are working quickly to resolve the problem. Please try again soon and thank you for your patience!</gameClosed>';

				if (window.DOMParser){
					var parser = new DOMParser();
					xmlDoc = parser.parseFromString(defaultMessage,"text/xml");
				} else { // Internet Explorer
					xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async="false";
					xmlDoc.loadXML(defaultMessage);
				}
				processGate( xmlDoc );
			} else{
				checkGate();
				errorInt++;
			}
		}
	} );
}

function processGate(xml){
	if(jq('testUser',xml).length > 0){
		showGate(jq('testUser',xml).text());
		gateMsg = jq('testUser',xml).text();
	}
	if(jq('notification',xml).length > 0){
		showGate(jq('notification',xml).text());
		gateMsg = jq('notification',xml).text();
	}
	if(jq('gameClosed',xml).length > 0){
		showGate(jq('gameClosed',xml).text());
		disablePlay();
		gate = true;
		gateMsg = jq('gameClosed',xml).text();
	}
	if(jq('notification',xml).length == 0 && jq('gameClosed',xml).length == 0){
		removeGate();
	}
}

function disablePlay(){
	if(jq('#CarsPlayButton').length > 0){
		jq('#CarsPlayButton').remove();
	}
}

function showGate(msg){
	if(msg != 'true' && msg != 'false'){
		if(jq('#gate').length == 0){
			jq('#chrome').after('<div id="gate"><div class="l_gate"><p>'+msg+'</p></div></div>');
			jq('#gate').slideDown();
		}
		if(jq('#gate p').html() != msg)
			jq('#gate p').html(msg);
	}
}

function removeGate(){
	gate = false;
	jq('#gate').slideDown(function(){jq(this).remove();});
	loadPlayButton();
}

function carsLogin(u,p){
	if(gate == true){
		alert(gateMsg);
	}else{
		jq.ajax({
			type: "GET",
			url: login,
			data: "username="+u+"&password="+p,
			success: loginSuccess,
			error: handleError
		});
	}
}

function toCancel(){
	window.location = '/sponsorship/manage-account/cancel-sponsorship/confirmation.html';
}

function productLoginSuccess(){	
}

function loginComplete(){	
}
function handleError(e){
	alert(e);
}
function exitMod(){
	disablePopup(activeDiv);
}
function loadOverlay(){
	
}

function loadRegMod(){
	if( !swfobject.hasFlashPlayerVersion( '10' ) ) {
		jq( window ).attr( 'location', PATH.siteRoot +'/flash-upgrade/' );
		return false;
	}

	if(gate == true){
		alert(gateMsg);
	}else{
	jq('body').append('<div id="regDiv"><div id="flashcontent"></div></div><div id="blk_alpha"></div>');
	jq('#regDiv').css({
			"position":"absolute",
			"left":"0",
			"top":"0",
			"width":"997px",
			"height":"100%",
			"z-index":"999999"
		});

		centerPopup('regDiv');
		whichModule = "registration";			

		flashparams["base"]				= PATH.swf +'/reg/';
		flashvars["registrationOnly"]	= "";
			
    var attributes = {
			id:"CarsReg"
		};

		swfobject.embedSWF( PATH.swf +'/reg/DVC_OS.swf', "flashcontent", "100%", "100%", "10.0.0","http://a.dolimg.com/swf/dcom/expressInstall.swf", flashvars, flashparams, attributes, function(e){
			setTimeout( 'jq( "#CarsReg" ).focus();', 100 );
		} );
	}
}
/*
function loadRegMod(){
	if(gate == true){
		alert(gateMsg);
	}else{
	jq('body').append('<div id="regDiv"><div id="flashcontent"></div></div><div id="blk_alpha"></div>');
	jq('#regDiv').css({
			"position":"absolute",
			"left":"0",
			"top":"0",
			"width":"997px",
			"height":"100%",
			"z-index":"999999"
		});

		centerPopup('regDiv');
		whichModule = "registration";			
		flashparams["base"] = basePath+"/swf/reg/";
			
    var attributes = {
			id:"CarsReg"
		};

		swfobject.embedSWF(basePath+"/swf/reg/DVC_OS.swf", "flashcontent", "100%", "100%", "10.0.0","http://a.dolimg.com/swf/dcom/expressInstall.swf", flashvars, flashparams, attributes, function(e){
			setTimeout( 'jq( "#CarsReg" ).focus();', 100 );
		} );
	}
}
*/
function loadPurchMod(){
	if( !swfobject.hasFlashPlayerVersion( '10' ) ) {
		alert( 'Flash 10 required.' );
		return false;
	}

	jq('body').append('<div id="purchDiv"><div id="flashPurch"></div></div><div id="blk_alpha"></div>');
	jq('#purchDiv').css({
			"position":"absolute",
			"left":"0",
			"top":"0",
			"width":"997px",
			"height":"906px",
			"z-index":"999999"
		});
		centerPopup('purchDiv');		
		whichModule = "purchasing";
			
			var loginPageURL = querySt("loginURL");
			if( loginPageURL == null )
				loginPageURL = "someurl.html";
			
			var playPageURL = querySt("playURL");
			if( playPageURL = null )
				playPageURL = "someurl.html";

			flashvars["loginPageURL"] = loginPageURL;
			flashvars["playPageURL"] = playPageURL;

			flashvars["whoAmI"]					= PATH.siteRootSecure + whoAmI;
			flashparams["base"]					= PATH.swfSecure +'/purchasing/';

			for( i in flashvars ) {
				if( typeof flashvars[i] == 'string' ) {
					flashvars[i] = flashvars[i].replace( PATH.cdn, PATH.cdnSecure );
				}
			}			

			var attributes = {
				id:"CarsPurchasing"
			};
		swfobject.embedSWF(PATH.swfSecure+"/purchasing/DVC_OS.swf", "flashPurch", "100%", "100%", "9.0.0","http://a.dolimg.com/swf/dcom/expressInstall.swf", flashvars, flashparams, attributes, function(e){
			setTimeout( 'jq( "#CarsPurchasing" ).focus();', 100 );
		} );
}

function loadAcctMgr(){
	jq('body').append('<div id="acmDiv"><div id="flashACM"></div></div><div id="blk_alpha"></div>');
	jq('#acmDiv').css({
			"position":"absolute",
			"left":"0",
			"top":"0",
			"width":"997px",
			"height":"100%",
			"z-index":"999999"
		});
		centerPopup('acmDiv');
		whichModule = "accountManagement";			
		flashparams["base"] = basePath+"/swf/acm/";
			
    var attributes = {
			id:"CarsAcctMgmt"
		};

		swfobject.embedSWF(basePath+"/swf/acm/DVC_OS.swf", "flashACM", "100%", "100%", "10.0.0","http://a.dolimg.com/swf/dcom/expressInstall.swf", flashvars, flashparams, attributes, function(e){
			setTimeout( 'jq( "#CarsAcctMgmt" ).focus();', 100 );
		});
}

function loadPlayButton(){
	if( jq( '#CarsPlayButton' ).length > 0 ) {
		return false;
	}

	jq('#header_play').html('<div id="flash_play"></div>');
	if( swfobject.hasFlashPlayerVersion("10") ) {
		jq( '#flash_play' ).html( '<a class="create_car_button" href="javascript: loadRegMod();"></a>' );
	} else {
		jq( '#flash_play' ).html( '<a class="upgrade_flash_button" href="'+ PATH.siteRoot +'/flash-upgrade/"></a>' );
	}

	/*

	jq('#header_play').append('<div id="flash_play"></div>');
	flashparams["base"] = "http://a.dolimg.com/worldofcars/websitedevelopment/swf/play_btn/";
					
	var attributes = {
		id:"CarsPlayButton"
	};
		
	swfobject.embedSWF("http://a.dolimg.com/worldofcars/websitedevelopment/swf/play_btn/DVC_OS.swf", "flash_play", "100%", "100%", "9.0.0", "", flashvars, flashparams, attributes)
	*/
}

function loadDataservice(){
	var swfBaseUrl	= arguments[0] ? arguments[0] : PATH.swf;
	var callback	= arguments[1] ? arguments[1] : false;
	var wrap = jq('<div>');//.css({'height':'0px','width':'0px'});

	jq('body').append('<div id="flash_content"></div>');
	jq('#flash_content').wrap(wrap);		
	var attributes = {};
		attributes['id'] = 'dataservice';
		attributes['allowScriptAccess'] = "always";
	var flashparams = {};
		flashparams['allowScriptAccess'] = "always";
	var flashvars = {};
		flashvars['allowScriptAccess'] = "always";

	swfobject.embedSWF(swfBaseUrl +'/dataservice.swf', "flash_content", "1", "1", "9.0.0", "", flashvars, flashparams, attributes, callback);
}

function regComplete(){
	if( window.location.href.indexOf( '/race-codes/' ) != -1 ) {
		disablePopup( 'regDiv' );
		callRaceCodes();
	} else {
		window.location.href = PATH.siteRoot +'/community/';
	}
}

function goToReg(){
	loadRegMod();
}
			
function purchaseComplete(){	
	disablePopup(activeDiv);	
	window.location.href="/sponsorship/";
}

function toXML(string){
	try //Internet Explorer
	{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.loadXML(string);
		return xmlDoc;
	}
	catch(e)
	{
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(string,"text/xml");
		return xmlDoc;
	}	
}

function launchGame(){
	disablePopup(activeDiv);	
	window.open("/play.html","game_window","status=no,height=700,width=1005,resizable=no,toolbar=no,menubar=no,scrollbars=no,location=no,dependent=yes");
	game_window.focus();
}

function callRaceCodes(){
	jq('body').append('<div id="raceCodesDiv"><div id="flashcontent"></div></div><div id="blk_alpha"></div>');
	jq('#raceCodesDiv').css({
			"position":"absolute",
			"left":"0",
			"top":"0",
			"width":"600px",
			"height":"500px",
			"z-index":"999999"
		});

		centerPopup('raceCodesDiv');
		whichModule = "registration";			
			
		var flashparams = {
			menu: "false",
			scale: "noScale",
			allowFullscreen: "true",
			allowScriptAccess: "always",
			bgcolor: "#FFFFFF",
			base: PATH.swf +'/race_codes/',
			wmode: 'transparent'
		};
		var attributes = {
			id:"CarsCodeRedeem"
		};

		swfobject.embedSWF( PATH.swf +'/race_codes/DVC_OS.swf', "flashcontent", 600, 500, "10.0.0","http://a.dolimg.com/swf/dcom/expressInstall.swf", flashvars, flashparams, attributes );
}

function helpSwitch(){
	jq('.q_list a').removeClass('selected');
	jq(this).addClass('selected');
	var index = jq('.q_list a').index(this);
	jq('.help_answer_mod p').each(function(i){
		if(i == index){
			jq(this).fadeIn();
		}else{
			jq(this).hide();
		}
	});
}
function querySt(name) {
	gy = window.location.search.substring(1).split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == name) {
			return ft[1];
		}
  }
}
var errorMsgs = [];
errorMsgs[1] = 'Unautorized';
errorMsgs[2] = 'We were unable to send your feedback please <a href="/help/contact-us/">click here</a> to try again.';
errorMsgs['default'] = 'We\'re sorry, we are having difficulties with your request.';

function goToLogin() {
	exitMod();
	loadRegMod();
}

if( typeof nav != 'undefined' ) {
	var NAV = new nav( {
		'pages'	: {
			'about'		: PATH.siteRoot +'/about-game.html',
			'help'		: PATH.siteRoot +'/help.html',
			'trailer'	: PATH.siteRoot +'/trailer.html'
		}
	} );
}