// JS settings
$.cookie.options = { expires:90, path:'/' };
Date.format = 'yyyy-mm-dd';
Date.today = (new Date()).asString();


// All AJAX links
$(".logo a, ul.leauges li a, .live_score .lg a, .team a, .home_team a, .away_team a, .live_score .h2h a, .vpl a, .league .team a, .active_table_tab a, ul.small_menu li a").live('click', function(e) {	
	if (e.button == 1 || e.button == 0) {
	    if (!e.ctrlKey && !e.shiftKey) {
			var url = $(this).get().toString();
			if (url) Request.load(url);
			return false;
		}
	}
});
//

// Ready
$(document).ready(function(){
	Request.start();
	Toolbar.ready();
	Request.ready();
	if (!Request.isFeeds) {
		MainDbTree.load();		
	}
	Latest.ready();
});	
//


/*
 * Class Toolbar Request
 *
 * Load data into #content div and makes appropriate changes in page layout
 */
var Request = {

	construct: function() {
		this.isAjax		= false;
		this.isFeeds	= /\/feed\/\d+\/\d+\//.test(document.location.href);
		this.url		= this.internalURL(document.location.href);
		this.page		= false;
		this.controller	= null;
		this.date		= Date.today;
		this.group		= 'time';
	},

	start: function() {
		if (!this.isAjax)
			Request.cookiesStart();

		this.date	= $.cookie('fixtures_date');
		this.group	= $.cookie('fixtures_group');

		// current page
		if (this.url == '/' || this.url == '/league/') {
			this.page		= 'current';
			this.controller	= LiveScore;
			this.setDate (Date.today);
			this.setGroup(this.url == '/' ? 'time' : 'league');
	    } else if (matches = this.url.match(/^(\/league)?\/(\d{4}-\d{2}-\d{2})\//)) {
			this.page		= 'fixtures';
			this.controller	= LiveScore;
			this.setDate (matches[2]);
			this.setGroup(matches[1] ? 'league' : 'time');
		} else if (/^\/[A-Z][a-zA-Z_]*\//) {
			this.page		= 'fixtures';
			this.controller	= LiveScore;
			this.setGroup('league');
		} else if (/^\/[A-Z][a-zA-Z_]*\/[a-zA-Z0-9_]*\/[A-Z][a-zA-Z_]*-[a-zA-Z0-9_]*-vs-[A-Z][a-zA-Z_]*-[a-zA-Z0-9_]*\//.test(this.url)) {
	    		this.page		= 'h2h';
			this.controller	= H2h;
		} else if (/^\/[A-Z][a-zA-Z_]*\/Teams\/[a-zA-Z0-9_]*\//.test(this.url)) {
	    		this.page		= 'team'; 
			this.controller	= Team;
		} else if (/^\/[A-Z][a-zA-Z_]*\/[a-zA-Z0-9_]*\//.test(this.url)) {
	    		this.page		= 'league';
			this.controller	= LeagueTable;
		} else {
	    		this.page = false;
		}
	},

	ready: function() {
    	if (this.isAjax)
    		this.start();

    	if (this.controller)
    		this.controller.ready();
		
		if (this.isAjax) {
			this.loadEnd();
			Adverts.ready();
		}
	},
	
	load: function(url, show_loader, no_cache) {
		show_loader = show_loader != null ? show_loader : true;
	    if (show_loader)
			this.loadStart();
	    
	    this.url = this.internalURL(url);
	    if (Request.isFeeds) {	    	
	    	document.location.href = '/feed/'+css_id+'/'+timezone+this.url;
	    } else {	
			this.isAjax = true;
		    $.cookie('content_url', this.url);
	    	this.loadAjax($("#content"), this.url, function() { Request.ready(); }, (Request.isFeeds ? '/feeds/'+css_id+'/'+timezone+'' : ''), no_cache);
	    }	
	},
	loadDiv: function(container, url, callback, no_cache) {
	    this.loadAjax(container, this.internalURL(url), callback, '', no_cache);
	},
	loadAjax: function(container, url, callback, prefix, no_cache) {
		prefix = '/ajax' + prefix;		
		no_cache = no_cache != null ? no_cache : false;
		suffix = no_cache ? this.noCacheQueryString() : '';
		container.load(prefix + url + suffix, null, callback);
	},

	reload: function() {
		this.load(this.url);
	},
	reloadLayout: function() {
		document.location = this.url;
	},

	internalURL: function(url) {
	    if (Request.isFeeds){
	    	url = url.replace('/feed/'+css_id+'/'+timezone, '');	    	
	    }	    
	    // TODO: optimize using regexp
	    var base = document.location.href.replace(document.location.pathname,'').replace('http:/','http://').replace('http:///','http://');
	    url = url.replace(base, '/').replace(/\/\//,'/');	    		
	    //
	    return url;
	},
	noCacheQueryString: function(query_string) {
		return '?' + Math.round(Math.random()*10000);
	},

	loadStart: function() {
		$("#loader").show();			
	},
	loadEnd: function() {
		$("#loader").hide();
	},
	
	setDate:	function(val) { $.cookie('fixtures_date',	this.date	= val) },
	setGroup:	function(val) { $.cookie('fixtures_group',	this.group	= val) },

	cookiesStart: function() {		
        if(!$.cookie('timezone_city')) {
        	$.cookie('timezone', Request.isFeeds ? timezone : '0');
        	$.cookie('timezone_city', 'London [GMT]');
			$.cookie('fixtures_date', Date.today);
			$.cookie('fixtures_filter', 'all');
			$.cookie('fixtures_group', 'time');
			$.cookie('fixtures_goals', '');
        	$.cookie('sound_enabled', 'mute');
        	$.cookie('sound_type', 'bell');
        }
        if(!$.cookie('fixtures_selected')) {
            var sopt = { expires:3, path:'/' };  
		    $.cookie('fixtures_selected', 'off', sopt);
			$.cookie('fixtures_selected_ids', '', sopt);
        }
        if(!$.cookie('layout_url')) {
            var urlopt = { path:'/' }; // expires on browser close
			var url = Request.internalURL(document.location.href);
			$.cookie('layout_url',  url, urlopt);
			$.cookie('content_url', url, urlopt);
        }
        
	}
}
Request.construct();
// Class Request END


/*
 * Class Toolbar
 */
var Toolbar = {

	panel_fixtures_filter: function(type, reload) {
		type   = type ? type : 'all';
		reload = reload != null ? reload : true;		
		
		$(".clockbar .bottombar div").css({display:'none'});
    	$("#"+type+"_games_hint")    .css({display:'block'});  
    	
   		$.cookie('fixtures_filter', type);
		if (reload) {
		    if (Request.page == 'current') {
			    LiveScore.filterTable(true);		    
		    } else {
			    LiveScore.load('current');
			}
		} 
	}, 
	panel_fixtures_group: function (type, reload) {
		type   = type ? type : 'time';
		reload = reload != null ? reload : true;
		
		$(".sortbar .bottombar div").css({display:'none'});
    	$("#sort_by_"+type+"_hint") .css({display:'block'});
   		
   		Request.setGroup(type);
		if (reload) {
		    LiveScore.load();
		}
	},
	panel_fixtures_selected: function (is_select, reload) {
		reload = reload != null ? reload : true;

		if (is_select == 'on') 
			$("#select").removeClass("off").addClass("on");
		else
			$("#select").removeClass("on").addClass("off");

		$.cookie("fixtures_selected", is_select);
		if (reload) {
			LiveScore.filterTable(true);
		}
	},
	
	panel_fixture_sound: function(type, element_id){			
		var sound = $.cookie('sound_enabled');
		if (type == null) {
			if (sound == 'mute') {
				$("#sound").removeClass("sound_on");
				element_id = 'sound';
			} else {
				$("#sound").addClass("sound_on");
				element_id = $.cookie("sound_type");
			}
		} else if (type == 'on-off') {
			if (sound == 'mute') {
				sound = 'on';
				$("#sound").addClass("sound_on");
				element_id = $.cookie('sound_type');
			} else {
				sound = 'mute';
				$("#sound").removeClass("sound_on");
				element_id = 'sound';
			}						
		} else if (type == 'sound_type') {
			sound = 'on';
			$("#sound").addClass("sound_on");						
			$.cookie('sound_type', element_id);
		}
		
		$(".soundbar .bottombar div").hide();
		$("#"+element_id+"_hint").show();	
		$.cookie('sound_enabled', sound);
	},

	// Calendar 
	calendarUpdate: function() {
		var date = Date.fromString(Request.date);
		
	    var str = date.getDayName(true)+', '+date.getDate()+' '+date.getMonthName()+' '+date.getFullYear();
	    $('#calendar').html(str);

		$('.calendar_img').dpSetSelected(Request.date,true,true,false);
	},
	calendarReady: function() {
		$('.calendar_img')
			.datePicker({createButton:false,startDate:'2000-01-01',endDate:(new Date()).addYears(1).asString(),horizontalPosition:$.dpConst.POS_RIGHT,verticalOffset:28 })
			.bind(
				'click',
				function() {
					$(this).dpDisplay();
					this.blur();
					return false;
				}
			)
			.bind(
				'dateSelected',
				function(e, selectedDate, $td, status) {
					LiveScore.load(selectedDate.asString());
				}
			);

		this.calendarUpdate();
	},
	
	// Timezone select 
	timezoneReady: function() {
		$("#timezone option:first").text($.cookie('timezone_city'));
		
		Request.loadDiv($("#timezone"), "/timezones/select_timezone/", function(){
			$("#timezone option:contains('"+$.cookie('timezone_city')+"')").attr('selected','selected');
		});
        $("#timezone").change(function(){
			$.cookie('timezone',      $(this).val());
			$.cookie('timezone_city', $("#timezone option:selected").text());

			//Request.reload();
			//Latest.reload();
			Request.reloadLayout();
        });
	},

	ready: function() {
		// init current buttons state
		this.panel_fixtures_filter	($.cookie('fixtures_filter'),	false);
		this.panel_fixtures_group	($.cookie('fixtures_group'),	false);
		this.panel_fixtures_selected($.cookie('fixtures_selected'), false);
		this.panel_fixture_sound();
		
		// sound player 	
		if (!Request.isFeeds && $("#jquery_jplayer").length) {
			$("#jquery_jplayer").jPlayer();
		}		
		// button clicks
		// filter
        $("#live_games")    	.click(function() {	Toolbar.panel_fixtures_filter('live');     });
        $("#scheduled_games")	.click(function() {	Toolbar.panel_fixtures_filter('scheduled'); });
        $("#finished_games")	.click(function() {	Toolbar.panel_fixtures_filter('finished'); });
        $("#all_games")     	.click(function() {	Toolbar.panel_fixtures_filter('all');      });
        if (!Request.isFeeds) {
        // group
        	
        $("#sort_by_time")  .click(function() { Toolbar.panel_fixtures_group('time');   });
        $("#sort_by_league").click(function() { Toolbar.panel_fixtures_group('league');	});		
		//sound
		$("#sound").click(function(){	Toolbar.panel_fixture_sound('on-off', this.id);});
		$("#commentator, #football_ground, #bell").click(function(){Toolbar.panel_fixture_sound('sound_type', this.id);});		
		
        }
		// selected
		$("#select").click(function() { Toolbar.panel_fixtures_selected($.cookie('fixtures_selected')=='on'?'off':'on') });
		
		this.calendarReady();
		this.timezoneReady();
	},

	playSound: function(url) {
	    if ($("#jquery_jplayer").length)
			$("#jquery_jplayer").setFile(url).play();
	},

	goal: function() {
		if (!Request.isFeeds && $.cookie('sound_enabled') == 'on') 
			this.playSound('files/mp3/'+$.cookie('sound_type')+'.mp3');
	}
 
}
// Class Toolbar

/*
 * Class MainDbTree
 */
var MainDbTree = {

	// flags
	country_flags: {
		AFGHA:1,AFRIC:2,ALBAN:3,ALGER:4,AMSAM:5,ANDOR:6,AGO:7,ANGUI:8,ANTIG:9,ARGEN:10,ARMEN:11,ARUBA:12,ASIA:13,AUSTL:14,AUSTR:15,AZERB:16,BAHAM:17,BAHRA:18,BANGL:19,BARBA:20,BELAR:21,BELGI:22,BELIZ:23,BENIN:24,BERMU:25,BHUTA:26,BOLIB:27,BOSNI:28,BOTSW:29,BRASI:30,BRVIR:31,BRUNE:32,BULGA:33,BURKI:34,BURUN:35,CAMBO:36,CAMER:37,CANAD:38,CAPEV:39,CAYMA:40,CEAFR:41,TCHAD:42,CHILE:43,CHINA:44,TAIWA:45,COLOM:46,COMOR:47,DEREC:48,CONGO:49,COOKI:50,COSTA:51,IVORY:52,CROAT:53,CUBA:54,CYPRU:55,CZECH:56,DENMA:57,DJIBO:58,DOMCA:59,DOMRE:60,EASTI:61,EQUAD:62,EGYPT:63,ELSAL:64,ENGLA:65,EQUAT:66,ERITR:67,ESTON:68,ETHIO:69,EUROP:70,FAROE:71,FIJI:72,FINLA:73,FRANC:74,FRGUY:75,GABON:76,GAMBI:77,GEORG:78,GERMA:79,GHA:80,GIBRA:81,GREEC:82,GRENA:83,GUADE:84,GUAM:85,GUATE:86,GUIBI:87,GUINE:88,GUYAN:89,HAITI:90,HONDU:91,HONGK:92,HUNGA:93,ICELA:94,INDIA:95,INDON:96,IRAN:97,IRAQ:98,IRELA:99,ISRAE:100,ITALY:101,JAMAI:102,JAPAN:103,JORDA:104,KAZAK:105,KENYA:106,NOKOR:107,SKORE:108,KUWAI:109,KYRGY:110,LAOS:111,LATV1:112,LEBAN:113,LESOT:114,LIBER:115,LIBYA:116,LIECH:117,LITH1:118,LUXEM:119,MACAO:120,FYROM:121,MADAG:122,MALAW:123,MALAY:124,MALDI:125,MALI:126,MALTA:127,MARTI:128,MAURI:129,MAURT:130,MEXIC:131,MOLDO:132,MONGO:133,MONTE:134,MONTS:135,MOROC:136,MOZAM:137,MYANM:138,NAMIB:139,AMERN:140,NEPAL:141,NETHE:142,NEDER:143,NEWCA:144,NEWZE:145,NICAR:146,NIGR:147,NIGER:148,NIRLA:149,NORWA:150,OCEAN:151,OMAN:152,PAKIS:153,PALES:154,PANAM:155,PAPUA:156,PARAG:157,PERU1:158,PHILI:159,POLAN:160,PORTU:161,PUERT:162,QATAR:163,REUNI:164,ROMAN:165,RUSSI:166,RWAND:167,STMAR:168,SAMOA:169,SANMA:170,SAOTP:171,SAUDI:172,SCOTL:173,SENEG:174,SERBI:175,SERBI:176,SEYCH:177,SIERR:178,SINGA:179,SIMAR:180,SLOVA:181,SLOVE:182,SOLOM:183,SOMAL:184,SAFRI:185,AMERS:186,SPAIN:187,SRILA:188,STKIT:189,STLUC:190,STVIG:191,SUDAN:192,SURIN:193,SWAZI:194,SWEDE:195,SWITZ:196,SYRIA:197,TAHIT:198,TAJIK:199,TANZA:200,THAIL:201,TGO:202,TONGA:203,TNT:204,TUNIS:205,TURKE:206,TURKM:207,TURKS:208,TUVAL:209,UGAND:210,UKRAI:211,UAE:212,USA:213,URUGU:214,VIRIS:215,UZBEK:216,VANUA:217,VENEZ:218,VIETN:219,WALES:220,WORLD:221,YEMEN:222,ZAMBI:223,ZANZI:224,ZIMBA:225,
		AFCOC:226,AFRCN:227,AFRCQ:228,CAANC:229,CAFCL:230,CAFSC:231,CAFYC:232,ECAC:233,NAFC:234,CCFCC:235,CCFCL:236,CON20:237,GOLD:238,NASL:239,UNCAF:240,CLIB:241,COPAM:242,COPAS:243,RECOP:244,SU20:245,A3CC:246,AFCC:247,AFCCC:248,AFCCQ:249,AGS:250,ASCL:251,ASCUQ:252,EAASC:253,GCC:254,GCU17:255,GULF:256,SAFFC:257,SEAG:258,WAFFC:259,AMST:260,BALT:261,CHL:262,ESC:263,EU21Q:264,EUQ19:265,EUR19:266,EUR21:267,EURO:268,EURQ:269,EUU17:270,INTER:271,SETA:272,UEFA:273,UEFRL:274,UEFSC:275,WCQEU:276,OCC:277,ARCL:278,ARNC:279,CISCC:280,CONFE:281,COPAF:282,CYPIN:283,ECU19:284,FCWC:285,INTCP:286,INTF:287,INTFN:288,INTFU:289,KIRIN:290,OLQAF:291,OLQAS:292,OLY:293,PAG:294,PEACE:295,TOUTO:296,UHREN:297,WCC:298,WCD:299,WCE:300,WCF:301,WCF1:302,WCF3:303,WCG:304,WCH:305,WCKO:306,WCQAF:307,WCQAS:308,WCQF:309,WCQNA:310,WCQOC:311,WCQSA:312,WCSF:313,WCU17:314,WCU20:315,WOCFB:316,WOCUP:317,YTOUR:318
	},
	
	load: function() {
		Request.loadDiv($("#main_db_tree"), "/leagues/main_db_tree/", MainDbTree.ready);
	},

	ready: function() {
		
        europeDD = $(".EUROP").next();
        europeHeight = europeDD.height();
        americaDD     = $(".AMERI").next();
        americaHeight = americaDD.height();
        asiaDD = $(".ASIA").next();
        asiaHeight = asiaDD.height();
        africaDD     = $(".AFRIC").next();
        africaHeight = africaDD.height();
        australiaDD = $(".AUSTL").next();
        australiaHeight = australiaDD.height();
   
        $(".b-acc").click(function(){
    
            europeDD.height(europeHeight);
            americaDD.height(americaHeight);
            asiaDD.height(asiaHeight);
            africaDD.height(asiaHeight);
            australiaDD.height(australiaHeight);
    
            if($(this).hasClass('b-acc-active')) {
            	//do something
           	 	$("dd.leauges").css({display: "none"});
            	$('dt.country').removeClass('enable').addClass('disable');
            	
            	$(this).removeClass('b-acc-active').addClass('b-acc').next().animate({height:"hide"}, 500);
            	            	
                }
            else{
            	if ($(".b-acc-active").length == 0) {
            		$(this).removeClass('b-acc').addClass('b-acc-active').next().css({height:"auto"}).animate({height:"show"}, 500); //show(500);
            		
            	} else {	
	            	$('dt.country').removeClass('enable').removeClass('disable').addClass('disable');
	            	
	                toShow = $(this).next();
	                //toShow.css({height:"auto"});
	                toHide = $(".accordion dd:visible");
	    
	                staticheight = toShow.css({height:"auto"}).height(); 
	    
	                toShow.css({display: 'block', overflow: 'hidden'}); 
	    
	                toHide.animate({height:"hide"},{ //
	                    step: function(now) {
	                        var current = staticheight - now;
	                        if ($.browser.msie || $.browser.opera || $.browser.safari) {
	                            current = Math.ceil(current);
	                        }
	                        toShow.height(current);
	                    },
	                    duration: 500
	                });
	                
	                //setting classes
	                $(".b-acc-active").removeClass('b-acc-active').addClass('b-acc');
	                $(this).removeClass('b-acc').addClass('b-acc-active').next().css({height:"auto"});
            	}
            }
        });
    
        $(".country").click(function(){
            if($(this).hasClass('disable')){
                toShow = $(this).next();               
                toShow.css({display: 'block'});
                $(this).removeClass('disable');                
                $(this).addClass('enable');
                Continent = $(this).parents(this);
                el2 = Continent[2];
                $(el2).css({height:"auto"});
    
            } else { 
             if($(this).hasClass('enable')){
                    toHide = $(this).next();
                    toHide.css({display: 'none'});
                    $(this).removeClass('enable');
                    $(this).addClass('disable');
                }
            }
        });

	    // flags
		$("#main_db_tree dt.country span").each(function(i) {
			var country = $(this).attr('class'); 	
			if (country && MainDbTree.country_flags[country]) {
				var flag_index = 16 * MainDbTree.country_flags[country]+1;
				$(this).css('background-position','0 -'+flag_index+'px');
			}
		});
	}
}
// Main DB Tree END


/**
 * Class LiveScore
 *
 * Homepage livescore table class
 */
var LiveScore = {

	timer_started: false,

	ready: function() {

	    // Update calendar
	    if (Request.isAjax)
			Toolbar.calendarUpdate();
		
		// Status filter & selected games
		this.filterTable();
		
		// Popups
		this.FixtureInfo = new Popup(".fixture_popup", function(){
			LiveScore.FixtureOdds.hideClick();
		});
	
		this.FixtureOdds = new Popup(".odds_popup", function(){
			LiveScore.FixtureInfo.hideClick();
		});
		
		$(".live_score td.sc a").click(function() {
			LiveScore.FixtureInfo.showClick($(this));
			return false;
		});
		
		$(".live_score td.tools a").click(function() {
			LiveScore.FixtureOdds.showClick($(this));
			return false;
		});
	 
		$("body").click(function() {
			LiveScore.FixtureInfo.hideClick();
			LiveScore.FixtureOdds.hideClick();			
		});		
		//

		// Game select button
		$(".selected div").click(function() {	
			if ($(this).hasClass("select_game_off")) {
				$(this).removeClass("select_game_off").addClass("select_game_on");    		

				$.cookie('fixtures_selected_ids', $.cookie('fixtures_selected_ids') + ',' + $(this).parent().parent()[0].id);
			} else {
				$(this).removeClass("select_game_on").addClass("select_game_off");
				var select_array = $.cookie('fixtures_selected_ids');
				var tr_id = $(this).parent().parent()[0].id;
				
				select_array = select_array.replace(tr_id, '');
				select_array = select_array.replace(',,', ',');
				if (select_array == ',') {
					select_array = '';
				}
				$.cookie('fixtures_selected_ids', select_array);
			}
		});

		// flags
		$(".vpl").each(function(i) {
			var country = $(this).attr('class').split(' ')[1]; 			 
			if (country && MainDbTree.country_flags[country]) {
				var flag_index = 16 * MainDbTree.country_flags[country]+1;
				$(this).css('background-position','4px -'+flag_index+'px');
			}
		});		

		// games timer
		if (!this.timer_started) {
			this.timer_started = true;			
			this.setTimeout();
		}

		// Goal event hide timer
		if ($.cookie('fixtures_goals'))
			setTimeout('LiveScore.update()', 30000);
	},
	
	filterTable: function(show_loader) {
		if (show_loader && !Request.isFeeds) {
		    Request.loadStart();
		}

		if (Request.page == 'current')
			Latest.newGoalsCookieClear();

	    LiveScore._prev_date_tr  = false;
	    LiveScore._prev_separ_tr = false;
	    LiveScore._prev_title_tr = false;
		LiveScore._fixtures_no   = 0;
	    LiveScore._finished		 = false;
	    LiveScore._fixtures_filter		 = $.cookie('fixtures_filter');
	    LiveScore._fixtures_selected	 = $.cookie('fixtures_selected');
	    LiveScore._fixtures_selected_ids = $.cookie('fixtures_selected_ids') ? $.cookie('fixtures_selected_ids') : '';
	    LiveScore._fixtures_goals		 = $.cookie('fixtures_goals') ? $.cookie('fixtures_goals').toString().split(',') : [];
	    // clear cookies 
	    
		$('.live_score tr').each(function(i) {
			if (i == 0) return;
							
		    // Hide league title if it doesn't show fixtures
		    if (Request.group == 'league') {
				if ($(this).hasClass('league_separator')) {
					LiveScore._filterTableCheckLeagueTitle();
					LiveScore._fixtures_no = 0;
					LiveScore._prev_separ_tr = $(this);
				}
				if ($(this).hasClass('league_title')) {
					LiveScore._prev_title_tr = $(this);
				}
			}
		    // Hide league title if it doesn't show fixtures
		    if (Request.group == 'time') {
				if ($(this).hasClass('date_title')) {
					LiveScore._filterTableCheckDateTitle();
					LiveScore._fixtures_no = 0;
					LiveScore._prev_date_tr = $(this);
				}
			}

			// if it fixture tr and 
			var index = 8;
			var delta_feed = 0;
			if (!Request.isFeeds) {
				index = Request.group == 'time' ? 9 : 8;				
			} else {
				delta_feed = 1;
			}
			var status_td = $(this).children()[index];
			if (status_td != undefined && this.id != '') {

				var display = true;

				// Filter check
				if (Request.page == 'current') {
				    var status_div   = $(status_td).children('div')[0];				    
				    var status_class = $(status_div).attr('class');
					if ((LiveScore._fixtures_filter == 'scheduled' && status_class != 'sched') || (LiveScore._fixtures_filter == 'finished' && status_class != 'final') || (LiveScore._fixtures_filter == 'live' && status_class != 'on_air') ) {
						display = false;
					}
				}
				
				if (display) {
					// Selected check
					var select_array = LiveScore._fixtures_selected_ids;
					 
					if (select_array.search(this.id) > 0) {
						var td_sel = $(this).children()[0];
						$(td_sel.childNodes[0]).removeClass("select_game_off").addClass("select_game_on");
					} else {
						if ((select_array.search(this.id) != '') && (LiveScore._fixtures_selected == 'on')){
							display = false;
						} else {
							display = true;
						}
					}
				}
								
				if (display && Request.page == 'current' && status_class == 'on_air') {
					for(i in LiveScore._fixtures_goals) {
						var goal = LiveScore._fixtures_goals[i].split(':');
						if ('f' + goal[1] == this.id) {
							var row_td = $(this).children();
						    var goal_css = {"background-color":"#ffcccc", "color":"red", "font-weight":"bold", "border-color":"fff"};
						    $(row_td[index+delta_feed-5]).css(goal_css);
						    $($(row_td[index+delta_feed-5]).children('a')[0]).css(goal_css);
							if (goal[2] == 'home') {
								$(row_td[index+delta_feed-6]).css(goal_css);
							} else {
								$(row_td[index+delta_feed-4]).css(goal_css);
							} 
							break;
						}
					}
				}

				if (display) {
					$(this).show();
					LiveScore._fixtures_no++;
					if (status_class == 'final') LiveScore._finished = true;
				} else {
					$(this).hide();
				}
			}
		});	

	    if (Request.group == 'time') {
			// Last date title
			LiveScore._filterTableCheckDateTitle();
			if (Request.page == 'current') {
				// Finished title
				$('.live_score tr.finished')[LiveScore._finished?'show':'hide']();
			}
		} else {
			// Last league title
			LiveScore._filterTableCheckLeagueTitle();
		}

		if (show_loader && !Request.isFeeds) {
		    Request.loadEnd();
		}
	},
	
	_filterTableCheckLeagueTitle: function() {
		if (LiveScore._prev_title_tr) {
			if (LiveScore._fixtures_no != 0) {
				LiveScore._prev_separ_tr.show();
				LiveScore._prev_title_tr.show();
			} else {
				LiveScore._prev_separ_tr.hide();
				LiveScore._prev_title_tr.hide();
			}
		}
	},
	_filterTableCheckDateTitle: function() {
		if (LiveScore._prev_date_tr) {
			if (LiveScore._fixtures_no != 0) {
				LiveScore._prev_date_tr.show();
			} else {
				LiveScore._prev_date_tr.hide();
			}
		}
	},


/*
 * Load livescore table for specified date 
 *
 * Use cookies fixtures_date and fixtures_group as default values 
 *
 * @param	date	string	'yyyy-mm-dd' or 'current' or null
 */
	load: function(date, show_loader) {
		show_loader = show_loader != null ? show_loader : true;
	    if (date != null) {
			if (date == 'current') {
				date = Date.today;
			}
			Request.setDate(date);
		} else {
			date = Request.date;
		}
		var url = ( Request.isFeeds ? '/feed/'+css_id+'/'+timezone : '') + (Request.group == 'league' ? '/league' : '') + (date != Date.today ? '/' + date : '') + '/';
		// Load livescore, no cache for current day
		Request.load(url, show_loader, date == Date.today);
	},

	goal: function() {
		//alert('Goal!');
		this.update();
	},
	update: function() {
		if (Request.page == 'current') {			
			this.load(Date.today, false);
		}
	},	
	setTimeout: function() {
		setInterval('LiveScore.gameBlink()', 500); 
		setInterval('LiveScore.gameTimer()', 60000);
		setInterval('LiveScore.update()',    300000);
	},
	
	gameTimer: function(){		
		if (Request.page == 'current') {
			$('span.game_time').each(function() {
				var cur_time = $(this).text()*1;				
				if ((cur_time < 90)&&!isNaN(cur_time)) {
					$(this).text(++cur_time);
				}
				if (cur_time == 46) {
					//Reload
					LiveScore.update();
				}
			});
		}
	},
	gameBlink: function(){	
		if (Request.page == 'current') {
			$('span.blink').each(function() {
				game_time = $(this).css("visibility");
				if (game_time == "visible" ) {
					$(this).css({"visibility":"hidden"});
				} else {
					$(this).css({"visibility":"visible"});
				}
			});
		}
	}

}

/*
 * Class Popup
 *
 * Display hidden div container as popup aln load url into it
 */
function Popup(container_name, show_callback, popup_div_class) {
    this.container_name = container_name;
    this.show_callback = show_callback;
    this.showed = false;
    this.show_start = false;
    this.show_url = false;
    this.pointer_offset = 0;

	this.show = function(url, offsetTop) {
		$(this.container_name).css({top: offsetTop});		
		$(this.container_name).show();

		this.load(url);		
	};
	
	this.hide = function() {
		$(this.container_name).hide();
	};
/*
 * @param	object	element		clicked anchor jquery object inside a table cell
*/
	this.showClick = function(element, popup) {
	    if (this.show_callback)
	    	this.show_callback();

	    var url = element.get().toString();	    
	    if (this.showed && url == this.show_url) {
			this.showed = false;
			this.hide();
	    } else if (!this.showed || url != this.show_url) {
			this.showed = true;
			this.show_url = url;
	
	        var td = element.parent();
	        var tr = td.parent();
	        var table = tr.parent();

	        // x offset where pointer should point
	        this.pointer_offset = td.position().left + td.width()/2;

		    // y offset where popup should be shown
	        var offsetTop = tr.offset().top + tr.height() - (Request.isFeeds ? 0 : $("#content_area").offset().top);	        
			this.show(url, offsetTop);
		}
	};
	this.hideClick = function() {
		this.showed = false;
		this.hide();
	};
	// load popup, no cache for current day
	this.load = function(url) {
        Popup.currentPopup = this;
		Request.loadDiv($(this.container_name), url, function(){
		    var _this = Popup.currentPopup;
			var container = $(_this.container_name).find('div');
			var pointer   = $(_this.container_name+" .popup_pointer");
			var offset = _this.pointer_offset - container.position().left - pointer.width()/2;
			pointer.css({"margin-left":offset});
		}, Request.page == 'current');		
	};
}
// Class Popup



/*
 * Class TabBar 
 * 
 * Table tab with AJAX reloaded content
 */
function TabBar(parent_selector, conteiner_id, url_callback, ready_callback){
	
	this.parent_selector = parent_selector;
	this.conteiner_id = conteiner_id;
	this.url_callback = url_callback;
	this.ready_callback = ready_callback;

	this.click = function(e) {
		var _this = e.data;
		if ($(this).hasClass("table_tab")) {
			var enable_tab =  parent_selector+" .active_table_tab";
			var disable_tab = parent_selector+" .table_tab";
			
			var active = $(enable_tab);
			$(active).parent(active).removeClass("border_shadow");
			
			active.removeClass("active_table_tab");
			active.addClass("table_tab");
			
			$(this).parent().addClass("border_shadow");
			$(this).removeClass("table_tab");
			$(this).addClass("active_table_tab"); 
							
			var url = _this.url_callback.call(this, $(this));
			_this.load(url);
		}
	};	

	this.load = function(url) {
	    TabBar.current = this;
		
		Request.loadStart();
		$(this.conteiner_id).load(url, null, this.ready);
	};

	this.ready = function() {
		var _this = TabBar.current;

		if (_this.ready_callback)
			_this.ready_callback();

		Request.loadEnd();
	};

	var enable_tab =  parent_selector+" .active_table_tab";
	var disable_tab = parent_selector+" .table_tab";
	$(enable_tab+", "+disable_tab).bind('click', this, this.click);
}


/*
 * Class LeagueTable
 *
 * Leagues to head page
 */
var LeagueTable = {

	ready: function() {
		var tab = new TabBar(".league", "#league_table", function(selected) {
			return "/league_tables/table/"+$("#league_id").text()+"/"+$("#season_id").text()+"/"+selected.attr('id')+'/';
		}, LeagueTable.tableReady);

		$("#season").change(function() {
		    var val = $(this).children('option:selected').text();
		    val = val != "Current" ? val+'/' : '';
			Request.load('/'+$("#league_api_id").text()+'/'+val);
		});
		
		LeagueTable.setFlag();
		LeagueTable.tableReady();
	},

	setFlag: function(){
	    var div_country = $("div.country");
		if (div_country.length) {
			var country = div_country[0].id;		
			var flag_index = 24 * MainDbTree.country_flags[country]+2;
			$("div.country").css('background-position','0 -'+flag_index+'px');
		}
	},
	
	tableReady: function() {

	    // Compare button
	    $("#compare").click(function(){

	    	var select_checkbox = $(":checkbox:checked");
	    	if (select_checkbox.length = 2) {
	    		
	    		var league_id = $("#league_api_id").text();	
	    		var url = "/"+league_id+"/"+select_checkbox[0].value+"-vs-"+select_checkbox[1].value+'/';
	    		
	    		Request.load(url, H2h.ready);
	    	}
	    	
	    	return 1;
	    });
	    
	    // Checkbox checked rules
	    $(":checkbox").click(function(){
	    	var select_checkbox = $(":checkbox:checked");

	    	if (select_checkbox.length > 2) {
	    		select_checkbox[0].checked = '';
	    	}
	    });
	}
}


/*
 * Class H2h
 *
 * Head to head page
 */
var H2h = {

	filterParam: function(home_away) {
	    home_away = home_away.toLowerCase();
		if (home_away == "home" || home_away == "away") {
			return home_away+'/';
		} else {
			return '';
		}
	},
	ready: function() {
		var tab0 = new TabBar(".h2h_info_table_history", "#h2h_info_table_history", function(selected) {
			return "/fixtures/teams_history/"+$("#league_id").text()+"/"+$("#team_home_id").text()+'-'+$("#team_away_id").text()+'/'+H2h.filterParam(selected.attr('id').replace('h_',''));
		});
		var tab1 = new TabBar(".last6_first_team", "#last6_first_team", function(selected) {
			return "/fixtures/team_history/"+$("#league_id").text()+"/"+$("#team_home_id").text()+'/'+H2h.filterParam(selected.text());
		});
		var tab2 = new TabBar(".last6_second_team", "#last6_second_team", function(selected) {
			return "/fixtures/team_history/"+$("#league_id").text()+"/"+$("#team_away_id").text()+'/'+H2h.filterParam(selected.text());
		});
		var tab3 = new TabBar(".next6_first_team", "#next6_first_team", function(selected) {
			return "/fixtures/team_scheduled/"+$("#league_id").text()+"/"+$("#team_home_id").text()+'/'+H2h.filterParam(selected.text());
		});
		var tab4 = new TabBar(".next6_second_team", "#next6_second_team", function(selected) {
			return "/fixtures/team_scheduled/"+$("#league_id").text()+"/"+$("#team_away_id").text()+'/'+H2h.filterParam(selected.text());
		});
	}
}


/*
 * Class Team
 *
 * Team page
 */
var Team = {
	ready: function() {
		var tab = new TabBar(".team_fixtures", "#team_fixtures", function(selected) {
		    var filter = H2h.filterParam(selected.text().replace(' Matches','')); 
		    	filter = filter ? filter : 'all/';
		    var league = $("#league_id").text() ? $("#league_id").text() + '/' : '';
			return '/fixtures/team/'+$("#team_id").text()+'/'+filter+league;
		}, Team.fixturesReady);

		$("#season").change(function() {
		     var val = $(this).val() ? $(this).val() + '/' : '';
			 Team.fixturesLoad('/fixtures/team/'+$("#team_id").text()+'/all/'+val);
		});
		
		LeagueTable.setFlag();		
		Team.fixturesReady();
		
	},

	fixturesLoad: function(url) {
		Request.loadStart();
		Request.loadDiv($("#team_fixtures"), url, Team.fixturesReady);
	},

	fixturesReady: function() {
		$("#team_fixtures .p_nav td a").click(function(){
			Team.fixturesLoad($(this).get().toString());
			return false;
		});

		// Popups
		this.FixtureInfo = new Popup(".fixture_popup");
		$(".team_table td .details").click(function() {
			Team.FixtureInfo.showClick($(this).parent().find('a'));
			return false;
		});
		$("body").click(function() {
			Team.FixtureInfo.hideClick();
		});		
		//
		
		Request.loadEnd();
	}
}

/**
 * Class Latest
 * 
 * Latest score block
 */
var Latest = {

	timer_started: false,

	data: {'Goals':[],'RCs':[],'hashSumm':[]},
	newEvents: {'Goals':[],'RCs':[],'hashSumm':[]},
	
	template_tr: function(d) {
		return ''+
		'<tr>'+
			'<td class="time" width="50">['+d['fixtureevent_time']+']</td>'+
			'<td class="'+d['class_home']+'" width="175">'+d['teamhome_name']+'</td>'+
			'<td class="sc" width="37">'+d['fixtureevent_goal1']+'-'+d['fixtureevent_goal2']+'</td>'+
			'<td class="'+d['class_away']+'" width="200">'+d['teamaway_name']+'</td>'+
		'</tr>';
	},
		
	ready: function() {
		$("div.latest_info .plus_close").click(function(){
			if ($(this).hasClass("plus_close_on")){
				$(this).removeClass("plus_close_on").addClass("plus_close_off");
				$("div.latest_info").addClass("latest_info_off");
			} else {
				$(this).removeClass("plus_close_off").addClass("plus_close_on");
				$("div.latest_info").removeClass("latest_info_off");
			}				
		});
		if (!this.timer_started) {
			this.timer_started = true;
			this.setTimeout();
		}
	},

	load: function() {
		$.getJSON('/ajax/fixture_events/json_latest/'+Request.noCacheQueryString(), null, function(data, textStatus) { Latest.dataLoaded(data, textStatus) });
	},

	reload: function() {
		this.data = new Array();
		this.load();
	},
	
	dataLoaded: function(data, textStatus) {
		if (!object_equal(data, this.data)) {
	        var goal = false;
			if (this.newTopEvents('Goals', data)) {
				// new goals
				this.newGoalsCookieSet();

				Toolbar.goal();
				LiveScore.goal();
	
		        goal = true;
			}
			if (this.newTopEvents('RCs', data)) {
				// new red cards
			}
			if (!goal) {
				LiveScore.update();
			}

		    this.data = data;
			this.updateTable();
		}
		this.setTimeout();
	},

	newTopEvents: function(type, data) {
		this.newEvents[type] = [];

		for (i in data[type]) {
		    var is_new = true;
			for (j in this.data[type]) {
				if (object_equal(data[type][i], this.data[type][j])) {
				    is_new = false;
					break;
				}
			}
			if (is_new)
				this.newEvents[type].push(data[type][i]);
			else
				break;
		}

		return (this.newEvents[type].length > 0);
	},

	setTimeout: function() {			
		setTimeout('Latest.load()', 30000);
	},
	
	updateTable: function() {		
		var table = '';
		if (this.data['Goals'].length != 0) {
			for(var i in this.data['Goals']) {
				row = this.data['Goals'][i];
				if (row["fixtureevent_team_id"] == row["teamhome_id"]) {
					row['class_home'] = "home event";
					row['class_away'] = "away";
				} else {
					row['class_home'] = "home";
					row['class_away'] = "away event";
				}
				table += this.template_tr(row);
			}
		} else {
			table = '<tr><td>Watch all the action live on globalscore.com</td></tr>';
		}
		$("#latest_table").html(table);
	},

	newGoalsCookieSet: function() {
		var time = (new Date).getTime()+30000;
		var cookie_goals = $.cookie('fixtures_goals') ? $.cookie('fixtures_goals').toString().split(',') : [];
	    var new_goals    = this.newEvents['Goals'].slice();
		for (var i in new_goals) {
			cookie_goals.push( time + ':' + new_goals[i]['fixture_id'] + ':' + (new_goals[i]['fixtureevent_team_id'] == new_goals[i]['teamhome_id'] ? 'home' : 'away') + '' );
		}
		$.cookie('fixtures_goals', cookie_goals.join(','));
	},

	newGoalsCookieClear: function() {
		if ($.cookie('fixtures_goals')) {
			var time = (new Date).getTime();
			var cookie_goals  = $.cookie('fixtures_goals') ? $.cookie('fixtures_goals').toString().split(',') : [];
			var cleared_goals = [];
			for (i in cookie_goals) {
				var goal = cookie_goals[i].split(':');
				if (goal[0] > time)
					cleared_goals.push(cookie_goals[i]);
			}
			$.cookie('fixtures_goals', cleared_goals.join(','));
		}
	},

	setData: function(data) {
		this.data = data;
	}
}


/**
 * Class Adverts
 * 
 * Advertisement bannets
 */
var Adverts = {
	ready: function() {
	    var right_banner = $('.right_banner img');
		right_banner.attr('src', right_banner.attr('src'));
	}
}


//
// Functions
//
function is_object(val) {
	return (typeof(val) == "object") ? true : false;
}
function is_array(arr) {
	return (arr != undefined && is_object(arr) && arr.constructor == Array) ? true : false;
}
function array_equal(a1, a2) {
	return object_equal(a1, a2)
}
function object_equal(o1, o2) {
    if (o1 == o2)
    	return true;

    if (!is_object(o1) || !is_object(o2) || o1.length != o2.length)
    	return false;

	for (var i in o1) {
		if ( (o1[i] != o2[i]) && !(is_object(o1[i]) && is_object(o2[i]) && object_equal(o1[i],o2[i])) )
	    	return false;
	}
	return true;
}
function array_search(needle, haystack, strict) {
    var strict = !!strict;
 
    for(var key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ) {
            return key;
        }
    }
 
    return false;
}
function array_search(arr, value) {
	for(var element in arr) if(arr[element] == value) return element;
	return;
}
function array_delete(arr, i) {
	return arr.slice(0, i).concat(arr.slice(i+1));
}
//
