var EXTERNAL_CLOSE = 'externalClose';
var OPEN_VARIABLES = 'openVariables';
var BROWSER_UID_LEN = 8;
var SB_WIDTH = 850;
var SB_HEIGHT = 600;
var MIN_SB_HEIGHT=600;
var FRONT_INDEX = 60;
var BACK_INDEX = 10;
var BUGGY_FF_VERSION=0; // // Applies to all FF versions
var IE7_PNG_SUFFIX = ".png";

var openVars;
var versionStr='';
var errorsReporting=false;
var gamePageName="gameplay";
var gameParams;
var scriptParams = {};

var amInIframe=checkIsIframe();//we want to call the check function once since it throws errors
var isIframe=function(){return amInIframe;}
var clientName;
var clientUrl;
var clientFrameId;

$.ajaxSetup({
	cache: true
});

function generateClientName() {
	var d = new Date();
	return "client" + d.getTime();
}

function resetClient(){
	clientName = generateClientName();
	clientFrameId = 'frame_'+clientName;
	clientUrl  = null;
}

var serverName = 'main';
var wrapperCount = 0;
var wrapperName = "";
var wrapperContent = "";
var username = null;
var reloadReason = "user";

var initialHash;

var fb_appID = "193458864000413";
var fbAppUrl = "http://apps.facebook.com/secretbuilders/";


document.originalTitle = document.title;

String.prototype.beginsWith = function(str) {return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};


var browserIE = {
  version: function() {
	var version = 999; // We assume a sane browser (not IE)
	if (navigator.appVersion.indexOf("MSIE") != -1)
	  // IE, so lets downgrade version number
	  version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	return version;
  }
}

var browserFF = {
	version: function(){
		var vrs=999;
		if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
			vrs=parseFloat(RegExp.$1);
		}
		return vrs;
	}
}

function new_xmlHttp(){
	var obj = null;
	try { 
		obj=new XMLHttpRequest();
	}
	catch (e) {
		try {
			obj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1){
			try {
				obj=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				alert("Your browser does not support AJAX!");			
			}
		}
	}    
	
	return obj;
}

function CookiesClass() {

    this.write = function (name, value, seconds) {
		var expires = "";
		
        if (typeof(seconds) != 'undefined') {
            var date = new Date();
            date.setTime(date.getTime() + (seconds*1000));
            expires = "; expires=" + date.toGMTString();
        }
	
		var cookie = name+"="+value+expires+"; path=/";
		document.cookie = cookie;
	};

    this.read = function (name) {
        name = name + "=";
        var carray = document.cookie.split(';');
	
        for(var i=0;i < carray.length;i++) {
            var c = carray[i];
            while (c.charAt(0)==' ') {
				c = c.substring(1,c.length);
			}
			
            if (c.indexOf(name) === 0) {
				return c.substring(name.length,c.length);
			}
        }
	
        return null;
    };
    
    this.erase = function (name) {
        this.write(name, "", -1);
    };
}

var Cookies = new CookiesClass();

function supportsCookies() {
	// Set testing cookie
	Cookies.write("testcookie", "1");
	cookieEnabled = Cookies.read("testcookie") == "1";
	
	if(cookieEnabled) {
		Cookies.erase("testcookie");
	}
	
	return cookieEnabled;
}

