//- Define prefix for cookie used for window collapsing (it is defined here but used in other files!)
var windowStatePrefix = "PowerSoccer_";
var game = "soccer";

function onBlur() {
	var flashObject = getFlashById("levelsystem");
	if (flashObject && flashObject.setBrowserWindowActive != undefined) {
		flashObject.setBrowserWindowActive(false);
	}
}
function onFocus(){
	var flashObject = getFlashById("levelsystem");
	if (flashObject && flashObject.setBrowserWindowActive != undefined) {
		flashObject.setBrowserWindowActive(true);
	}
}

if (navigator.appName == "Microsoft Internet Explorer") {
	document.onfocusin = onFocus;
	document.onfocusout = onBlur;
} else {
	document.onfocus = onFocus;
	document.onblur = onBlur;
}

function addBuddy(userId, returnSuccessAsResponse) {
	if (userId == self.addBuddyInProgressUserId) {
		return;
	}
	
	self.addBuddyInProgressUserId = userId;
	ajaxCall("com/authenticated/ajax/com.php", "val=addBuddy&id=" + userId+"&return_success=" + (returnSuccessAsResponse ? "true" : "false") , "ajax_addBuddyResponse", "");
}

function removeBuddy(userId) {
	ajaxCall("com/authenticated/ajax/com.php", "val=removeBuddy&id=" + userId , "", "");
}

function ajax_addBuddyResponse(readyState, response, responseParameter) {
	if (readyState == 4) {
		self.addBuddyInProgressUserId = 0;
		// we got a message, display it
		if (response != "") {
			alert(response);	
		}
	}
}

function joinCup(cupId) {
	var matchmakingFlashObject = document.matchmaking;
	// if the have the gamerooms flash available, we can probably join a cup without redirecting, we just need to update the session first via an ajax call
	if (matchmakingFlashObject && matchmakingFlashObject.joinCup != undefined) {
		ajaxCall("com/authenticated/ajax/com.php", "val=setIsInCup&cup_id=" + cupId, "ajax_setIsInCupResponse", "");
	}
	else {
		location.href = "?p=arena&cid=" + cupId;
	}
}

function openPlayerInventory(playerId, teamId) {
	var base = 'flash/';
	var showContentOnly = true;
	var bgcolor = '#7a7a7a';
	
	var flashvars = "";
	if (typeof(flashVarsAppearance) != "undefined") {
		flashvars += flashVarsAppearance;
	}

	playerId ? flashvars += "&pid=" + playerId : '';
	teamId ? flashvars += "&tid=" + teamId : '';
	var filename = 'flash/player_inventory.swf?cacheControl=14';
	var name = "PlayerInventory";
	var width = 976;
	var height = 496;
	
	var content = '<div id="player_inventory_content" style="width: ' + width + 'px; height: ' + height + 'px;"></div>';

	openLightBox(width, '', content, '', '', '', '', '', 'flashbox_', 'flashbox_lightboxCloseButton', showContentOnly);
	swfobject.embedSWF(filename, "player_inventory_content", width, height, "9.0.0", false, false, {wmode: "opaque", base: "flash/", bgcolor: bgcolor, AllowScriptAccess: "sameDomain", flashvars: flashvars}, {id: name});
}

function playerInventoryConfirmPlayerChangeCosts(nameChanged, nicknameChanged) {
	var productNames = [];
	if (nameChanged) {
		productNames.push("change_player_name");
	}
	if (nicknameChanged) {
		productNames.push("change_player_nickname");
	}
	
	openConfirmProductsLightbox(productNames, "playerInventoryConfirmPlayerChangeCostsResponse", "just_save_other_changes");
}

function playerInventoryConfirmPlayerChangeCostsResponse(productsToBuy) {
	var nameConfirmed = false;
	var nickConfirmed = false;
	
	if (productsToBuy) {
		for (var n=0;n<productsToBuy.length;n++) {
			if (productsToBuy[n] == "change_player_name") {
				nameConfirmed = true;
			}
			else if (productsToBuy[n] == "change_player_nickname") {
				nickConfirmed = true;
			}
		}
	}
	
	if (getFlashById("PlayerInventory")) {
		if (getFlashById("PlayerInventory").savePlayerAfterConfirm) {
			getFlashById("PlayerInventory").savePlayerAfterConfirm(nameConfirmed, nickConfirmed);
		}
		else {
			alert("Error: PlayerInventory.savePlayerAfterConfirm not found");
		}
	}
	else {
		alert("Error: PlayerInventory not found");
	}
	
}

// called when closing the player inventory
function closeShopLightbox(selectedPlayerId){
	// kludge: closing the shop lightbox directly causes Firefox 2 to crash. Having a timeout solves the problem
	setTimeout("_doCloseShopLightbox("+selectedPlayerId+")", 10);
}

