/**
 * @file: core::main.js.part
 * @version: 2.1
 * @since: 2011-10-06
 */

/**
 * DEFINE GLOBAL VARS
 */
var observeContainerValues = new Array();
var afterDOMParams = new Array();
var forcedHitPageType = false;
var currentPageType = null;
var currentPageParams = {};

/**
 * Function to getElementById
 *
 * @param String eId
 * @type: JS:default
 */
function eId(eId){
	e = document.getElementById(eId);
	if (e){
		return e;
	}else{
		return false;
	}
}

/**
 * function to toggle a Object 'display' status
 * default: none|block
 *
 * @param: objectId
 * @param: defaultValue
 * @type: JS:default
 */
function toggleDiv(divId,defaultValue){
	if (!defaultValue){
		defaultValue = "block";
	}

	e = document.getElementById(divId);
	if (e){
		if (e.style.display == "none"){
			e.style.display = defaultValue;
		}else{
			e.style.display = "none";
		}
	}
}

/**
 * clears a field and focus'es
 * @type: JS:default
 */
function clearField(field){
	field.value = "";
	field.focus();
}

/**
 * checks current search field value, and submits' it
 *
 * @type: JS:jQuery
 */
function checkSearchField(){
	searchField = $("#search_field");

	if (searchField.val().length < 3){
		searchField.fadeOut(250);
		searchField.css("background-color","#f00");
		searchField.fadeIn(250);
		searchField.focus();
	}else if(searchField.val() == findGameString){
		searchField.css("background-color","#f00");
		searchField.fadeOut(250);
		searchField.fadeIn(250);
		searchField.val("");
		searchField.focus();
	}else{
		document.location.href = searchLocation+"/"+searchField.val().replace(/ /g,"_");
	}
}

/**
 * toggles a backgroundImage
 * used for startconfigs
 *
 * @type: JS:default
 */
function toggleBackground(elementObj,imageScr){
	if(imageScr == 'null'){
		elementObj.style.backgroundImage = "none";
	}
	else{
		elementObj.style.backgroundImage = "url("+imageScr+")";
	}
}

/**
 * get absolute position x from left
 * @type: JS:default
 */
function getElementX(el){
	if (typeof(el) != "object"){
		el = eId(el);
	}

	x = el.offsetLeft;
	if (!el.offsetParent) return x;
	else return (x+getElementX(el.offsetParent));
}

/**
 * get absolute position y from top
 * @type: JS:default
 */
function getElementY(el) {
	if (typeof(el) != "object"){
		el = eId(el);
	}

	y = el.offsetTop;
	if (!el.offsetParent) return y;
	else return (y+getElementY(el.offsetParent));
}

function openWindow(url,windowDim){
	(!windowDim)?windowDim={width: 550, height: 400}:null;
	dimX = (window.innerWidth/2)-(windowDim["width"]/2);
	dimY = 200;

	fbT = "window"+Math.floor(Math.random()*1001);
	fbw = window.open(url,fbT, 'dependent=yes,menubar=no,location=no,resizable=no,scrollbars=no,status=no,toolbar=no,width='+windowDim["width"]+',height='+windowDim["height"]+',left='+dimX+',top='+dimY);
	fbw.id = fbT;
	fbw.opener = self;
}

/**
 * observe container and handle action
 * @type: JS:default
 * @param: array observeContainerValues
 */
function app_observeContainer(advContainerId,observeName,observeFunction,forceFunction,recFlag){
	observeContainerObj = eId(advContainerId);
	if (!observeContainerObj){
		return false;
	}
	if(!forceFunction){
		forceFunction = "false";
	}else{
		forceFunction = "true";
	}
	forceAvailable = false;

	if (typeof(observeContainerValues[advContainerId]) == 'undefined'){
		observeContainerValues[advContainerId] = new Array();
		forceAvailable = true;
	}
	if (typeof(observeContainerValues[advContainerId][observeName]) == 'undefined'){
		observeContainerValues[advContainerId][observeName] = eval("observeContainerObj."+observeName+"");
		forceAvailable = true;
	}

	if (observeContainerValues[advContainerId][observeName] != eval("observeContainerObj."+observeName+"") || (forceFunction == "true" && forceAvailable)){
		observedValueOld = observeContainerValues[advContainerId][observeName];
		observedValue = eval("observeContainerObj."+observeName+"");
		eval(observeFunction);
	}
	observeContainerValues[advContainerId][observeName] = eval("observeContainerObj."+observeName+"");

	if (!recFlag){
		window.setInterval("app_observeContainer(\""+advContainerId+"\",\""+observeName+"\",\""+observeFunction+"\","+forceFunction+",true);", 200);
	}
}

