$(document).ready(function(){
    /**
     * Default settings
     */
    $.ajaxSetup({
        url:        "do_some_ajax",
        dataType:   "json",
        async:		"true",
        global:     false/*,
        complete:	function(XMLHttpRequest, textStatus){
        	alert(XMLHttpRequest)
        }
        ,
        error: function(XMLHttpRequest, textStatus, errorThrown){
        	alert(textStatus + ' - ' + errorThrown)
        }*/
    });
    
    $().ajaxStart(function(){
        $("#ajax_indicator").show();
        $("#game_screen").css('cursor', 'url(img/cursor.png), wait');
    });
    $().ajaxStop(function(){
        $("#ajax_indicator").hide();
        $("#game_screen").css('cursor', 'url(img/cursor.png), default');
    });
    
    
    /**
     * Call standard events
     */
    if ($("body").attr("id") != "room_building_iframe") {
    	requestDefaultData();
    }
    handleEvents();
    createDefaultEvents()
    $(".movie_box").fixedTooltip();

	// Chat message is sent
	$("form#chat_input").submit(function() {
		$.ajax({
			data: "todo=insertChatMessage&chatMessage=" + encodeURIComponent($("input[name=chat_message]").val()),
			global: true,
			type: "POST"
		});
		$("input[name=chat_message]").val("");
		$("input[name=chat_message]").focus();
		return false;
	});
	
	// Game channel message is sent
	$("form#game_channel").submit(function() {
		$.ajax({
			data: "todo=insertGameChannelMessage&message=" + encodeURIComponent($("input[name=game_channel_message]").val()),
			global: true,
			type: "POST"
		});
		$("input[name=game_channel_message]").val("");
		$("input[name=game_channel_message]").focus();
		return false;
	});
	
	// Handle small hints
    setTimeout(function(){$(".small_hint.visible").toggle("slow")}, 500);
    // Closing of small hints
    $(".small_hint_close_layer").click(function(){
		$(this).parent().addClass("closed");
		$(this).parent().toggle("slow");
		return false;
	});
    // Self-closing / self-showing of hints
	cObjArray = new Array();
	$("#small_hints .toggle").each(function (i) {
		cObjArray[i] = $(this);
		cObjArray["time" + i] = $(this).attr("rel");
		setTimeout(
			function(){
				cObjArray[i].toggle("slow");
			},
			cObjArray["time" + i] * 1000
		);
	});
	
	/* balance screen */
    $(".balance .bottom").click(function() {
    	$("#balance_today").toggle();
        $("#balance_yesterday").toggle();
    });
    
    /* show money details */
    $("#console_users_budget").hover(function() {
        $(this).next("#money_details").madtvShow();
    },function() {
    	$(this).next("#money_details").madtvHide();
    });
    
	/* show watchers details */
	$("#console_info").hover(function() {
		$(this).next("#console_info_details").madtvShow();
	},function() {
		$(this).next("#console_info_details").madtvHide();
	});
    
    /* show day details */
	$("#console_day").hover(function() {
		$(this).next("#console_day_details").madtvShow();
	},function() {
		$(this).next("#console_day_details").madtvHide();
	});
	
	/* end day hint */
    $("#console_end_day").hover(function() {
        $(this).next("#console_end_day_hint").madtvShow();
    },function() {
    	$(this).next("#console_end_day_hint").madtvHide();
    });
	/* confirm end day */
	$("#console_end_day").click(function() {
		if ($("body").attr("id") != "screen_television_program") {
			$.ajax({
				data: "todo=consoleEndDay&filename=" + $("body").attr("id"),
				global: true,
				success: function(data){
					$("#content_screen").prepend(data.confirm_msg);
					$("#confirm_end_day").madtvShow();
				}
			});
			return false;
		}
	});
	$("#confirm_end_day .confirm_yes").live("click", function() {
		window.location.href = $("base").attr("href") + "screen_television_program?action=end_day";
    });
    $("#confirm_end_day .confirm_no").live("click", function() {
		$("#confirm_end_day").madtvRemove();
    });
	
    /**
     * Actions for right click
     */
	$("#game_screen").bind('contextmenu', function(e) {
        // close message window
        /* TODO: not possible, perhaps with live query... if ($('#error_report').children().css("display") == "block") {
        	$('#error_report').children().hide();*/
        // deselect ad / movie
        if (typeof(movieId) != 'undefined' && movieId != '' && typeof(movieTitle) != 'undefined' && movieTitle != '') {
            movieToTrash();
        } else if (typeof(adId) != 'undefined' && adId != '' && typeof(adTitle) != 'undefined' && adTitle != '') {
            adToTrash();
        // television program
        } else if ($("#category_select").css("display") == "block") {
        	$("#category_select").hide();
        	$(".movie_select").hide();
        } else if ($("#ad_select").css("display") == "block") {
        	$("#ad_select").hide();
        // close balance screen
        } else if ($("#balance_today").css("display") == "block") {
            $("#balance_today").hide();
        } else if ($("#balance_yesterday").css("display") == "block") {
            $("#balance_yesterday").hide();
        // movie agency: close special movies
        } else if ($("#special_movies").css("display") == "block") {
            $("#special_movies").hide();
            $("#small_hints").fadeIn();
        // news room: close news window
        } else if ($("#news_select").css("display") == "block") {
            $("#news_select").hide();
        // supermarcet
        } else if ($("#film_needs").css("display") == "block" || $("#gifts").css("display") == "block") {
            supermarketResetAll();
        // room agent
        } else if ($("#room_agent_map_rooms").css("display") == "block") {
            $("#room_agent_map_rooms").fadeOut();
        // movie auction
        } else if ($(".multiplayer_auction_movie.active").css("display") == "block") {
            $(".multiplayer_auction_movie").madtvHide();
        // leave room
        } else if (typeof(js_href) != 'undefined' && js_href != '') {
            if (js_href.indexOf("jsVars") != -1) {
                jsVars = giveIds();
                js_href = js_href.replace(/jsVars/, jsVars);
            }
            window.location.href = js_href;
        }
        $("#madtvTooltip").hide();
		return false;
	});
	
	// right_block Tabs darstellen / Einstellungen speichern
	$(".change-visibility").click(function(){
		cObj = $(this);
		$.ajax({
			data: "todo=changeVisibility&changeElement=" + $(this).children("img").attr("rel") + "&filename=" + $("body").attr("id"),
			success: function(data){
				cObj.parents(".box").children('.box-content').slideUp().remove();
				if (data.response) {
					cObj.parents(".box").append(data.response);
				}
				cObj.children("img").attr("src", "img/" + data.switchSrc);
				if (cObj.children("img").attr("rel") == 'chat') {
					$("#chat_content").html(
						htmlChatMessages(data.chat_global)
					);
				}
			}
		});
	});
	// display messages
	setTimeout(function(){$(".error_report").madtvShow({fade: true})}, 500);
	
	// in game message system
	$("#dont_show_this_message_again").click(function(){
		$(this).parents(".error_report").madtvHide({fade: true});
		$.ajax({
			data: "todo=dontShowThisMessageAgain&filename=" + $("body").attr("id")
		});
		return false;
	});
});