function _doCloseShopLightbox(selectedPlayerId){
	lightboxHide();
	com.powerchallenge.kpi.sendAndFlush();
	if (getFlashById("team_page_player_viewer")) {
		getFlashById("team_page_player_viewer").refresh(selectedPlayerId);
	}
}

function ajax_setIsInCupResponse(readyState, response, responseParameter) {
	if (readyState == 4) {
		var matchmakingFlashObject = document.matchmaking;
		var cupId = parseInt(response);
		
		if (cupId != NaN && cupId > 0) {
			// if the gamerooms flash is available we join without redirect 
			if (matchmakingFlashObject && matchmakingFlashObject.joinCup != undefined) {
				matchmakingFlashObject.joinCup(cupId);
			}
			else {
				location.href = "?p=arena&cid=" + cupId;
			}
		}
		else {
			alert("Failed to join cup. Please try again later.");
		}
	}
}

function showChallengeSettingsMenu() {
  ajaxCall('com/authenticated/ajax/com.php', 'val=loadChallengeSettingsItems', 'ajax_openSettingsMenu', '');
}

function acceptClanInvitation(cid) {
		ajaxCall('com/authenticated/ajax/com.php', 'val=acceptClanInvitation&cid=' + cid, 'ajax_redirectClanPage', cid);
}


function ajax_redirectClanPage(readyState, response, responseParameter) {
	if (readyState == 1) {
		showGeneralMouseMenu(new Array(), "", true);
	}
	else if (readyState == 4) {
			window.location='?p=clan&id=' + responseParameter;
	}
}


function showLeagueGroupForTeam(teamId) {
  ajaxCall('com/authenticated/ajax/com.php', 'val=getLeagueGroupData&tid='+teamId, 'showLeagueGroupForTeamResponse', '');
}


function showLeagueGroupForTeamResponse(readyState, response, responseParameter) {
  if (readyState == 4) {
    eval(response);
    //alert(response);
  }
}