/**
 * observe containers and handle action
 * @type: JS:default
 */
function app_observeContainers(advContainerId,secondAdvContainerId,observeName,observeFunction,recFlag){
	observeContainerObj = eId(advContainerId);
	secondAdvContainerObj = eId(secondAdvContainerId);
	if ((!observeContainerObj) || (!secondAdvContainerObj)){
		return false;
	}
	if (typeof(observeContainerValues[advContainerId]) == 'undefined'){
		observeContainerValues[advContainerId] = new Array();
	}
	if (typeof(observeContainerValues[advContainerId][observeName]) == 'undefined'){
		observeContainerValues[advContainerId][observeName] = eval("secondAdvContainerObj."+observeName+"");
	}

	if (observeContainerValues[advContainerId][observeName] != eval("observeContainerObj."+observeName+"")){
		eval(observeFunction);
	}
	observeContainerValues[advContainerId][observeName] = eval("secondAdvContainerObj."+observeName+"");

	if (!recFlag){
		window.setInterval("app_observeContainer(\""+advContainerId+"\",\""+observeName+"\",\""+observeFunction+"\",true);", 200);
	}
}

/**
 * opens a popup game
 * @type: JS:default
 * @status: toDo
 */
function openPopupGame(gameHash){
	alert("game is not available!\n"+gameHash);
}

/**
 * handle a Webservice Action
 * @type: JS:jQuery
 */
function doWebserviceAction(serviceName){
	$.ajax({
		url: "/webservice/serviceAction/"+serviceName,
		async: false
	});
}

/**
 * Refresh header (login<->logout header)
 *
 * @type: JS:jQuery
 */
function doRefreshHeader(){
	$('#head_dynamic_container').html($.ajax({
		url: "/account/remote_refresh_header",
		async: false
	}).responseText);
}

/**
 * Refresh profile (profile section)
 *
 * @type: JS:jQuery
 */
function doRefreshProfile(){
	$('#head_dynamic_container').html($.ajax({
		url: "/account/remote_refresh_header",
		async: false
	}).responseText);
}

/**
 * handle a remote Action
 * @type: JS:jQuery
 */
function remoteRequest(containerId,destUrl){
	$('#'+containerId).html($.ajax({
		url: destUrl,
		async: false
	}).responseText);
}

/**
 * show or hide waitContainer
 *
 * @type: JS:jQuery
 */
function toggleWaitContainer(containerStatus,handleOtherArea){
	(!handleOtherArea)?handleOtherArea=false:null;

	if (containerStatus){
		/* special options for IE-Browser */
		if (($.browser.msie && $.browser.version > 8) || (!$.browser.msie)){
			$("#fullcontent_container").css("opacity",0.2);
		}
		/* show the 'none-clickable-container' */
		$("#outer_window").css("height",$("#fullcontent_container").height());
		$("#outer_window").show();
		/* show the wait-container */
		$("#wait_window").show();
		$("#wait_window").centerInClient({forceWindowHeight:true, forceWindowWidth:true});

		/* hide all 'flash' or none overlay objects */
		handleHideArea(false);
	}else{
		/* hide the wait-container */
		$("#wait_window").hide();

		if (handleOtherArea){
			/* special options for IE-Browser */
			if (($.browser.msie && $.browser.version > 8) || (!$.browser.msie)){
				$("#fullcontent_container").animate({opacity : 1},300);
			}

			$("#outer_window").hide();
			handleHideArea(true);
		}
	}
}

