var _Application = function() {this._constructor();};

_Application.prototype = {
	authKey: '#@&$!@#&(',
	debug: true,
	wpajaxurl: '',
	
	_constructor: function() { // Constructor for the application object
		if($("#tabs").size()>0) {
			$("#tabs").tabs();
		}
		if($(".fctable").size()>0) {
			$(".fctable").tablesorter({widgets: ['zebra']});
		}
		if($("#mainframe").size()>0) {
			$("#mainframe").fadeIn();
		}
		if(typeof FCTmatchentre == 'object') { 		
			FCTmatchentre.functions.moveWPcontent();
		}
	},
	boot: function(wpajaxurl) { // Application startup
		this.wpajaxurl = wpajaxurl;
		_.console.info('Bootup');
	}
};

(function() {_Core.prototype.extend(new _Application());})();

var FCTmatchdata = {};

FCTmatchdata.functions = {
		
	wpajaxurl: null,
	selector: '#season_dd',
	serverurl: null,
	shortcachedir: '/infostrada/live_output/',
	longcachedir: '/infostrada/longcache/',
	langAttr: null,
	debug: true,
	
	init: function(wpajaxurl, serverurl, langAttr) {
		this.wpajaxurl = wpajaxurl;
		this.serverurl = serverurl;
		this.langAttr = langAttr;
		this.seasonInit();
		
		if($(this.selector).size()>0) {
			if ("onhashchange" in window) {
				$(window).bind('hashchange', function(e) {
					FCTmatchdata.functions.seasonInit();
				});
				$(this.selector).bind('change', FCTmatchdata.functions.setHash);
			} else {
				$(this.selector).bind('change', FCTmatchdata.functions.selectChangeOldBrowser);
			}
		}
	},
	
	selectChangeOldBrowser: function() {
		FCTmatchdata.functions.setHash();
		FCTmatchdata.functions.loadFromLongCache();
	},
		
	seasonInit: function() {
		hashJSON = this.bookmarkToJson();
		if(hashJSON['seizoen']) {
			$('#rankings').hide();
			$('#program').hide();
			$('#scorers').hide();
			var seasonID = null;
			$(FCTmatchdata.functions.selector + " option").each(function() { 
				if($(this).text() == hashJSON['seizoen']) {
					seasonID = $(this).attr('value');
				}
			});
			$(FCTmatchdata.functions.selector).val(seasonID);
			FCTmatchdata.functions.loadFromLongCache();
		} else {
			if($('#rankings').size()>0) {
				this.rankingTables();
			}			
		}		
	},
		
	bookmarkToJson: function(){ 
		/* Determines the hash values and extracts the correct vars  to a JSON */
		if(document.location.hash){
			var sHash = document.location.hash.substring(1);
			var aItems = sHash.split('&');
			var oDataJSON = {};
			for(var i=0; i< aItems.length;i++) {
				aItem = aItems[i].split('=');
				sKey = aItem[0];
				sValue = aItem[1];
				oDataJSON[sKey] = sValue;
			}
			return oDataJSON;						
		} else{
			this.trace('Initial state empty');
			return {};
		}
	},	
	
	rankingTables: function() {
		$('tr.fct').each(function() {
			var parentTableID = $(this).parent().parent().attr('id');
			$('#' + parentTableID).show();
			var parentGroupID = parentTableID.replace("_table_", "_group_");
			$('h3#' + parentGroupID).show();
			FCTmatchdata.functions.trace(parentTableID);
		});
		$('#rankings').show();
		$('.fctable').tablesorter({widgets: ['zebra']});
	},
	
	setHash: function() {
		var newHash = '#seizoen=' + $(FCTmatchdata.functions.selector + ' option:selected').text();
		if(document.location.hash != newHash) {
			document.location.hash = newHash;
		}
	},
		
	loadFromLongCache: function() {
		var selectedID = $(FCTmatchdata.functions.selector + ' option:selected').val();
		var type = $(FCTmatchdata.functions.selector).attr('class');
		var cacheurl = FCTmatchdata.functions.serverurl + FCTmatchdata.functions.longcachedir + type + '-' + selectedID + '-' + FCTmatchdata.functions.langAttr + '.xml';
		FCTmatchdata.functions.showLoader();
		jQuery.ajax({
			  url: cacheurl,
		      global: false,
		      dataType: "xml",
		      async: false,
		      success: function(msg){
				FCTmatchdata.functions.processServerResponse(msg);
		      },
		      error:function (xhr, ajaxOptions, thrownError){
		    	  if( (xhr.status!='304') && (xhr.status!=304)  ) {
		    		  FCTmatchdata.functions.loadFromShortCache();
		    	  }
              }
		});			
	},	
	
	loadFromShortCache: function() {
		var selectedID = $(FCTmatchdata.functions.selector + ' option:selected').val();
		var type = $(FCTmatchdata.functions.selector).attr('class');
		var cacheurl = FCTmatchdata.functions.serverurl + FCTmatchdata.functions.shortcachedir + type + '-' + selectedID + '-' + FCTmatchdata.functions.langAttr + '.xml';
		FCTmatchdata.functions.showLoader();
		jQuery.ajax({
			  url: cacheurl,
		      global: false,
		      dataType: "xml",
		      async: false,
		      success: function(msg){
				FCTmatchdata.functions.processServerResponse(msg);
		      },
		      error:function (xhr, ajaxOptions, thrownError){
		    	  if( (xhr.status!='304') && (xhr.status!=304)  ) {
		    		  FCTmatchdata.functions.ajaxLoad({action:'loadSeasonDataAjax', seasonID: selectedID, infoType:type});
		    	  }
              }
		});			
	},		
	
	ajaxLoad: function ( pData ) {
		FCTmatchdata.functions.showLoader();
		var type = $(FCTmatchdata.functions.selector).attr('class');
		jQuery('#' + type).hide();
		jQuery.ajax({
			  url: FCTmatchdata.functions.wpajaxurl,
		      global: false,
		      type: "POST",
		      data: pData,
		      dataType: "xml",
		      async: false,
		      success: function(msg){
				FCTmatchdata.functions.processServerResponse(msg);
		      }
		});		
	},	
	
	showLoader: function () {
		$("#loader").show();
	},
	
	hideLoader: function () {
		$("#loader").hide();
	},	
	
	processServerResponse : function (xml){    
		
		try {
			eval(jQuery(xml).find("execute").text());
		} catch(err) {
			FCTmatchdata.functions.processError(err,'js-execute'); 
		}
		
		FCTmatchdata.functions.processData(jQuery(xml).find("data"));
				
		try{
			eval(jQuery(xml).find("execute-after").text());
		} catch(err){ 
			FCTmatchdata.functions.processError(err,'js-execute-after');
		}
		
		FCTmatchdata.functions.hideLoader();

	},	
	
	processData: function (xml){
		/* Parse data blocks and insert them in the subsequent ID's */
		jQuery("content",xml).each (function(i){
			if(document.getElementById(jQuery(this).attr("for"))){
				switch (jQuery(this).attr("method")){
					case 'prepend':
						jQuery('#'+jQuery(this).attr("for")).prepend (jQuery(this).text());
					break;				
					case 'append':
						jQuery('#'+jQuery(this).attr("for")).append (jQuery(this).text());
					break;				
					case 'replace':
						jQuery('#'+jQuery(this).attr("for")).html (jQuery(this).text());
					break;
					default:
						jQuery('#'+jQuery(this).attr("for")).html (jQuery(this).text());
					break;
				}
			} else {
				FCTmatchdata.functions.processError("Server trying to write to DIV that does not exist: ", 'div: '+jQuery(this).attr("for") + " could not be found in the DOM");
			}
		});
	},	
	
	processError : function(err,type){
		if(FCTmatchdata.functions.debug && typeof console =='object'){
			console.warn ("ERROR OCCURED ("+type+"):");
			if(typeof err == 'object'){
				console.dir(err);
			}else{
				console.warn("Message: "+ err + " in "+type);
			}
		}
	},	
		
	trace: function (trace){
		if(FCTmatchdata.functions.debug) {
			if(typeof console =='object') {
				if(typeof trace =='string' || typeof console.dir !='function'){
					console.info("Trace: "+trace);
				}else{
					console.dir(trace);
				}
			}
		}
	}
	
};