/**
 * This function resets all the default events
 */
function handleEvents(){
	// jTip
	$("span.jTip").unbind("mouseenter");
	$("span.jTip").unbind("mouseleave");
	$("span.jTip").bind("mouseenter", function(){
		JT_init(this);
	});
	$("span.jTip").bind("mouseleave", function(){
		JT_hide();
	});
}

/**
 * Diese Funktion wird beim Seitenaufruf und nach jedem Ajax-Aufruf aufgerufen
 */
function createDefaultEvents() {
    $(".close").click(function() {
    	/* close error report */
        $(this).parent(".error_report").madtvHide({fade: true});
        /* close balance screen */
        $("#balance_today").hide();
        $("#balance_yesterday").hide();
    });
}

function requestDefaultData(){
	params = new Object();
	params['todo'] = 'all';
	params['filename'] = $("body").attr("id");
	if (typeof(globalChatLatestIdGlobal) != 'undefined') {
		params['chat_latest_id_global'] = globalChatLatestIdGlobal;
	}
	if (typeof(globalChatLatestIdMpGame) != 'undefined') {
		params['chat_latest_id_mp_game'] = globalChatLatestIdMpGame;
	}
	$.ajax({
		data: params,
		ifModified: true,
		success: function(data){
			htmlGeneral(data);
			// chat messages
			if (data.chat_global) {
				$("#chat_content .loader").hide();
				$("#chat_content").prepend(
					htmlChatMessages(data.chat_global)
				);
			}
			if (data.chat_latest_id_global) {
				globalChatLatestIdGlobal = data.chat_latest_id_global;
			}
			// game channel messages
			if (data.chat_mp_game) {
				$("#multiplayer_game_channel_content .loader").hide();
				$("#multiplayer_game_channel_content").prepend(
					htmlChatMessages(data.chat_mp_game)
				);
			}
			if (data.chat_latest_id_mp_game) {
				globalChatLatestIdMpGame = data.chat_latest_id_mp_game;
			}
			// output games of the user
			if (data.multiplayer_games) {
				$("#multiplayer_user_games_content").html(
					htmlMultiplayerGames(data.multiplayer_games)
				);
			}
			// actual multiplayer game: info
			if (data.multiplayer_game_info) {
				$("#multiplayer_game_info_content").empty();
				if (data.multiplayer_game_info['remaining_time']) {
					$("#multiplayer_game_info_content").append(
						data.multiplayer_game_info['remaining_time_text'] + ': <span id="countdown"></span>'
					);
					prepareCountdown(data.multiplayer_game_info['remaining_time'], '#countdown');
					prepareCountdown(data.multiplayer_game_info['remaining_time'], 'title');
				}
				$("#multiplayer_game_info_content").append(
					data.multiplayer_game_info['participants_info']
				);
			}
			// countdown ad delay
			if (data.last_ad_taken > 0) {
	           	prepareCountdown(data.last_ad_taken, '#ad_agency_countdown');
	        }
	        
	        // start countdown
			if (globalVarCountdowns.length) {
				doCount();
				timeout = window.setInterval("doCount()", 1000);
			}
		},
		complete: function(){
			// set periodical updater
			setTimeout("requestDefaultData()", 10000);
		}
	});
}


