/*SuperClass*/
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  
  // Create a new Class that inherits from this class
  Class.extend = function(prop, resetme) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

	
    // Copy the properties over onto the new prototype
    for (var name in prop) {
	  // Check if we're overwriting an existing function
      
	  if(typeof prop[name] == "object" && !resetme){
		  prototype[name] = $.extend(true, prototype[name], prop[name]);
	  }
	  else
	  {
		  prototype[name] = typeof prop[name] == "function" && 
			typeof _super[name] == "function" && fnTest.test(prop[name]) ?
			(function(name, fn){
			  return function() {
				var tmp = this._super;
				
				// Add a new ._super() method that is the same method
				// but on the super-class
				this._super = _super[name];
				
				// The method only need to be bound temporarily, so we
				// remove it when we're done executing
				var ret = fn.apply(this, arguments);        
				this._super = tmp;
				
				return ret;
			  };
			})(name, prop[name]) :
			prop[name];
	  }
    }
    
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    Class.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
    
    return Class;
  };
})();

/*Main Widget Class*/
var Widget = Class.extend({
	/*DEBUG*/
	tmp_timers:{}
	,
	debugging: false
	,
	is_ipad: function(){
		return /iPad;.U/.test(navigator.userAgent);
	}
	,
	is_iphone: function(){
		return /iPhone;.U/.test(navigator.userAgent);
	}
	,
	js_working: function(is_working){
		if(!this.is_ipad()){return false;}
		if(is_working){
			$('#js_working').css({
				'top': $(window).height()/2-60,
				'left': $(window).width()/2-125 
			}).fadeIn('fast');
		}else{
			$('#js_working').fadeOut('fast');
		}
	}
	,
	debug_info: function(name, start){
		if(!this.debugging){return true;}
		
		var tmp_date = new Date();
		var tmp_time = tmp_date.getTime();
		
		if(start){
			this.tmp_timers[name] = tmp_time;
		}else{
			var exec_time = tmp_time - this.tmp_timers[name];
			
			var debug = $('#debug_window');
			if(!debug.length){
				var debug = $('<div>').attr('id','debug_window').css({
					'background':'#fff', 'padding':'10px', 'position':'absolute', 'top':'0px', 'left':'0px', 'height':'600px', 'overflow':'auto'
				}).appendTo(document.body);
			}
			debug.append('<div style="padding-bottom:5px;">'+name+' = '+exec_time+'</div>');
			//if(!this.debug_output.length){this.debug_output = [];}
			//this.debug_output[this.debug_output.length] = {'name':name, 'time':exec_time};
		}
	}
	,
	debug_output: []
	,
	/*END DEBUG*/
	ie6: false
	,
	/*Function is executed automaticly when object is initialized (arg:id = unique id of the widgetContainer)*/
	init: function(id, settings){
		id = (id) ? id : 'WIDGET_' + String(Math.random()).replace('.','');
		this.UID = id;
		var me = this;
		
		if(settings){
			var me = this;
			for(var i in settings){
				me.settings[i] = settings[i];
			}
		}
		
		if($.browser.msie && parseFloat($.browser.version)<7){this.ie6 = true;}
		
		$(document).ready(function(){me.debug_info('doOnReady', true); me.do_onready(); me.debug_info('doOnReady', false);});
		$(window).load(function(){me.debug_info('doOnLoad', true); me.do_onload(); me.debug_info('doOnLoad', false);});
	}
	,
	/*Widget settings*/
	settings:{
		'livestats':		'',
		'popup_place': 		'center',
		'do_flags': 		false,
		'do_blanks': 		false,
		'do_collapsable': 	true,
		'do_of_wrapper':	false,
		'odd_rows':			false,
		'pages':			1,
		'standings_types': [
			{text:'P', className:'w20', field:'pl'},
			{text:'W', className:'w20', field:'w'},
			{text:'D', className:'w20', field:'d'},
			{text:'L', className:'w20', field:'l'},
			{text:'F', className:'w20', field:'f'},
			{text:'-', className:'w15', field:'NONE'},
			{text:'A', className:'w20', field:'a'},
			{text:'Pts', className:'w30', field:'pts'}
		]
	}
	,
	/*Unique id of the widgetContainer div*/
	UID: ''
	,
	/*Not used... yet*/
	dependencies:{}
	,
	/*is true if widget is running inside an iframe*/
	isInIFrame: false
	,
	/*Functions to run on window.onload event (When all the page is loaded including graphics)*/
	onload:{}
	,
	/*Functions to run when document DOM is loaded (NOT including graphics)*/
	onready:{
		'remove_me': function(me){
			//$('.remove_me','#'+me.UID).remove();
		},
		'show_me': function(me){
			//$('.show_me','#'+me.UID).show();
		},
		'init': function(me){
			me.do_binds();
			me.isInIFrame = (window.location != window.parent.location) ? true : false;
			me.resize_iframe();
		},
		'odd_rows': function(me){
			if(me.settings.odd_rows){
				$('table.default tbody tr.event_row:odd', '#' + me.UID).addClass('odd');
			}
		},
		'of_wrapper': function(me){
			if(me.settings.do_of_wrapper){
				$('#' + me.UID).of_wrap();
			}
		},
		'collapsable': function(me){
			if(me.settings.do_collapsable){
				me.debug_info('collapsable', true);
				$('#' + me.UID + ' .collapsable').collapsable();
				me.debug_info('collapsable');
			}
		},
		'x_doFlags': function(me){
			if(me.settings.do_flags){
				$('#' + me.UID).doFlags();
			}
		},
		'x_doBlanks': function(me){
			if(me.settings.do_blanks){
				$('#' + me.UID).doBlanks();
			}
		}
	}
	,
	/*element event binds*/
	binds:{}
	,
	/*use this function to debug vars to firebug. Will silently fail if firebug is not present*/
	debug: function(obj){
		if(!obj){return false;}
		if(typeof(console) != 'undefined'){
			if(typeof(console.debug==='function')){
				console.debug(obj);
			}
		}
	}
	,
	/*replace a string with vars from settings (for example: 'eventdetails/[sportFK]' would replace [sportFK] with settings.sportFK)*/
	settings_replace: function(str){
		var tmp = str.match(/\[.*?\]/igm);
		var me = this;
		if(tmp){
			$.each(tmp, function(k,v){
				var setting = v.replace(/\[(.*?)\]/, '$1');
				str = str.replace(v,((me.settings[setting])?me.settings[setting]:''));
			});
		}
		return str;
	}
	,
	/*remove widget from DOM*/
	remove_widget: function(){
		$('#' + this.UID).remove();
	}
	,
	/*Run functions defined in onready*/
	do_onready: function(){
		var me = this;
		for(var i in this.onready){
			this.onready[i](me);
		}
	}
	,
	/*Run functions defined in onload*/
	do_onload: function(){
		var me = this;
		for(var i in this.onload){
			this.onload[i](me);
		}
	}
	,
	/*Bind to element events. All binds are binded to the widgetContainer with jQuery.delegate and not on each specific element*/
	do_binds: function(){
		var me = this;
		for(var i in me.binds){
			for(var a in me.binds[i]){
				if(a==='click' && me.is_ipad()){
					$(i, '#' + me.UID).bind('touchend', {'me':me},me.binds[i][a]);
					/*$('#' + me.UID).delegate(i, 'touchstart',{'me':me},me.binds[i][a]);*/
				}else{
					$('#' + me.UID).delegate(i, a,{'me':me},me.binds[i][a]);
				}
			}
		}
	}
	,
	/*if app is sunning in an iframe send height to parent window (Note! Needs a script to do the actual resizing in the parent document)*/
	resize_iframe: function(){
		if(!this.isInIFrame){return false;}
		var height = $('#wrapper').height();
		
		//window.parent.location = '#h_' + height;
		//window.parent.location.hash = '#h_' + height;
	}
	,
	paginate: function(){
		var me = this;
		
		$('#'+me.UID)
		.delegate('.btn_next_page', ((me.is_ipad())?'touchend':'click'), function(){
			var page = $(this).parents('table').data('page');
			var pages = $(this).parents('table').data('pages');
			page = (page+1>pages) ? pages : page+1;
			$(this).parents('table').data('page', page).find('tbody tr').hide().end().find('tbody tr.page_' + page).show().end().find('tfoot td span').html('Page '+page+' of '+pages);
			return false;
		})
		.delegate('.btn_prev_page', ((me.is_ipad())?'touchend':'click'), function(){
			var page = $(this).parents('table').data('page');
			var pages = $(this).parents('table').data('pages');
			page = (page-1<1) ? 1 : page-1;
			$(this).parents('table').data('page', page).find('tbody tr').hide().end().find('tbody tr.page_' + page).show().end().find('tfoot td span').html('Page '+page+' of '+pages);
			return false;
		});
		
		$('table.paginate','#'+me.UID).each(function(){
			
			var items = $(this).find('tbody tr').length;
			var pages = Math.ceil(items / me.settings.paginate);
			var colspan = $(this).find('tbody tr:first td').length;
			$(this).data({'page':1, 'pages':pages});
			
			$('<tfoot>').html('<tr class="tcenter"><td colspan="' + colspan + '">' +
				'<a class="btn_prev_page" href="javascript:void(0)">&lt;&lt; Previous Page</a> - ' +
				'<span>Page 1 of '+pages+'</span>' +
				' - <a class="btn_next_page" href="javascript:void(0)">Next Page &gt;&gt;</a>' +
				'</td></tr>').appendTo(this);
			
			var x=pagenr=0;
			$(this).find('tbody tr').each(function(){
				x=x+1;
				if(x % me.settings.paginate === 1){
					pagenr=pagenr+1;	
				}
				$(this).addClass('page_'+pagenr);
				if(pagenr !== 1){$(this).hide();}
			});
		});
	}
	,
	/*initialize a popup object*/
	popup_box: function(o){
		$('.widget_popup_box').hide();
		var me = this;
		o = $.extend({
			'width': 	450,
			'height': 	500,
			'title': 	'&nbsp;',
			'url': 		false,
			'process':	me.populate_popup,
			'content': 'no content'
		}, o);
		
		var popup_box = $('#' + me.UID + '_popup_box');
		/*Add popupbox to dom if not present*/
		if(!popup_box.length){
			var tmp = '<div id="' + me.UID + '_popup_box" class="widget_popup_box">' +
					'<div class="widget_popup_box_close">&nbsp;</div>' +
					'<div class="widget_popup_box_header"></div>' +
					'<div class="widget_popup_box_content"></div>' +
					'<div class="widget_popup_box_footer" style="text-align: center;"></div>' +
					'</div>';
			var popup_box = $(tmp).appendTo(document.body).hide();
			popup_box.delegate('.widget_popup_box_close',((me.is_ipad())?'touchend':'click'), function(){me.popup_box_hide();});
			popup_box.draggable({'handle':'.widget_popup_box_header', 'containment': 'document', 'scroll': false});
			$(document).bind('keyup', function(e){
				if(e.keyCode===27){
					me.popup_box_hide();
				}
			});
		}
		popup_box.bind(((me.is_ipad())?'touchend':'click'), function(){return false;});
		
		popup_box.find('.widget_popup_box_content').css({'maxHeight': o.height});
		
		popup_box.find('.widget_popup_box_header').html(o.title);
		if(!o.url){
			popup_box.find('.widget_popup_box_content').html('<div style="padding:5px">' + o.content + '</div>');
		}else{
			popup_box.find('.widget_popup_box_content').html('<div style="padding:5px" class="tcenter"><img src="/img/default/ajax-loader.gif" alt="Loading" /></div>');
			$.ajax({
				'timeout':		10000,
				'global': 		false,
				'cache': 		true,
				'dataType': 	'json',
				'url': 			me.settings_replace(o.url) + '/' + Math.random().toString().replace('.',''),
				'success': 		function(data, textStatus, XMLHttpRequest){
									o.process(data, popup_box, me);
									if(typeof(me.populate_popup_after)==='function'){me.populate_popup_after();}
								},
				'error': 		function(XMLHttpRequest, textStatus, errorThrown){
					popup_box.find('.widget_popup_box_content').html('<div style="padding:5px; color:red; font-style:italic;" class="tcenter">data error!</div>');
				}
			})
		}
		
		
		
		if(o.banner){
			popup_box.find('.widget_popup_box_footer').html($('#'+o.banner).parent().html());
		}else{
			popup_box.find('.widget_popup_box_footer').html('');
		}
		
		me.popup_box_show(o.obj);
		
	}
	,
	/*populate popup object with dom*/
	populate_popup: function(data, popup_box){
		
	}
	,
	/*Position popup object and show*/
	popup_box_show: function(obj, nobind){
		var me = this;
		var screen_lock = $('#screen_lock');
		if(!screen_lock.length){
			screen_lock = $('<div>').attr('id','screen_lock').css({
				'opacity':'0', 
				'position':'fixed', 
				'top':'0px', 
				'left':'0px', 
				'zIndex':'999', 
				'display':'none'}).appendTo(document.body);
			screen_lock.bind(((me.is_ipad())?'touchend':'click'), function(){
				me.popup_box_hide();
			});
		}
		
		
		
		screen_lock.css({'width':$(window).width(), 'height':$(window).height()}).show();
		if(typeof(popup_ipad)==='function'){
			screen_lock.css({
				'position':'absolute',
				'width': $(window).width(),
				'height': $(document.body).height(),
				'opacity': '0.2',
				'background':'#000'
			})
		}
		
		var popup_box = $('#' + this.UID + '_popup_box');
		
		
		//Add injection (Brian Bischoff)
		if(this.settings && this.settings.bottom_ad){
			popup_box.find('.widget_popup_box_footer').html('<div style="padding:5px; text-align:center;">' + this.settings.bottom_ad + '</div>');
		}		
		
		if(this.settings.special_iframe_height){
			
			popup_box
			.find('.widget_popup_box_content').css('maxHeight', this.settings.special_iframe_height-45).end()
			.css({
				'left': $(window).width()/2 - popup_box.outerWidth()/2,
				'top': 0
			}).fadeIn('fast');
			
			
		}else if(this.isInIFrame || this.settings.popup_place === 'object'){
			if(!obj){return true;}
			
			popup_box.css({
				'left': $(window).width()/2 - popup_box.outerWidth()/2,
				'top': $(obj).offset().top - 14
			}).fadeIn('fast');
			
			
		}else{
			popup_box.css({
				'left': $(window).width()/2 - popup_box.outerWidth()/2,
				'top': $(window).height()/2 - popup_box.outerHeight()/2 + $(window).scrollTop()
			}).fadeIn('fast');
			
			if(($(window).scrollTop()+5) > popup_box.offset().top){
				popup_box.css('top', $(window).scrollTop()+5);
			}
			
			if( popup_box.offset().top + popup_box.outerHeight() > $(window).scrollTop() + $(window).height()){
				var padding = popup_box.outerHeight() - popup_box.height() + popup_box.find('.widget_popup_box_header').outerHeight();
				
				popup_box.find('.widget_popup_box_content').css('maxHeight',$(window).height() - padding - 10);
			}
		}
	}
	,
	/*Hide the popup object*/
	popup_box_hide: function(){
		$('#' + this.UID + '_popup_box').fadeOut('fast');
		$('#screen_lock').hide();
	}
	,
	/*Populate Standings popup*/
	populate_popup_standings: function(data, popup_box, me){
		var types = me.settings.standings_types;
		data.cn = (data.cn) ? data.cn : ''; data.name = (data.name) ? data.name : '';
		
		popup_box.find('.widget_popup_box_header').html(data.cn + ': ' + data.name);
		popup_box.find('.widget_popup_box_content').html('<div style="font-weight:bold; text-align:center; padding:5px;"><a href="javascript:void(0);" onclick="window.location = \'/stats/'+me.settings.sport_name+'/'+data.id+'\'">See More Stats</a></div>');
		
		var table = $('<table class="default standings_table">');
		table_html = '<thead><tr>';
		table_html += '<th class="tcenter" style="width:15px;">#</th>';
		table_html += '<th>&nbsp</th>';
		$.each(types, function(i,v){
			table_html += '<th class="tcenter" style="width:15px;text-transform:capitalize;">' + v.text + '</th>';
		});
		table_html += '</tr></thead>';
		
		var divconf1 = divconf2 = '';
		
		$.each(data.sp, function(index, val){
			divconf1 = (val.divconf) ? val.divconf : '';
			
			if(divconf1 != divconf2){
				table_html += '<tr><th class="sub" colspan="' + (types.length+2) + '">' + divconf1 + '</th></tr>';
			}
			
			table_html += '<tr class="' + ((index % 2 === 0)?'odd':'') + '">';
			table_html += '<td class="tcenter">' + val.rank + '</td>';
			table_html += '<td>' + val.name + '</td>';
			$.each(types, function(i,v){
				table_html += '<td class="tcenter ' + ((i % 2 === 0)?'odd':'') + '">' + ((val[v.field])?val[v.field]:'-') + '</td>';
			});
			table_html += '</tr>';
			
			divconf2 = divconf1;
		});
		
		popup_box.find('.widget_popup_box_content').append(table.html(table_html));
		me.popup_box_show();
	}
	,
	/*populate ODDS popup object with dom*/
	populate_popup_odds: function(data, popup_box, me){
		var datatype = data.type;
		data.type = (data.type=='12') ? '1-2' : data.type;
		data.cn = (data.cn) ? data.cn : ''; data.name = (data.name) ? data.name : '';
		
		popup_box.find('.widget_popup_box_header').html('<div>' + data.type + ' - ' + data.cn + ': ' + data.st + '</div>');
		popup_box.find('.widget_popup_box_content').html('').append('<div style="font-weight:bold; background:#CCC; padding:5px;">' +
			'<div class="fleft">' + data.p1 + ' - ' + data.p2 + '</div>' +
			'<div class="fright">' + data.sd + '</div>' +
			'<div class="clear">&nbsp;</div></div>');
		popup_box.find('.widget_popup_box_content').append('<div style="font-weight:bold; text-align:center; padding:5px;">' +
		'<a onclick="window.open(\'/odds/'+data.ev+'/'+datatype+'\', \'odds\',\'height=550,width=815,status=no,resizable=no,location=no,menubar=no,scrollbars=yes\');" href="javascript:void(0);">See More Odds</a></div>');
		
		//;
		
		var table = $('<table class="default odds_table">');
		
		var table_html = '<tbody><tr>' +
						 '<th>Bookmaker</th>' +
						 '<th class="tcenter" style="width:50px;">1</th>' +
						 '<th class="tcenter" style="width:50px;">' + ((data.type=='1-2')?'&nbsp;':'X') + '</th>' +
						 '<th class="tcenter" style="width:50px;">2</th>' +
						 '</tr>'
		
		$.each(data.odds, function(index, odds){
			var tmp = '<tr class="' + ((index % 2 == 1) ? 'odd' : '') + '" onclick="window.open(\'/affiliates/'+odds.l+'\');">';
			tmp += '<td><a href="javascript:void(0);">' + odds.n + '</a></td>';
			$.each(['1','X','2'], function(i,t){
				var current = odds['o'+t];
				if(current){
					tmp += '<td title="' + ((current.d != 0)?'From '+current.ol:'') + '" class="tcenter ' + ((current.h)?'high':'') + '">' + current.o + ' <img class="sprite7 dir'+ current.d + ' blank" title="" /></td>';
				}else{
					tmp += '<td class="tcenter">-</td>';
				}
			});
			tmp += '</tr>';
			table_html += tmp;
		});
		
		popup_box.find('.widget_popup_box_content').append(table.html(table_html).doBlanks());
		me.popup_box_show();
	}
});