/**
 * toggles a window container (remote - auto)
 * @type: JS:jQuery
 */
function toggleWindowContainer(containerId,containerStatus,containerOptions){
	/* show or hide this container */
	(!containerStatus)?containerStatus=false:null;
	(!containerOptions)?containerOptions={showWait: false, displayTime: null}:null;

	/* choose one of existing containers, if id is undefined */
	if (!containerId){
		tmpId = $("div[id^=window_]").last().attr("id");
		/* no windows available, close it */
		if (!tmpId){
			toggleWaitContainer(false,true);
			return false;
		}
		idtoken = tmpId.split("_");
		containerId = idtoken[1];
	}

	/* show or hide wait container */
	toggleWaitContainer(containerOptions["showWait"],false);

	/* show this container */
	if (containerStatus){
		/* show the 'none-clickable-container' */
		$("#outer_window").css("height",$("#fullcontent_container").height());
		$("#outer_window").show();

		defaultContainerZIndex = 151;
		maxZIndex = defaultContainerZIndex;
		$("div[id^=window_]").each(function(){
			if ($(this).css("z-index") > maxZIndex){
				maxZIndex = $(this).css("z-index");
			}
		});
		$("#window_"+containerId).css("z-index",maxZIndex-1);

		/* special options for IE-Browser */
		if (($.browser.msie && $.browser.version > 8) || (!$.browser.msie)){
			$("#fullcontent_container").css("opacity",0.2);
		}

		$("#window_"+containerId).fadeIn(500);
		$("#window_"+containerId).centerInClient({forceWindowHeight:true, forceWindowWidth:true});
		handleHideArea(false);

		/* hide this container, after x seconds */
		if (containerOptions["displayTime"] > 0){
			setTimeout("toggleWindowContainer('"+containerId+"',false)",(containerOptions["displayTime"]*1000));
		}
	/* hide this container */
	}else{
		$("#window_"+containerId).fadeOut(0,function(){
			/* remove this container (DOM cleanup) */
			$(this).remove();
			cSize = $("div[id^=window_]").size();
			if (cSize == 0 && (!containerOptions["showWait"])){
				$("#fullcontent_container").animate({opacity : 1},300);
				$("#outer_window").hide();
				handleHideArea(true);
			}
		});
	}
}

/**
 * handle a request as window layout
 * @type: JS:jQuery
 */
function remoteWindowRequest(destUrl,wParams,showWait){
	(!wParams)?wParams={}:null;
	(!showWait)?showWait=false:null;
	wParams["layout"] = "window";

	if (showWait){
		toggleWaitContainer(true,false);
	}

	$('#dynamic_container').append($.ajax({
		url: destUrl,
		data: wParams,
		async: false
	}).responseText);
}

/**
 * shows a ajax flash message with KEY,TYPE
 * @type: JS:jQuery
 */
function remoteFlash(messageKey,messageType){
	(!messageType)?messageType="success":null;
	destUrl = "/static/remote_flash";
	$('#dynamic_container').append($.ajax({
		url: destUrl,
		data: {key: messageKey, type: messageType},
		async: false
	}).responseText);
}

/**
 * shows a ajax flash message
 * @type: JS:jQuery
 */
function remoteFlashMessage(messageMsg,messageOptions){
	(!messageOptions)?messageOptions={messageType: "success"}:null;
	messageOptions["message"] = messageMsg;

	destUrl = "/static/remote_flash";
	$('#dynamic_container').append($.ajax({
		url: destUrl,
		data: messageOptions,
		async: false
	}).responseText);
}

/**
 * submits the current_form data
 * @type: JS:jQuery
 */
function submitAjaxFormData(targetUrl,formName){
	if (formName == null){
		formName = "current_form";
	}

	formValues = {};
	s = $('#'+formName).serializeArray();
	jQuery.each(s,function(){
		formValues[this.name]=this.value;
	});

	$.ajax({
		url: targetUrl,
		data: formValues,
		async: false,
		type: "POST"
	});
	return true;
}

/**
 * submits the current_form data and refreshs an container with it's return value
 * @type: JS:jQuery
 */
