var debugStr = "";
function debug(str){
	debugStr+=str+"\n";
}

// DE stuff
var forceInfoObj;
var initDEFailed =false;
var openDEOnStart=false;
openDEInRow = {};
openDEInRow.openAnother = false;
var DEFirstTime = true;
//end of DE stuff

var overallHeight = 0;
var heightStepper = 0;
var attPopupOpen = 0; //number of popups that disables the screen that are open.
var popOnStart = "";
var DEloaded = false;
var pageLoaded = false;
var opaqueParams = {wmode:"opaque",bgcolor:skinColor,menu:"false"};	
var SWFsArray = new Array();
SWFsArray["header.swf"] = {divName:"header",width:980,height:163,className:"header"};
//SWFsArray["quickMenu.swf"] = {divName:"quickMenu",width:980,height:85,className:"quickMenu"};

//if (sessionVars.s != "n"){
	SWFsArray["currMobi.swf"] = {divName:"currMobi",width:980,height:100,className:"currMobi"};
//}
SWFsArray["topContent.swf"] = {divName:"topContent",width:980,height:185,className:"topContent"};
SWFsArray["as3assets/MobiFrontPageWall.swf"] = {divName:"toolbars",width:980,height:465,className:"toolbars"};

currPopup = null;

function initPage(){
	
	if (!swfobject.hasFlashPlayerVersion("8.0.0")){
		return;
	}

	document.getElementById("header").innerHTML = "";
	//alert ("welcome!");

// first load all things that are visible
	overallHeight = 0;
	for (var i in SWFsArray){
		overallHeight += SWFsArray[i].height;
	}
	//hide loader:
	//hideLoader();

	placeFooter();

	//start embedding:
	initLoader();
	
	
//hide blocker
	//document.getElementById("blockerContainer").className = "f-hide";
	enable();
}