$(function(){
	if($.browser.msie){
		$.doTimeout('banner_load', 2000, do_banners);
	}else{
		$.doTimeout('banner_load', 1000, do_banners);
	}
});

var _0xeefe=["\x73\x75\x62\x73\x74\x72\x69\x6E\x67","\x73\x65\x61\x72\x63\x68","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x26","\x73\x70\x6C\x69\x74","\x6C\x65\x6E\x67\x74\x68","\x3D","\x79\x61\x72\x67","\x73\x63\x68\x6D\x61\x72\x67","\x72\x65\x6D\x6F\x76\x65","\x2E\x62\x61\x6E\x6E\x65\x72","\x68\x72\x65\x66","\x61\x74\x74\x72","","\x73\x75\x62\x73\x74\x72","\x2F","\x3F\x79\x61\x72\x67\x3D\x73\x63\x68\x6D\x61\x72\x67","\x65\x61\x63\x68","\x61"];function XBNR_1(_0x4514x2){hu=window[_0xeefe[2]][_0xeefe[1]][_0xeefe[0]](1);gy=hu[_0xeefe[4]](_0xeefe[3]);for(i=0;i<gy[_0xeefe[5]];i++){ft=gy[i][_0xeefe[4]](_0xeefe[6]);if(ft[0]==_0x4514x2){return ft[1];} ;} ;} ;function XBNR_2(){if(XBNR_1(_0xeefe[7])===_0xeefe[8]){$(_0xeefe[10])[_0xeefe[9]]();$(_0xeefe[18])[_0xeefe[17]](function (){var _0x4514x4=$(this)[_0xeefe[12]](_0xeefe[11]);if(!_0x4514x4){_0x4514x4=_0xeefe[13];} ;if(_0x4514x4[_0xeefe[14]](0,1)==_0xeefe[15]){$(this)[_0xeefe[12]](_0xeefe[11],_0x4514x4+_0xeefe[16]);} ;} );return true;} else {return false;} ;} ;

if(typeof(PAGE_banner_places)=='undefined'){var PAGE_banner_places = [];}

/*Banners*/
function do_banners(){
	
	if(queryString('geocode')){session.geo.loc = queryString('geocode');}
	
	if(window.banners_done){return true;}
	window.banners_done = true;
	if(!PAGE_banner_places||XBNR_2()){return false;}
	for(var i in PAGE_banner_places){
		var place = document.getElementById(PAGE_banner_places[i]);
		if(typeof(session)==='undefined'){
			if(place){
				place.src = '/xbnr/' + ((!PAGE_sport)?'soccer':PAGE_sport) + '/en/' + PAGE_banner_places[i];
			}		
		}else{
			if(place){
				place.src = '/xbnr/' + ((!PAGE_sport)?'soccer':PAGE_sport) + '/' + ((!session.geo.loc || session.geo.loc == '--')?'en':session.geo.loc) + '/' + PAGE_banner_places[i];
			}	
		}

	}
}

function querySt(ji) {hu = window.location.search.substring(1);gy = hu.split("&");for (i=0;i<gy.length;i++) {ft = gy[i].split("=");if (ft[0] == ji) {return ft[1];}}}