function ExternalClass() {
    this.reloaded = false;
    this.reloadVars = "";
	this.connStr = "";
	this.env=undefined;
    
    this.onBeforeUnload = function () {
		if(reloadReason != "reload") { // If not 10-th room reload
			ex_pass(serverName,'BeforeUnload',reloadReason);
			var report_reload = null;
			
			if(reloadReason == "user") {
				report_reload = "refresh";
				removeMain(); // Destroy swf. Browser button reload.
			}
			else { // reload2
				report_reload = "reload";
			}
				
			Cookies.write("report_reload", report_reload, 60);
			
		}
    };
    
	this.initParams = function(hash) {
		if(typeof(hash)=="undefined")
			return false;
		var reloadStart = "#/reload/";
		
		if(!hash.beginsWith(reloadStart)) {
			// Not a reload. Do nothing.
			return false;
		}
		
		var vars = parseQueryString(hash.substr(reloadStart.length));
		
		var relvar = vars["reload"];
		var connstr = vars["constr"];
		var expTime = parseInt(vars["exp"]) * 1000; // Time is in seconds
		delete vars["exp"];
		var sbEnv = {};
		delete vars["reload"];
		delete vars["constr"];
		
		for(envParam in vars) {
			sbEnv[envParam] = vars[envParam];
		}
		
		var now = new Date();
		
		if(expTime >= now.valueOf()) {
			// Data not expired
			this.reloadVars = relvar;
			this.connStr = connstr;
			this.reloaded = true;
		}
		
		window.location.hash = "/login";
		this.env = sbEnv;
		return false;
	};
	
    this.onLoad = function () {
		return this.initParams(document.location.hash);
    };
	
}

var External = new ExternalClass();

function getUrlParam(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	
	if( results == null )
		return "";
	else
		return results[1];
}

function getEl(el) {
    return document.getElementById(el);
}

function getMain() {
	return findObject(serverName);
}

// Said by Adobe to be more reliable than getElementById
function findObject(movieName) {
	var result = null;
	
    if (navigator.appName.indexOf("Microsoft") != -1) {
		result = window[movieName];
    } 
	
	if(isNull(result) && (document[movieName] != movieName)) {
		result = document[movieName];
    }
	
	if(isNull(result)) {
		result = getEl(movieName);
	}
	
	return result;
}

function isNull(target){
	return target == null || typeof(target) == 'undefined';
}
function fixAnchorTitleBug() { 
	document.title = document.originalTitle; 
} 

function setFocusOnClient() {
	// Give focus to client to handle keyboard properly.
	var flashObject = findObject(clientName);
	
	if(typeof(flashObject) != 'undefined') {
		flashObject.focus();
	}
}


function convertRequest(){
    var strHref = document.location.href;
    if ( strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?") + 1).toLowerCase();
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].indexOf("=") > -1 ){
			var aParam = aQueryString[iParam].split("=");
			if(aParam[0] == 'contest'){					
				Cookies.write('contest', aParam[1]);
			}else if (aParam[0]=='forcedperfclass' || aParam[0]=='netspd' ){
				if(aParam[1].length > 0 && aParam[1] != "clear") {
					Cookies.write(aParam[0], aParam[1]);
				}
				else {
					Cookies.erase(aParam[0]);
				}
			}
			}
		}
    }
}

function isBrowserIE(version) {
	return (/MSIE (\d+\.\d+);/).test(navigator.userAgent);
}

function isEeLt() {
	IE6 = navigator.appVersion.indexOf("MSIE 6.") != -1;
}

function removeMain() {
	if(!isNull(swfobject))
		swfobject.removeSWF(serverName);
	getEl("flashContent").innerHTML = "";
}

function hideMain() {
	getEl("externalContent").style.zIndex = FRONT_INDEX;
	if(!(getEl("externalContent").innerHTML)){
		showSplash();
	}
}

function showMain() {
	hideSplash();
	getEl("externalContent").style.zIndex = BACK_INDEX;
}

function showSplash(){
	getEl("splash").style.zIndex = FRONT_INDEX+10;//splash over main
}

function hideSplash(){
	getEl("splash").style.zIndex = BACK_INDEX-1;
}

// This return 4 digit 16x integer number
function randomString() {
    return (((1 + Math.random())*0x10000) | 0).toString(16).substring(1);
}

function randomIdentifier() {
    var result = "";
    
    for(var i = 0; i < BROWSER_UID_LEN; i++) {
		result += randomString();
	}
    
    return result;
}