function submitAjaxUpdateFormData(updateId,targetUrl,formName){
	if (formName == null){
		formName = "current_form";
	}

	formValues = {};
	s = $('#'+formName).serializeArray();
	jQuery.each(s,function(){
		formValues[this.name]=this.value;
	});

	$('#'+updateId).html($.ajax({
		url: targetUrl,
		data: formValues,
		async: false,
		type: "POST"
	}).responseText);

	return false;
}

/**
 * submits the current_form data and loads a new window container
 * @type: JS:jQuery
 */
function submitAjaxWindowFormData(cWindowId,targetUrl,showWait,formName){
	(!formName)?formName="current_form":null;
	(!showWait)?showWait=false:null;

	formValues = {};
	s = $('#'+formName).serializeArray();
	jQuery.each(s,function(){
		formValues[this.name]=this.value;
	});

	formValues["layout"] = "window";
	toggleWindowContainer(cWindowId,false,{showWait: showWait, displayTime: null});

	$('#dynamic_container').append($.ajax({
		url: targetUrl,
		data: formValues,
		async: false,
		type: "POST"
	}).responseText);

	return false;
}

/**
 * toggle tab boxes and load content, if required
 * @type: JS:jQuery
 */
function toggleTabBox(tabboxArea,tabboxNb,contentUrl){
	(!contentUrl) ? contentUrl=false : null;
	$("#tabarea_"+tabboxArea).find(".tabBox").each(function(cTp,currentBox){
		if (cTp == tabboxNb){
			$(this).show();
			/* getContent for Tabbox */
			if (contentUrl && $(this).attr("vstatus") == null){
				$(this).children(".loadingImg").css("margin-top",(($(this).parent().attr("offsetHeight")/2)-16));
				$(this).load(contentUrl);
				$(this).attr("vstatus","1");
			}
		}else{
			$(this).hide();
		}
	});
	$("#tabarea_"+tabboxArea).find(".tabBoxLink").each(function(cTp,currentBox){
		if (cTp == tabboxNb){
			$(this).addClass("tabBoxLinkActive");
		}else{
			$(this).removeClass("tabBoxLinkActive");
		}
	});
}

/**
 * get modified pixelDifferences for other browsers
 * @type: JS:jQuery
 * @status: overwrite by other browsers
 */
function lccPD(pageType,currentPD){
	return currentPD;
}

/**
 * loads params/functions after dom-finished
 * @type: JS:jQuery
 * @param: array afterDOMParams
 * @require: $(document).ready fnc
 */
function afterDOMLoad(functionParams,loadNow){
	(!loadNow) ? loadNow=false : null;
	afterDOMParams[afterDOMParams.length] = functionParams;
	if (loadNow){
		eval(functionParams);
	}
}

/**
 * level all container to the same height-level-position
 * @type: JS:jQuery
 * @require: JS:jQuery:equalHeightElements.fnc
 */
function levelContainer(levelContainers,forceLevelContainer,pixelDifference){
	$(levelContainers).equalHeightElements({
		forceContainer: forceLevelContainer,
		pixelDifference: pixelDifference
	});
	return true;
}

/**
 * fadeIn function for 'blinking' effect
 * @type: JS:jQuery
 */
function doFadeInBlink(classname, speed) {
	$("."+classname).fadeTo(speed,1.00);
	window.setTimeout("doFadeOutBlink('"+ classname + "', " + speed + ")", speed);
}

/**
 * fadeOut function for 'blinking' effect
 * @type: JS:jQuery
 */
function doFadeOutBlink(classname, speed) {
	$("."+classname).fadeTo(speed,0.01);
	window.setTimeout("doFadeInBlink('" + classname + "', " + speed + ")", speed);
}

/**
 * used for navigation-toggle
 * @type: JS:default
 */
function toggleNavigation(naviObject, naviStatus){
	if(naviStatus){
		naviObject.className = "hover";
	}
	else{
		naviObject.className = "";
	}
}

/**
 * used to show/hide all 'none-overlay-containers' like "flash"
 * @type: JS:jQuery
 */