var FCTmenu = {};

FCTmenu.functions = {

	debug: true,
	hideSpeed: 5000,
	forcedSubmenu: null,
	animationSpeed: 1000,
	
	init: function () {
		//$("#menu-headernavigation").find("li.level_0").bind('mouseover', FCTmenu.functions.mainMenuOver);
		//$("#menu-headernavigation").find("li.level_0").bind('mouseout', FCTmenu.functions.mainMenuOut);	
		/*
		$(".sub-menu").hover(
				function () {
					$(this).addClass("hover");
				},
				function () {
					$(this).removeClass("hover");
				}
		);
		*/		
		//this.enableCurrentSubmenu();
		$("#tabnav ul li a").each( FCTmenu.functions.addTab );
		
		//$("#tabnav ul li a").bind('mouseover', FCTmenu.functions.tabMenuOver);
		//$("#tabnav ul li a").bind('mouseout', FCTmenu.functions.tabMenuOut);
		
		this.lowlevelmenu();
	},
	
	lowlevelmenu: function() {
		if($('#level3menu').size()>0) {
			var index=0
			$('#level3menu li').each(function() {
				index++;
				if(index%2==0) {
					$(this).addClass('even');
				} else {
					$(this).addClass('odd');
				}
			});
		}
	},
	addTab: function () {
		
		var href = $(this).attr('href');
		var title = $(this).attr('title');
		var style = $(this).attr('class');
		var target = $(this).attr('target');
		if(target==undefined) {
			target = '';
		} else {
			target = 'target="'+target+'"';
		}
		
		var html_append = '<div class="over"><p>'+title+'</p><a href="'+href+'" class="'+style+'" title="'+title+'" alt="'+title+'" '+target+' /></div>';
				
		$(this).append(html_append);
			
		var newwidth = $(this).find('.over p').width() + 75;
		
		$(this).find('.over').attr('style', 'width:'+newwidth+'px; display:none; visibility:visible;');
		
		$(this).hover(
				function(event){
					$(this).find('.over').show();
				},
				function(event){
					$(this).find('.over').hide();
				}
			);
		
	},
		
	mainMenuOver: function() {

		/* hide all submenus */
		$(".sub-menu").hide();

		/* show current submenu */
		$(this).find('.sub-menu').show();

	},
	
	mainMenuOut: function() {

		var menuID = $(this).attr("id");
			
		var current_page_id = $('.current_page_item').attr("id");
			
		if(current_page_id!=menuID) {
			/* Set timer to hide this submenu */
			setTimeout("FCTmenu.functions.hideSubMenu('"+menuID+"')",FCTmenu.functions.hideSpeed);	
		}
	},	
	
	hideSubMenu: function( pID ) {
		
		var target = $('#' + pID ).find('.sub-menu');

		if( $(target).is(':visible') ) {
			if($(target).hasClass('hover')) {
				setTimeout("FCTmenu.functions.hideSubMenu('"+pID+"')",FCTmenu.functions.hideSpeed);
			} else {
				$(target).fadeOut(1000, function() {
					/* show the submenu of the current_page_parent or current_page (if any) */
					FCTmenu.functions.enableCurrentSubmenu();
				});
			}
		} else {
			
		}
		
	},	
	
	enableCurrentSubmenu: function() {
		/* enable current page submenu (if a currentpage is in the tree */
		var current = $("#menu-headernavigation").find(".current_page_item").attr("id");
		
		if( $("#menu-headernavigation").find(".current_page_item").hasClass('level_1') ) {
			current = $("#menu-headernavigation").find(".current_page_ancestor").attr("id");
		}
		
		if(current) {
			$("#" + current).find('.sub-menu').show();
		} else if(FCTmenu.functions.forcedSubmenu) {
			$("#" + FCTmenu.functions.forcedSubmenu).find('.sub-menu').show();
		}
		
	}

};