function noCacheIE(url){
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	if(!isIE) {
		return(url);
	}
	
	var newUrl = '?';
	if(url.indexOf('?') != -1) {
		newUrl = '&';
	}
	
	var now = new Date();
	var rand = Math.random().toString().substring(2,4);
	newUrl = url+newUrl+"noCacheIE="+rand+'-'+now.getTime().toString();
	return(newUrl);
}

function parseQueryString(query){
	var varsRes = {};
	var vars = query.split("&"); 
	
	for (var i=0; i < vars.length; i++) { 
		var pair =vars[i].split("=");
		varsRes[pair[0]] = unescape(pair[1]);
	}
	
	return varsRes;
}

function ex_get_uid() {
    var uid = Cookies.read("browserUid");
    
    if(!uid) {
	uid = randomIdentifier();
	Cookies.write("browserUid", uid);
    }
    
    return uid;
}

function ex_alert(message) {
    setTimeout('alert('+'"'+message+'")',1);
}

function ex_confirm(message) {
    return confirm(message);
}

function ex_prompt(message, defaultvalue) {
    return prompt(message, defaultvalue);
}

function ex_clear() {
    var clientFrame = findObject(clientFrameId);
	
	if(!isNull(clientFrame)){
		var clientDoc=clientFrame.contentDocument || clientFrame.contentWindow || clientFrame;
		if(!isNull(clientDoc.document))
			clientDoc = clientDoc.document;
		try{clientDoc.dispose();}catch(e){};//ie 8 says object doesn't supprot this action
	}
	
	getEl("externalContent").innerHTML = "";
	resetClient();
	showMain();
}
function ex_write(text, wrapperUrl) {
	if(wrapperUrl) {
		wrapperContent = text;
		wrapperName = "contentWrapper" + (wrapperCount++);
		getEl('externalContent').innerHTML = "";
		
		var ifr = '<iframe id="{0}" name="{0}" src="{1}" class="wrapperFrame" onLoad="exContentLoaded()" frameborder="0" scrolling="no"></iframe>';
		ifr = ifr.format(wrapperName, wrapperUrl, SB_WIDTH, SB_HEIGHT);
		
		var loading = '<div id="excProgress">LOADING</div>';
		
		ex_write(ifr + loading);
		hideMain();
		return;
	}

    getEl('externalContent').innerHTML += text;
}

function exContentLoaded(){
	wrapIframeContent();
	
	var parent = getEl("externalContent");
	var progress = getEl("excProgress");
	
	parent.removeChild(progress);
}


function wrapIframeContent() {
	if(wrapperContent && wrapperContent.length) {
		var contentEl = window.frames[wrapperName].document.getElementById("content");
		
		if(contentEl) {
			contentEl.innerHTML = wrapperContent;
		}
		
		//window.frames[wrapperName].document.getElementById("divClose").innerHTML = '&nbsp;';
		wrapperContent = "";
	}
}

function ex_open(src, bgcolor, vars, switchVisibility) {
	resetClient();
    openVars = vars;
	var iframe_src = vars && vars.iframe_src && vars.iframe_src.length ? vars.iframe_src : "game_frame.html";
    
    clientUrl = src;
	getEl("externalContent").innerHTML = "";
	var clientFrame = document.createElement("iframe");
	clientFrame.setAttribute("id",clientFrameId);
	clientFrame.setAttribute("src","/gameplay/" + iframe_src + "?cv="+ versionStr);
	clientFrame.setAttribute("scrolling","no");
	clientFrame.setAttribute("frameBorder",0);
	clientFrame.setAttribute("width",SB_WIDTH);
	clientFrame.setAttribute("height",SB_HEIGHT);
	clientFrame.setAttribute("onError","alert('Error loading game.please try again later.');ex_close({error:{id:'load'},target:'frame'})");
	getEl("externalContent").appendChild(clientFrame);
	
	if(switchVisibility == false && (!shouldShowSWF()))
		showMain();
	else
		hideMain();
}