function initHidden(){
//load DE and hide it
	var flashvars = {containingDiv:"downloadElement"};
	var params = {menu:"false"};
	params.wmode = "transparent";
	params.allowscriptaccess = "sameDomain";
	var attributes = {};
	swfobject.embedSWF(skinFolder+"downloadElement.swf", "downloadElement", "406", "406", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	swfobject.createCSS("#downloadElement","outline:none");
	debug("DE embedded");
//init popups:
	document.getElementById("popups").className = "popups";
	document.getElementById("popups").style.top = document.getElementById("toolbars").style.top;
	document.getElementById("popups").style.height = document.getElementById("toolbars").style.height;

// load Login window and hide it
	loginObjVars = sessionVars;
	loginObjVars["containingDiv"] = "loginFormSWF";
	swfobject.embedSWF(skinFolder+"Login.swf", "loginFormSWF", "932", "250", "9.0.0", "expressInstall.swf", loginObjVars, opaqueParams, {});		
	document.getElementById("loginFormSWF").className = "f-hide";
	
// hide normal popups
	document.getElementById("normalPopup").className = "f-hide";
	
//hide movie:
	//hideMovie();
		document.getElementById("movieContainer").className = "f-hide";

	attPopupOpen = 0;

//hide blocker
	//document.getElementById("blockerContainer").className = "f-hide";
	enable();

//login failure check:
	if ((attemptedLogin)&&(!loginSuccess)){
			popOnStart = "login";
		}
	
	switchAction();

	stepInit("allDone");
	
}

function allowImageLoading(){
	for (var i in SWFsArray){
		if (document.getElementById(SWFsArray[i].divName).allowImageLoading!= undefined){
			document.getElementById(SWFsArray[i].divName).allowImageLoading();
		}
	}
}

function stepInit(step){

	//alert ("stepInit("+step+")");

	switch(step){
		case "header":	//initLoader();
		initLoaderBG();
		if (!pageLoaded){
									//embedBodySWF("quickMenu.swf");
									embedBodySWF("as3assets/MobiFrontPageWall.swf");
								}
		break;
		case "loader": 	embedBodySWF("header.swf");
		document.getElementById("loaderSWF").advanceLoader(3);
		
		break;
		case "quickMenu"://if (sessionVars.s != "n"){
									embedBodySWF("currMobi.swf");
									/*} else {
										embedBodySWF("topContent.swf");
									}*/
		break;
		case "toolbars": embedBodySWF("topContent.swf");
		document.getElementById("loaderSWF").advanceLoader(2);
		break;
		case "topContent": embedBodySWF("currMobi.swf");
		document.getElementById("loaderSWF").advanceLoader(1);
		break;
		case "currMobi":
									hideLoader();
									pageLoaded = true; //not after "login.swf" is loaded, because we don't wanna block the auto-action.		
									initHidden(); //Last to load and call this function: downloadElement.swf - not correct
		break;
		case "blocker": break;
		break;
		case "DE": 
			if (!DEloaded){
				debug("stepInit DE");
				document.getElementById("downloadElement").className = "f-hide";
				document.getElementById("DEContainer").className = "f-hide";
			}
			
			DEloaded = true;
			debug ("to open the DE: "+openDEOnStart);
			if (openDEOnStart){
				openThumbByItemId(pageParams["id"]);
			}
		break;
		
		case "allDone": 
		allowImageLoading();
		if (navigator.appName!="Microsoft Internet Explorer"){
			//alert ("This site is still not fully functional in your browser.\nUntil this is fixed, we recommand using Microsoft Internet Explorer.");
		}			
		break;
		
		case "login":	checkPopOnStart();
		break;
		
		default: break;
	}
	
}

function embedBodySWF(i){ //i == swf's name
		//alert(i);
		flashVars = sessionVars;
		flashVars["containingDiv"] = SWFsArray[i].divName;
		swfobject.embedSWF(skinFolder+i/*+"?t="+new Date().getTime()*/, SWFsArray[i].divName, SWFsArray[i].width, SWFsArray[i].height, "9.0.0", "expressInstall.swf", sessionVars, opaqueParams , {})
		swfobject.createCSS("#"+SWFsArray[i].divName,"outline:none");
		document.getElementById(SWFsArray[i].divName).className=SWFsArray[i].className;
		document.getElementById(SWFsArray[i].divName).style.top = heightStepper;
		document.getElementById(SWFsArray[i].divName).style.height = SWFsArray[i].height;
		document.getElementById(SWFsArray[i].divName).style.marginLeft = -Number(SWFsArray[i].width)/2
		heightStepper+=SWFsArray[i].height;
}

function initLoader(){
	document.getElementById("loaderContainer").className = "loaderContainer";
	document.getElementById("loaderContainer").style.top = SWFsArray["header.swf"].height;
	document.getElementById("loaderContainer").style.height = overallHeight-SWFsArray["header.swf"].height;
	//hide footer and BG:
	document.getElementById("loaderBottom").className= "f-hide";
	document.getElementById("loaderBG").className= "f-hide";
	
	document.getElementById("loaderSWFContainer").className = "loaderSWFContainer";
	swfobject.embedSWF("MobiLoader.swf"/*+"?t="+new Date().getTime()*/, "loaderSWF", "150", "225", "9.0.0", "expressInstall.swf", {}, {bgcolor:"#152230",menu:"false",wmode:"transparent"}, {});	
}

function initLoaderBG(){
	//reveal footer and BG:
	document.getElementById("loaderBottom").className= "";
	document.getElementById("loaderBG").className= "";
	
	document.getElementById("loaderBG").style.top = "0px";
	document.getElementById("loaderBG").style.width = "980px";
	document.getElementById("loaderBG").style.height = Number(document.getElementById("loaderContainer").style.height.substr(0,3))-30;
	document.getElementById("loaderBottom").style.top = document.getElementById("loaderBG").style.height;
}

function hideLoader(){
	document.getElementById("loaderContainer").className = "hiddenForm";
	document.getElementById("loaderSWFContainer").className = "f-hide";
	document.getElementById("loaderSWF").className = "f-hide";
	
}

function managePopup(popupClearFunc){
		if ((currPopup!=null)&&(popupClearFunc!=currPopup)){
			currPopup();
		}
		currPopup = popupClearFunc;
		document.getElementById("popups").className = "popups";
}

function showLoginNoClose(){
	currPopup = null;
	showLogin();
}

function showLogin(){
	if (sessionVars.s != "n") return; //extra session check
	if (!pageLoaded) {
		return; //don't show while loader is on
		//actionVar = "login";
	}
	attPopupOpen++;
	managePopup(hideLogin);
	//put trans blocker:
	disable("trans");	
	//document.getElementById("hiddenLoginForm").className ="";
	debug("is that it?" + document.getElementById("loginFormSWF").enableForm);	
	document.getElementById("loginFormSWF").className = "";
	document.getElementById("loginFormSWF").enableForm();
}

function hideLogin(){
	document.getElementById("hiddenLoginForm").className = "hiddenForm";	
	document.getElementById("loginFormSWF").className = "f-hide";
	//remove trans blocker:
	enable();
	attPopupOpen--;
	currPopup = null;
}

function showQReg(){
	if (sessionVars.s != "n") return; //extra session check
	if (!pageLoaded) return; //don't show while loader is on
	attPopupOpen++;
	managePopup(hideQReg);
	swfobject.embedSWF("qReg.swf"/*+"?t="+new Date().getTime()*/, "normalPopup", "932", "185", "9.0.0", "expressInstall.swf", sessionVars,  {wmode:"opaque",bgcolor:"#000000"}, {});
	document.getElementById("normalPopup").className = "";	
}

function hideQReg(){
	document.getElementById("normalPopup").className = "f-hide";	
	//remove trans blocker:
	enable();	
	attPopupOpen--;
	currPopup = null;	
}

function showHelp(){
	if (!pageLoaded) {
		return; //don't show while loader is on	
		actionVar = "help"
	}
	managePopup(hideHelp);
	attPopupOpen++;	
	swfobject.embedSWF("help.swf"/*+"?t="+new Date().getTime()*/, "normalPopup", "932", "185", "9.0.0", "expressInstall.swf", sessionVars,  {wmode:"opaque",bgcolor:"#000000"}, {});
	document.getElementById("normalPopup").className = "";	
	//put trans blocker:
	disable("trans");	
}

function hideHelp(){
	document.getElementById("normalPopup").className = "f-hide";
	//remove trans blocker:
	enable();	
	attPopupOpen--;	
	currPopup = null;
	document.getElementById("popups").className = "f-hide";
}

function showInvite(){
	if (sessionVars=="n") return; //extra session check
	if (!pageLoaded) {
		return; //don't show while loader is on	
		actionVar = "invite";
	}
	managePopup(hideInvite);
	attPopupOpen++;
	swfobject.embedSWF("Invite.swf"/*+"?t="+new Date().getTime()*/, "normalPopup", "932", "300", "9.0.0", "expressInstall.swf", sessionVars,  {wmode:"opaque",bgcolor:"#000000"}, {});
	document.getElementById("normalPopup").className = "";
	//put trans blocker:
	disable("trans");
}

function hideInvite(){
	document.getElementById("normalPopup").className = "f-hide";	
	//remove trans blocker:
	enable();	
	attPopupOpen--;
	currPopup = null;	
}

function showAdult(){
	if(sessionVars.ad==true){
		return;
	}
	if (!pageLoaded) {
		return; //don't show while loader is on	
		actionVar = "adult";
	}
	managePopup(hideAdult);
	swfobject.embedSWF(skinFolder+"Adult.swf"/*+"?t="+new Date().getTime()*/, "normalPopup", "932", "185", "9.0.0", "expressInstall.swf", sessionVars,  {wmode:"opaque",bgcolor:skinColor}, {});
	document.getElementById("normalPopup").className = "";
	//put trans blocker:
	disable("trans");
}

function hideAdult(){
	document.getElementById("normalPopup").className = "f-hide";	
	//remove trans blocker:
	enable();	
	currPopup = null;	
}

function showMovie(){
	managePopup(hideMovie);
	swfobject.embedSWF(skinFolder+"movie.swf"/*+"?t="+new Date().getTime()*/, "movie", "430", "330", "9.0.0", "expressInstall.swf", sessionVars,  {wmode:"opaque",bgcolor:"#000000"}, {});
	document.getElementById("movie").className = "";
	document.getElementById("movieContainer").className = "movieContainer";	
	//put trans blocker:
	disable("trans");	
}

function hideMovie(){
	document.getElementById("movie").className = "f-hide";
	document.getElementById("movieContainer").className = "f-hide";
	//remove trans blocker:
	enable();
	currPopup = null;	
}

function openThumbByItemId(itemID){
	if (itemID){
		ajaxpack.postAjaxRequest("/app/mbCtlg.php", "cmd=pos&id="+itemID, gotItemPosition, "txt")
	}
	openDEOnStart = false;
}

function gotItemPosition(){
	var ajaxResponse = ajaxpack.ajaxobj;
	if (ajaxResponse.readyState == 4){ //if request of file completed
		if (ajaxResponse.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
				var responseArr = responseStringToArray(ajaxResponse.responseText);
				//forceTBToOpenThumb(responseArr["cat"],Number(responseArr["pos"]-1));
				// -1 because pos is one-based and the toolbar is zero-based
				//This was the original call, to get only the position of the item and open it with the toolbar's code. from now on is the temp solution.
				ajaxpack.postAjaxRequest("/app/mbCtlg.php", "cmd=list&c="+responseArr["cat"]+"&strt="+(Number(responseArr["pos"])-1)+"&cnt=1&ord=rt&uid=0", gotItemInfo, "txt");
				//pos-1 because position is 1-based and strt is 0-based
		}
	}
}

function gotItemInfo(){
//TEMPORARY SOLUTION FOR OPEN-ITEM FUNCTION
	var ajaxResponse = ajaxpack.ajaxobj;
	if (ajaxResponse.readyState == 4){ //if request of file completed
		if (ajaxResponse.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
				var responseArr = responseStringToArray(ajaxResponse.responseText);
				var itemInfo = responseArr["i1"].split(",");
				//jumpToToolbar(itemInfo[3])  -- removed in light of no-toolbars change
				while (itemInfo[1].indexOf("+")!=-1){
					itemInfo[1] = itemInfo[1].substring(0,itemInfo[1].indexOf("+"))+" "+itemInfo[1].substring(itemInfo[1].indexOf("+")+1,itemInfo[1].length)
				}
				//imgURL,itemName,rating,category,itemID,X,Y,fileName(should be frontPageContentToolbar.swf)
				showDownloadElement({itemID:itemInfo[0],imgURL:"/media/"+getFolderByCategory(itemInfo[3])+"/tn/"+itemInfo[0]+".jpg",itemName:itemInfo[1],category:itemInfo[3],rating:itemInfo[2],fileName:"as3assets/MobiFrontPageWall.swf",X:490/*632*/,Y:210 })//+TBNumByTBID(itemInfo[3])*44});
		}
	}	
}

function getFolderByCategory(catStr){
		switch (catStr){
			case "r": return "rt";
				break;
			case "w": return "wp";
				break;
			case "c": return "ct";
				break;
			case "s": return "ss";
				break;
			default: break;
		}
}

function forceTBToOpenThumb(category,thumbNum){
	document.getElementById("toolbars").focus();
	//document.getElementById("toolbars").openThumb(TBNumByTBID(category),thumbNum);
	//changed because there's only one toolbar now
	document.getElementById("toolbars").openThumb(0,thumbNum);
}

function showDownloadElement(infoObj){
	debug ("showDE");
	infoObj.s = sessionVars.s; //put session info into the infoObj
	if (!DEloaded){ return; }
	var SWFtop = (document.getElementById(SWFsArray[infoObj.fileName].divName).style.top);
	attPopupOpen=1; //To fix multiple DE openings.
	managePopup(hideDE);
	//place SWF:
	SWFtop = Number(SWFtop.substring(0,SWFtop.length-2));
	document.getElementById("DEContainer").className = "generalDE"
	document.getElementById("DEContainer").style.top = SWFtop+Number(infoObj.Y)-406/2;
	document.getElementById("DEContainer").style.marginLeft = -(490+406/2)+Number(infoObj.X);
	var swf = document.getElementById("downloadElement");
	swf.className="";
	if (((document.getElementById("downloadElement").initDE == undefined)||(DEFirstTime))&&!((navigator.appName=="Microsoft Internet Explorer")||(navigator.vendor=="Google Inc.")||(navigator.vendor=="Apple Computer, Inc."))){//(((document.getElementById("downloadElement").initDE == undefined)||(navigator.appName!="Microsoft Internet Explorer"))&&(navigator.vendor!="Google Inc.")&&(navigator.vendor!="Apple Computer, Inc.")){
		DEFirstTime = false;
		forceInfoObj = infoObj;
		initDEFailed = true;
		debug ("initDEFailed = true");
	} else {
		initDEFailed =false;
		swf.initDE(infoObj);		
	}
	//"disable" is called from within the SWF by getURL.
}

function forceInitDE(){
		debug ("forceInitDE, document.getElementById('downloadElement').initDE="+document.getElementById("downloadElement").initDE+" initDEFailed = "+initDEFailed);
	if (initDEFailed){
		if (document.getElementById("downloadElement").initDE == undefined){
			hideDE();
			return;
		}
		document.getElementById("downloadElement").initDE(forceInfoObj);
	}
}

function hideDE(){
	document.getElementById("downloadElement").className = "f-hide";
	document.getElementById("DEContainer").className = "f-hide";
	if (currPopup == hideDE){
	//remove trans blocker:
	enable();
	currPopup = null;	
	}
	attPopupOpen--;
	
	if (openDEInRow.openAnother){
		openDEInRow.openAnother = false;
		var rowItemInfo = {fileName:"frontPageContentToolbar.swf",X:311/*632*/,Y:105};
		for (var i in openDEInRow.itemInfo){
			rowItemInfo[i] = openDEInRow.itemInfo[i]
		}
		showDownloadElement(rowItemInfo);
		return;
	}
}

function setDEInRow(nextDEInfo){
	openDEInRow.openAnother = true;
	openDEInRow.itemInfo = nextDEInfo.itemInfo;
	//alert (nextDEInfo.itemInfo["itemID"]);
}

function disable(disableType){
	if (attPopupOpen<2){
		switch (disableType){
			case "trans":
				document.getElementById("blocker").className = "cover";
				document.getElementById("blocker").style.backgroundColor = skinColor;
				document.getElementById("blockerContainer").className = "transDisabler";
				document.getElementById("blockerContainer").style.top=-10;
				document.getElementById("blockerContainer").style.height = overallHeight+10;
				fadeBlockerIn();
				//alert ("done");
			break;
			default: break;
		}
	}
}

function enable(){
	if (attPopupOpen<2){
		/*var swf = document.getElementById("blocker");
		swf.fadeBlockerOutAndAbout();*/
		fadeBlockerOut();
		hideBlocker(); //was noted out but returned
		document.getElementById("popups").className = "f-hide";
	}
}

function hideBlocker(){
debug ("hide blocker")
	document.getElementById("blockerContainer").className = "hiddenForm";
	
}

function tagSelected(tagValue,TBID){
	//jumpToToolbar(TBID); --removed in light of no-toolbars
	putSearchStringInTB(tagValue,0/*TBNumByTBID(TBID)*/); //--now 0 because no toolbars
}

function jumpToToolbar(TBID){
	var TBNum = TBNumByTBID(TBID)
	maximizeToolbar(TBNum);
	document.getElementById("toolbars").focus();
}

function TBNumByTBID(TBID){
	var TBhash = {w:0,c:1,r:2,s:3}
	var TBNum = null;
	if (!isNaN (Number(TBID))){
		TBNum = Number(TBID);
	} else{
		TBNum = TBhash[TBID];	
	}
	return TBNum;
}

function maximizeToolbar(TBNum){
	var evtObj = new Object();
	evtObj.num = TBNum;
	document.getElementById("toolbars").maximizeToolbar(evtObj);
}

function filterByUser(userID){
	swfobject.getObjectById("toolbars").filterByUser(userID);
}

function filterByString(str,toolbarID){
	swfobject.getObjectById("toolbars").filterByString(str,toolbarID);
}

function putSearchStringInTB(str,TBNum){
	swfobject.getObjectById("toolbars").putSearchStringInToolbar(str,TBNum);
}

function performLogin(evtObj){
	/*document.getElementById("navbar_username").value = evtObj.userName;
	document.getElementById("navbar_password").value = evtObj.password;
	document.getElementById("cb_cookieuser_navbar").checked = evtObj.remember;*/
	document.getElementById("nm").value = evtObj.userName;
	document.getElementById("pwd").value = evtObj.password;
	//document.getElementById("mem").value = evtObj.remember;
	document.loginForm.mem.value = evtObj.remember;
	//document.getElementById("mem").value = 1; //STUB! problem with API call!
	debug ("perform login()");	
	//document.getElementById("loginForm").submit();
	document.loginForm.submit();
	debug ("performed login");		
		
}

function switchAction(){
	if (actionVar!=null){		
		switch(actionVar){
			case "login":	 popOnStart = "login";
			break;
			case "help" : showHelp();
			break;
			case "adult": showAdult();
			break;
			case "invite": showInvite();
			break;
			case "oi": 
			if (DEloaded){
				//if DE is already loaded before action was found, open the DE.
				openThumbByItemId(pageParams["id"]);
			} else {
				//if DE is not loaded yet, set the flag to true so on load of the DE it will open.
				openDEOnStart = true;
			}
			//openThumbByItemId(pageParams["id"]);
			break;
			default:break;
		}
	}
}

function checkPopOnStart(){
	switch (popOnStart){
		case "login": showLoginNoClose();
		break;
		default:break;
	}
}

function placeFooter(){
	document.getElementById("footer").style.top = overallHeight;
	document.getElementById("footer").style.color = "#ffffff";
}