//var aktiv = window.setInterval("Farbe()", 1000);
var i = 0, farbe = 1;
function Farbe () {
  if (farbe == 1) {
    alert("yellow");
    farbe = 2;
  } else {
    alert("aqua");
    farbe = 1;
  }
  i = i + 1;
  if (i >= 10)
    window.clearInterval(aktiv);
}

/**
 * Countdown of seconds
 */
globalVarCountdowns = new Array();
$(document).ready(function(){
	browserTitle = $("title").text();
});
function prepareCountdown(time, element) {
	// stop all existing countdowns
	if (typeof(timeout) != "undefined") {
		clearInterval(timeout);
	}
	key = globalVarCountdowns.length;
	globalVarCountdowns[key] = Array();
	globalVarCountdowns[key][0] = time;
	globalVarCountdowns[key][1] = element;
}

function doCount() {
	$.each(globalVarCountdowns, function(i, countdown) {
		var s = countdown[0];
		var h = Math.floor(s / 3600);
		var m = Math.floor((s - (h * 3600)) / 60);
		s = (s - (h * 3600)) % 60;
		output = (h > 0 ? h + ":" : "") + (m > 0 ? (m < 10 && h > 0 ? "0" + m : m) + ":" : "0:") + (s < 10 ? "0" + s : s);
		
		if (countdown[0] > 0 && countdown[1] != "title") {
			if (countdown[0] < 60) {
				$(countdown[1]).addClass('important');
			}
			$(countdown[1]).html(output);
			countdown[0]--;
		} else if (countdown[0] > 0 && countdown[1] == "title") {
			// when IE, do not continue
			if (document.all) return; // TODO: Enable for IE (bug in IE6..8?)
			$(countdown[1]).text("[" + output + "] " + browserTitle);
			countdown[0]--;
		} else {
			if (countdown[1] == "title") {
				$(countdown[1]).text("[0:00] " + browserTitle);
			} else {
				$(countdown[1]).text('-');
			}
			if (countdown[1] == "#ad_agency_countdown") {
	           	$("#ad_agency_hint").remove();
				// Countdown aus Array entfernen
				globalVarCountdowns[i] = new Array();
	        }
		}
	});
}