function ex_switch_client(){
	hideMain();
}

function ex_username(user) {
	username = user;
}

function ex_reload (connectionString, reloadVars,environment) {
	var now = new Date();
	var ttl = 60;
	var expTime = Math.round(now.valueOf() / 1000) + ttl;
	
	var hash = "#/reload/constr=" + escape(connectionString) + "&reload=" + escape(reloadVars) + "&exp=" + escape(expTime);
	
	if(typeof(environment) !="undefined")
		hash+="&"+environment;
		
	reloadReason = "reload"; // 10-th room reload
	
	reloadLoc(hash);
}

function ex_reload2 () {
	reloadReason = "reload2"; // Reload due to error
	reloadLoc(initialHash);
}

var reloadLoc=isIframe() ? 
function(hash){
	removeMain();
	showSplash();
	External.initParams(hash);
	getVersion();
}:
function(hash){
	removeMain();
	window.location.hash = hash;
	location.reload(true);
};

function ex_reloadVars() {
    return {connStr: External.connStr, reloadVars: External.reloadVars};
}

function ex_isReloaded() {
    return External.reloaded;
}

function ex_pass(id, type, data) {
    findObject(id).flashDataPass(type, data);
}

function ex_close(data) {
    //ex_clear();
    openVars = null;
    ex_pass(serverName, EXTERNAL_CLOSE, data);
}

function ex_pass_main(type, data) {
	ex_pass(serverName, type, data);
}

function ex_pass_client(type, data) {
	ex_pass(clientName, type, data);
}

function ex_openvars() {
	var client = findObject(clientName);
	//alert('ex_openvars client='+client)
    if(client !== null) {
		setFocusOnClient(); // Set focus to client
		ex_pass(clientName, OPEN_VARIABLES, openVars);
    }
	
}

function ex_get_cookie(key) {
    return Cookies.read(key);
}

function ex_set_cookie(key, value, exp) {
    Cookies.write(key, value, exp);
}

function ex_erase_cookie(key) {
    Cookies.erase(key);
}

function ex_eval_to_object(str) {
	var res = "";

	/*try {
		res = eval("(" + str + ")");
	}
	catch(e) { return {error: true, result: ""}; }*/
	
	return {error: false, result: res};
}

function pgt(page){
	parent.gt(page);
}

function embedMainSWF() {
	if(isNull(swfobject)){
		ex_reload2();
		return;
	}
	var mainurl = ex_isReloaded() ? "main.swf" : "login.swf";
	
	if(errorsReporting) {
		mainurl += "?pr=1";
	}
	showSplash();
	var flashVars = getFlashVars();
	flashVars.isSelected = getSelectedObjectId() == serverName;;
	swfobject.embedSWF.apply(this,generateEmbedParams(serverName,mainurl,flashVars));
	
}

function mainLoaded(){
	showMain();
	getEl("splash").innerHTML = "";
}

function generateEmbedParams(id,src,flashvars){
	src+=  (src.indexOf("?") > 0 ? "&cv=" : "?cv=") + versionStr;
	var params = {wmode: "opaque", cv: versionStr,allowscriptaccess: "always", menu:"false"};
	var attributes = {id: id, name: id};
	
	if(isNull(flashvars))
		flashvars = {};
		
	return [src, id, SB_WIDTH, SB_HEIGHT, "9.0.115", "../common/scripts/playerProductInstall.swf", flashvars, params, attributes,onSWFEmbedResult];
}

function onSWFEmbedResult(res){
	if(!res.success){
		var el = getEl(res.id);
		if(el){
			el.innerHTML = '<br/><br/><div style="text-align:center;width:100%"><font style="background-color:#000000;">Oops! Looks like you don\'t have Adobe Flash<br/>which is needed to access Secret Builders.<br/>Click<a href="http://www.adobe.com/go/getflash/"> here </a>to get Flash.</font></div>';
		}
		if(res.id == serverName){
			showMain();
		}
	}
}