function handleHideArea(showGame){
	if (showGame){
		$('.iframetoggle').css('visibility','visible');
		$('#flash_game_0').css('visibility','visible');
		$('#flash_game_1').css('visibility','visible');
	}else{
		$('.iframetoggle').css('visibility','hidden');
		$('#flash_game_0').css('visibility','hidden');
		$('#flash_game_1').css('visibility','hidden');
	}
}

/**
 * used to check, if currentUser is logged in
 * @type: JS:jQuery
 */
var relLiFnc = null;
function handleloggedIn(afterLoggedAction){
	resLi = $.ajax({
		url: "/static/remote_logged_in/",
		async: false
	}).responseText;
	if ((!resLi) || resLi == 0){
		relLiFnc = afterLoggedAction;
		remoteWindowRequest('/account/remote_lg_rg/empty');
	}else{
		eval(afterLoggedAction);
	}
}

function relLoggedIn(){
	if (relLiFnc == null){
		return true;
	}
	eval(relLiFnc);
	relLiFnc = null;
}

/**
 * used to track an event on the current page
 * @type: JS:googleAnalytics
 */
function gaTrackEvent(eventClass,eventName,eventLabel){
	(!eventName) ? eventName=false : null;
	(!eventLabel) ? eventLabel=false : null;

	if (typeof(_gaq) == 'undefined'){
		return false;
	}
	if (typeof(_gaq.push) != 'function'){
		return false;
	}

	if (eventName && eventLabel){
		_gaq.push(["_trackEvent",eventClass, eventName, eventLabel]);
	}else if (eventName){
		_gaq.push(["_trackEvent",eventClass, eventName]);
	}else{
		_gaq.push(["_trackEvent",eventClass]);
	}
}

/**
 * checks if maximum allowed characters are reached and cuts the content if it is too long
 * @param object fieldObj - object to check
 * @param int maxLength - maximum characters
 * @param String fieldIndicatiorId optional - Field where remaining characters are displayed
 * @type: JS:jQuery
 */
function checkFieldCharacterLength(fieldObj,maxLength,fieldIndicatiorId){
	if (!fieldObj){
		return false;
	}

	if (fieldObj.value.length > maxLength){
		fieldObj.value = fieldObj.value.substr(0,maxLength);
	}
	indRestChars = maxLength-fieldObj.value.length;

	if (fieldIndicatiorId != null){
		$("#"+fieldIndicatiorId).html(indRestChars);
	}
}

/**
 * loads params/functions after dom-finished
 * @type: JS:jQuery
 * @require: array afterDOMParams
 */
$(document).ready(function() {
	$.each(afterDOMParams,function(i,v){
		eval(v);
	});
	/* always force blink, for class .blinkingObject */
	doFadeOutBlink("blinkingObject", 500);
	/* always force shadow on NavigationElements - IE fix */
	$(".shadowNavigation").textShadow({x:1,y:1,radius:15,color: "#5F2F0E"});
});


/**
 * @file: portal::core::main.js.part
 * @version: 2.0
 * @since: 2011-06-07
 */

/**
 * toggle hits container with a toggle Button
 * @type: JS:jQuery
 * @require: forcedHitPageType
 */
function toggleHitControl(pageType){
	(!pageType) ? pageType=false : null;
	
	switch(pageType){
		case "newest":
		case "bestrated":
		case "top":
			toggleVisButton = $("#category_toggle_inactive");
			toggleInvisButton = $("#category_toggle_active");
		break;
		case "home":
		case "home_middle":
		case "home_small":
		case "home_big":
			toggleVisButton = $("#start_home_toggle_inactive");
			toggleInvisButton = $("#start_home_toggle_active");
		break;
		case "category":
		case "search":
			toggleVisButton = $("#category_toggle_inactive");
			toggleInvisButton = $("#category_toggle_active");
		break;
		case "download":
			toggleVisButton = $("#downloadToggleInactive");
			toggleInvisButton = $("#downloadToggleActive");
		break;
		default:
			toggleVisButton = $("#toggle_inactive");
			toggleInvisButton = $("#toggle_active");
		break;
	}
	if (toggleVisButton.is(':visible')){
		toggleVisButton.hide();
		toggleInvisButton.show();
		showStatus = true;
	}else{
		toggleVisButton.show();
		toggleInvisButton.hide();
		showStatus = false;
	}
	toggleHitContainer(showStatus);
	
	if (forcedHitPageType != false){
		pageType = forcedHitPageType
	}
	levelContainerControl(pageType);
}