/**
 * Handles visualisation of new budget
 * Displays messages
 * Makes redirect
 * 
 * @param data: response as json
 */
function htmlGeneral(data) {
    /* redirect */
    if (data.redirect) {
    	window.location.href = data.redirect;
    } else {
    	// count of queries
    	if (typeof(data.ajaxCountQueries) != "undefined") {
    		$("#ajaxCountQueries").append(' ...' + data.ajaxCountQueries);
    	}
    	// memory usage
    	if (typeof(data.ajaxMemoryUsage) != "undefined") {
    		$("#ajaxMemoryUsage").append(' ...' + data.ajaxMemoryUsage);
    	}
	    /* budget */
	    if (typeof(data.budget) != "undefined") {
	        updateBudget(data.budget);
	    }
	    /* error message */
	    if (data.messages) {
		    $.each(data.messages, function(i, message) {
		        $("#error_report").append(
		            "<div id='error_report_" + message.id + "' class='error_report'>" +
		            "<div class='message in_game_msg'>" + message.msg + "</div>" +
		            "<img class='close' alt='X' title='" + message.close + "' src='img/close.gif' />" + 
		            "</div>"
		        );
		    	$("#error_report_" + message.id).madtvShow({fade: true});
		    });
		}
		/* small hints */
	    if (data.hints) {
		    $.each(data.hints, function(i, hint) {
		        $("#small_hints").append(hint);
		    	$(".small_hint").fadeIn();
		    });
		}
		/* users in this room */
		if (data.users_in_this_room) {
			$("#users-in-room:not(.closed)").fadeIn();
			$("#users-in-room #users-in-room-names").html(data.users_in_this_room);
		}
    	createDefaultEvents();
    }
}

/**
 * Produce HTML code for JSON response
 */
function htmlChatMessages(chat_messages){
    retVal = '';
	firstClass = 'even';
	secondClass = 'odd';
	// latest message is even => start with odd
    if ($('#chat_content p:first').attr('class') == 'even') {
		firstClass = 'odd';
		secondClass = 'even';
    }
    $.each(chat_messages, function(i, item) {
        retVal += '<p class="' + (i%2 ? secondClass : firstClass) + '">' + 
        '<span class="name">' + item.name + '</span>' + 
        '<span class="date">' + item.date + '</span>' + 
        '<span class="message">' + item.message + '</span>' + 
        '</p>';
    });
    return retVal;
}

/**
 * Produce HTML code for JSON response
 */
function htmlMultiplayerGames(multiplayer_games) {
    retVal = "";
    $.each(multiplayer_games, function(i, item) {
        retVal += "<p>" + item.game + " - " + item.participants + "</p>";
    });
    return retVal;
}

/**
 * Update budget in console,
 * Update budget and credit in budget details
 */
function updateBudget(budget, credit){
    if (typeof(budget) != "undefined") {
        $("#console_users_budget").text(Math.floor(budget/1000));
        $("#money_details_budget").text(budget);
    }
    if (typeof(credit) != "undefined") {
        $("#money_details_credit").text(credit);
    }
}

/**
 * hint with confirmation, that user wants to leave game really
 */
function confirmLeaveGame() {
	$.ajax({
		data: "todo=confirmLeaveGame",
		success: function(data){
			if (data.confirm_box) {
				$("#game_screen").append(data.confirm_box);
				$("#confirm").madtvShow();
			} else {
				window.location.href = data.redirect;
			}
			
			$("#game_screen .confirm_no").click(function(){
				$("#confirm").madtvHide();
			});
			
			$("#game_screen .confirm_yes").click(function(){
				window.location.href = data.redirect;
			});
		}
	});
}