function startGame(acParam) {
		var main = getEl(serverName);
		if(isNull(main)){
			main = document.createElement("div");
			main.setAttribute("id",serverName);
			getEl("flashContent").appendChild(main);
		}
		
		versionStr = acParam;
		/*if(!isIframe()){
			fitToWindow();
			window.onresize=fitToWindow;
		}*/
		embedMainSWF();
		
}

function getVersion(){
	try{
		var xmlHttp = new_xmlHttp();		
		var params = '';
		xmlHttp.onreadystatechange=function(){
			if(xmlHttp.readyState==4){				
				startGame(xmlHttp.responseText);
			}			
		};
		
		var d = new Date();
		var t = d.getTime();
		xmlHttp.open("GET",'/build.txt?ac=' + t, true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);	
	}catch(e){
		startGame('');
	}
}

function sendToURL(url, params, readyHandler) {
	try{
		var xmlHttp = new_xmlHttp();
		
		xmlHttp.open("POST",url, true);
		//Send the proper header infomation along with the request
		xmlHttp.setRequestHeader("Content-type", "text/plain");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
	
		xmlHttp.onreadystatechange = readyHandler;
		xmlHttp.send(params);

	}catch(e){
	    //		alert(e);
	}
	
	return null;
}

//support for logging important messages. One at a time.
function ex_logPlease(message) {
    Cookies.write("log", message, 36000); //keep for 10 hours
}

function changeVisibility(what, visible){
	if(what == clientName) {
		if(visible) {
			hideMain();
		}
		else {
			showMain();
		}
		
		return;
	}
	else if(what == serverName) {
		if(visible) {
			showMain();
		}
		else {
			hideMain();
		}
		
		return;
	}
	
	var obj = findObject(what);
	if(typeof obj == 'undefined')
		return;
	
	if(browserIE.version() <= 7 || browserIE.version() == 9) {
		if(visible){
			obj.style.width = String(SB_WIDTH)+'px';
			obj.style.height = String(SB_HEIGHT)+'px';
		}else{
			obj.style.width = obj.style.height = '0px';
		}
	}
	else {
		if(visible){
			obj.style.visibility = "visible";
			obj.style.opacity=1;
		}else{
			obj.style.visibility = "hidden";
			obj.style.opacity = 0;
		}
	}
	
}

//support for reading important messages.
function ex_getUrgentLog() { return Cookies.read("log"); }
//clearing importanat messages
function ex_eraseUrgentLog() { Cookies.erase("log"); }

window.fbAsyncInit = function() {
	try {
		getEl(serverName).initFacebook("allLoaded");
	} catch (err) { }
};

//we need that flag cause the fbAsyncInit doesn't get called sometimes
function getFBAsync() {
	try {
		return window.fbAsyncInit.hasRun;
	} catch (err) { 
		return "error";
	}
}

window.bridgeAsyncInit = function() {
	try {
		getEl(serverName).initFacebook("bridgeLoaded");
	} catch (err) { }
};

function getScriptWithParams(url, params) {
	if($("script[src='" + url + "']").length) {
		return true;
	}
		
	if(params.params_id && params.params_id.length) {
		// We need params_id if it is not presents no params will be saved.
		scriptParams[params.params_id] = params;
	}
	
	$.getScript(url);
	return false;
}

//to add the facebook javascripts
function addScriptSource(url, onloadScript, target) {
	if($("script[src='" + url + "']").length) {
		// script already included
		return true;
	}
	else if(typeof(target) != "undefined") {
		var targetDiv = getEl(target);
		
		if(!targetDiv){
			targetDiv = document.createElement("div");
			targetDiv.setAttribute("id", target);
			$("body").append(targetDiv);
		}
		
		var e = document.createElement("script");
		e.type = "text/javascript";
		e.async = true;
		e.src = url;
		$("#" + target).append(e);
	}
	else {
		$.getScript(
			url,
			function() {
				if(onloadScript && onloadScript.length) {
					eval(onloadScript);
				}
			}
		);
	}
	
	return false;
}