/**
 * force levelContainer (pageType) after toggleHits
 * @type: JS:default
 */
function forceHitControlLevel(fpt){
	forcedHitPageType = fpt;
	return true;
}

/**
 * level container on sites
 * @type: JS:jQuery
 */
function levelContainerControl(pageType,forcedPixelDifference){
	/* importend, do not remove!!! */
	window.setTimeout("app_reposAllAdvertisingContainers();",5);
	
	(!pageType) ? pageType=false : null;
	(!forcedPixelDifference) ? forcedPixelDifference=false : null;
	levelContainers = "";
	forceContainer = "";
	pixelDifference = 0;

	switch(pageType){
		case "newest":
		case "bestrated":
		case "top":
			levelContainers = "#category__big_game_container_body, #start__right__small_game_container_body";
			forceContainer = "category__big_game_container_body";
			pixelDifference = -10;
		break;
		case "category":
		case "download":
		case "search":
			pixelDifference = 12;
			levelContainers = "#category__big_game_container_body, #category__small_game_container_body";
			forceContainer = "category__big_game_container_body";
			
			if (app_isAdvertisingAvailable("app_advertising_square")){
				pixelDifference -= $("#square_outer_container").height();
			}
		break;
		case "game":
			pixelDifference = -1;
			levelContainers = "#game_dimension_container, #game__small_game_container_body, #right_toggle_container_hs, #right_toggle_container";
			forceContainer = "game_dimension_container";
			
			/* special height for hs+cp container */
			if ($("#right_toggle_container_hs").length > 0 || $("#right_toggle_container").length > 0){
				pixelDifference = 0;
			}
			
			if (app_isAdvertisingAvailable("app_advertising_square")){
				pixelDifference -= $("#square_outer_container").height();
			}
		break;
		case "game_fixed":
			levelContainers = "#game_overlay_container, #right_toggle_container";
			forceContainer = "game_overlay_container";
		break;
		case "gamebottom":
			levelContainers = "#game_gameinfo_container, #game_instruction_container, #app_advertising_rectangle_ph, #game_other_container";
		break;
		case "home_full":
			levelContainers = "#start__big_outer_container_left, #small_container_body";
			forceContainer = "start__big_outer_container_left";
		break;
		case "home_middle":
			levelContainers = "#tip_container_body, #big_container_body";
			forceContainer = "big_container_body";
			pixelDifference = 0;
			levelContainer(levelContainers,forceContainer,pixelDifference);
		
			pixelDifference = -32;
			levelContainers = "#start__big_container_left, #small_container_body";
			forceContainer = "start__big_container_left";
			
		break;
		case "home":
		case "home_big":
		default:
			pixelDifference = -32;
			levelContainers = "#start_left_container_area, #small_container_body, #tip_container_body";
			forceContainer = "start_left_container_area";
		break;
	}
	/* overwrite current pixelDifference for other Browsers */
	pixelDifference = lccPD(pageType,pixelDifference);
	
	if (forcedPixelDifference){
		pixelDifference = forcedPixelDifference;
	}
	
	levelContainer(levelContainers,forceContainer,pixelDifference);
}

/**
 * toggle the hits container classes
 * @type: JS:jQuery
 */
function toggleHitContainer(showStatus){
	(!showStatus) ? showStatus=false : null;
	$(".gamestat_toggle").each(function(){
		if (showStatus){
			$(this).show();
		}else{
			$(this).hide();
		}
	});
}

/**
 * replace url string of browser
 * @type: JS:default
 */
function replaceUrlString(url){
	if ('replaceState' in history) {
    	history.replaceState(null, document.title, url);
	}
}