function toggleGuestbookMessage(layer, linkIndicator, shortMessage, longMessage) {
  var nextLinkImg       = "";
  var nextLinkIndicator = "";
  var thisMessage       = "";

  // Replace to make js-safe
  shortMessage = shortMessage.replace('"', '');
  longMessage  = longMessage.replace(/"/g, '&#34;'); // "

  if (linkIndicator == "+") {
    nextLinkIndicator = "-";
    nextLinkImg       = "/img/button_minimize.gif";
    thisMessage       = longMessage;
  }
  else {
    nextLinkIndicator = "+";
    nextLinkImg       = "/img/button_maximize.gif";
    thisMessage       = shortMessage;
  }

  var linkVar = "<img src=\""+nextLinkImg+"\" onclick=\"toggleGuestbookMessage('"+layer+"', '"+nextLinkIndicator+"', '"+shortMessage+"', '"+longMessage+"');\" style=\"cursor: pointer;\">";
  
  layer_write(layer, linkVar + "&nbsp;&nbsp;"+thisMessage);
}


function showCMFaq() {
	openLightBox(860, 'key:cm_benefits_title', '<span id=\'cm_faq_layer\'><table border=0 cellspacing=0 cellpadding=0 width=560 height=400><tr><td valign=\'top\'>$waiting</td></tr></table></span>');
  ajaxCall('com/authenticated/ajax/com.php', 'val=getCMInfo', 'writeLayer', 'cm_faq_layer');
}


function showLeagueFaq() {
	$.weeboxs.open('ajax.php?p=league_faq', {contentType: 'ajax', title: 'key:league_faq_title', width:860});
}


function showVideo(videoURL, width, height, title, thumbImageURL, autostart) {
	var fileName = "widgets/video/video_player.swf";
	var bgColor = "#ffffff";
	var base = "/";
	var flashvars = "nosplash=true&nologo=true&fullscreen_enabled=true&videoURL="+videoURL;
	height += 32; // add height for the playback controls

	if (title == undefined) {
		title = "";
	}
	
	if (thumbImageURL != undefined && thumbImageURL != "") {
		flashvars += "&thumbURL=" + thumbImageURL; 
	}
	
	if (autostart) {
		flashvars += "&autostart=true";
	}
	
	var content = '<div style="width: ' + width + 'px; height: ' + height + 'px;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="" align="middle">'
			+ '	<param name="allowScriptAccess" value="sameDomain" />'
			+ '	<param name="allowFullScreen" value="true" />'
			+ '	<param name="movie" value="' + fileName + '" />'
			+ '	<param name="quality" value="high" />'
			+ '	<param name="wmode" value="opaque" />'
			+ '	<param name="bgcolor" value="' + bgColor + '" />'
			+ '	<param name="base" value="' + base + '" />'
			+ '	<param name="flashvars" value="' + flashvars + '" />'
			+ '	<embed src="' + fileName + '" wmode="opaque" flashvars="' + flashvars + '" base="' + base + '" quality="high" bgcolor="' + bgColor + '" width="' + width + '" height="' + height + '" name="" align="middle" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
			+ '</object></div>';

	openLightBox(width, title, content, '', '', '', '', '', '', '', false);
	
}

// ugly temp. solution in order to be able to trigger showVideo from a news item.
function showHeadersVideo() {
	showVideo("/img/news_content_images/headers_intro.flv", 480, 360,"/img/news_content_images/headers_thumb.jpg");
}


function sendClanInvitation(uid) {
	var layer   = "content_clan_invitation";
	var content = "<div style=\"text-align: center; padding-bottom: 20px;\"><img src=\"common/img/icons/ajax_loader.gif\" width=\"16\" height=\"16\"></div>";

	openLightBox(400, 'key:invite_to_clan_title', '<div id="'+layer+'">'+content+'</div>', '', 0);
	ajaxCall("com/authenticated/ajax/com.php", "val=sendClanInvitation&uid="+uid, "writeLayerInLightbox", layer);
}


function kickClanMember(uid) {
	var layer   = "content_kick_clan_member";
	var content = "<div style=\"text-align: center; padding-bottom: 20px;\"><img src=\"common/img/icons/ajax_loader.gif\" width=\"16\" height=\"16\"></div>";
	
	openLightBox(400, 'key:kick_clan_member_title', '<div id="'+layer+'">'+content+'</div>', '', 0);
	ajaxCall("com/authenticated/ajax/com.php", "val=kickClanMember&uid="+uid, "writeLayerInLightbox", layer);
}


function updateTeamName() {
	ajaxCall('com/authenticated/ajax/com.php', 'val=updateTeamName', '', '');
}


function clientErr(el, str) {
	if (str != '') {
		var padding = 6;
		var leftPadding = 38;
		var html = '<div style="width: '+ ($(el).width() - leftPadding - padding) +'px !important" class="client_error_message"></div>';
		$(el).html(html);
		$(".client_error_message").text(str);
		$(".client_error_message").show("fast");
		$(".client_error_message").oneTime(2000, function() {
			$(".client_error_message").hide("fast", function() {
				$(".client_error_message").remove();
			});
		});
	}
}


function careerMatchEnded(data) {
	if ($.weeboxs.getBoxById("missionInProgress")) {
		$.weeboxs.getBoxById("missionInProgress").close();
	}
	$.weeboxs.open("ajax.php?p=careerintegration&sub=getLatestResult&data=" + data, {boxid: 'careerResult', contentType:'ajax'});
	if (typeof(reloadCurrentMap) != "undefined") {
		reloadCurrentMap(true);
	}
}

$(function() {
	$(".button").live("mouseover", 
		function(){
			var cssParams = {backgroundPosition: 'bottom left'};
			$(this).css(cssParams).find(".button_middle, .button_expand").css(cssParams);
			$(this).find(".button_right").css({backgroundPosition: 'bottom right'});
		}
	);
	$(".button").live("mouseout", 
		function(){
			var cssParams = {backgroundPosition: 'top left'};
			$(this).css(cssParams).find(".button_middle, .button_expand").css(cssParams);
			$(this).find(".button_right").css({backgroundPosition: 'top right'});
		}
	);
});

function openQuickMatchSubMenu(){
	var container = document.getElementById('quick_match_button_container');
	if (container) {
		var tableRows = container.getElementsByTagName('tr');
		
		for(var i=0; i<tableRows.length; i++){
			if(tableRows[i].className == "quick_match_subs"){
				if(tableRows[i].style.display == "none"){
					tableRows[i].style.display = "";
				}
				else{
					tableRows[i].style.display = "none";	
				}
			}	
		}
	}
}

function displayFbSelectFriends(readyState, response, responseParameter) {
	if( readyState == 4 )
	{
		var invite_div = document.getElementById("facebook_invite_friends"); 
		invite_div.innerHTML = response;
		FB.XFBML.Host.parseDomElement(invite_div);
	}
}

function facebook_ajaxcall(){
	$.weeboxs.open('<div id="facebook_invite_friends" style="width: 100%; min-height: 410; text-align: center; vertical-align: middle"><img src="common/img/icons/ajax_loader.gif" style="width: 16px; height:16px;"></div>', {width:600, boxid: 'facebook_invite'});
	ajaxCall("com/authenticated/ajax/facebook.php", "val=getFBInviteFriends", "displayFbSelectFriends", "facebook_invite_friends");
}

function displayNewsArchive(page) {
	$.weeboxs.open("ajax.php?p=news_archive&page="+page, {boxid: 'newsArchive', contentType:'ajax', width:'700px'});
}

function getSharingChoice(params) {
	params = params.split(",");
	var method = params[0];
	var methodIdentifier = params[1];
	var sharingUrl = "ajax.php?p=gigyaMethods&method=" + method + "&identifier=" + methodIdentifier + "&choice=true";
	$.weeboxs.open(sharingUrl, {contentType:'ajax', boxid:'sharingChoice_' + method});
}