function hasScript(url){
	var elements = document.getElementsByTagName('script');
	for(var i=0;i<elements.length;i++){
		if(elements[i].getAttribute('src') == url) {
			return true;
		}
	}
	
	return false;
}

function sizeFlash(height,width){
	if(typeof(height)!="undefined") {
		width = Math.round((17*height)/12);//ratio
	}
	else if(typeof(width)!="undefined") {
		height = Math.round((12*width)/17);
	}
	else {
		return;
	}
	
	//alert('size:'+width+" "+height)
	setSize('flashDiv',width,height);
	setSize(clientName,width,height);
	setSize('main',width,height);
	SB_WIDTH = width;
	SB_HEIGHT = height;
}

function setSize(elId,w,h){
	var el = findObject(elId);
	if(el!=null && typeof(el)!='undefined'){
		el.width = w;
		el.height = h ;
		el.style.width = w+"px"
		el.style.height = h+"px"
	}
}

function fitToWindow(){
	sizeFlash(Math.round(Math.max(0.87*getWindowHeight(),MIN_SB_HEIGHT)));
}

function getWindowHeight(){
	if( typeof( window.innerWidth ) == 'number' ) {
		return window.innerHeight;
	}else if( document.documentElement && document.documentElement.clientHeight){
		return document.documentElement.clientHeight;
	}else if( document.body && document.body.clientHeight){
		return document.body.clientHeight;
	}
	return 0;
}

function checkIsIframe(){
	try{
		return top.location.href!= window.location.href;
	}catch(err){
		if(typeof(err.message)!='undefined' && err.message.search(/permission/i)>=0 ){
			return true;//only premission errors detected
		}else{
			throw err;
		}
	}
	return true;
}

function getFBparams() {
	return {appId:fb_appID, appUrl:fbAppUrl};
}

function getAppID() {
	return fb_appID;
}

function getFlashVars(){
	var res={};
	
	res.splashImage = isDefined(document.splashImage)?document.splashImage:"sb";
	res.width = 850;
	res.height = 600;
	res.fbAppId = fb_appID;
	res.fbAppUrl = fbAppUrl;
	res.isIframe = isIframe();
	if(!isDefined(initialHash)){
		initialHash = isDefined(SWFAddress)?SWFAddress.getValue():(document.location.hash?document.location.hash.replace(/^#/,''):'');
	}
	res.hash = escape(initialHash);
	
	if(External.reloaded){
		res.connStr = External.connStr;
		res.reloadVars = External.reloadVars;
		
		res.isReloaded = true;
		
		if(isDefined(External.env)){
			for(param in External.env)
				res[param]=External.env[param];
		}
	}
	//browser
	if($.browser){
		for(param in $.browser){
			if(param == 'version'){
				res.browserVersion = $.browser[param];
			}else{
				res.browser=param;
			}
		}
	}
	
	return res;
}

function isDefined(val){
	return typeof(val)!="undefined"
}

function getSelectedObjectId(){//returns either 'splash',clientName or serverName
	if(getEl("splash").style.zIndex > FRONT_INDEX){
		return "splash";
	}
	return (getEl("externalContent").style.zIndex == FRONT_INDEX)?clientName:serverName;
}

function shouldShowSWF(){
	if(BUGGY_FF_VERSION == 0) {
		// Applies to all FF versions
		return navigator.userAgent.indexOf("Firefox") >= 0;
	}
	
	return browserFF.version() <= BUGGY_FF_VERSION;
}

// Make the functions visible from iframes.
window.ex_close = ex_close;
