/*
 * $Id: main.js,v 1.48 2011-06-27 13:35:02 pmiller Exp $
 * SingleAccount main.js
 * Copyright (c) 2010 Orbis Technology Ltd. All rights reserved.
 */


$(function() {
	
	css_browser_selector(navigator.userAgent);
	
	if ($('table.piechart').length > 0){
		$('table.piechart')
			.visualize({type: 'pie', appendKey: false, appendTitle: false, pieMargin: 0, height: 64, width: 64, colors: ['#99cc00','#3399ff','#e22018']})
			.trigger('visualizeRefresh');	
	}
	SA_addHandlers();

	if (!$('html').hasClass('ie6')){
		$("a").simpletooltip();
		$("i").simpletooltip();
		$("th").simpletooltip();
		$("button").simpletooltip();
		$("span.tooltip").simpletooltip();
		$("div.game > form > div.header > h3").simpletooltip();
		$("div.coupon input").simpletooltip();
	}
});

/*
 * Gets the coupon that contains the given element.
 */
function getCouponForElement(ele) {
	return SA_coupons[$(ele).parents(".game")[0].id];
}

/*
 * Context specifies as a string where to look for elements to apply the click
 * handlers to. Defaults to the root element if not specified.
 * Example: addHandlers("#cpn_452") will add handlers to coupon 452's
 * children.
 */
function SA_addHandlers(context) {
	if (!context)
		context = "";
	// Add event listeners for coupon stats
	//
	//console.log("SA_addHandlers("+context+")");
	$(context + ' div.flyBtnWrap > a.flyBtn').click(function(e) {
		e.preventDefault();
		$(this).blur();
		if ($(this).hasClass('betslip_trigger') && SA_betslip_obj.checkBetSlipCount(true) == 0) {
			alert("You currently do not have any bets on your bet slip.");
		}
		if ($(this).hasClass('betslip_trigger') && SA_betslip_obj.checkBetSlipCount(true) > 0 || !$(this).hasClass('betslip_trigger')) {
			if (!$(this).hasClass('inactive')){
				if ($(this).parents('#Body div.flyWrap').hasClass('open')){
					$('#Body div.flyWrap').removeClass('open');
					if (($('html').hasClass('ie6') || $('html').hasClass('ie7')) && $(this).parents('#Body div.game').hasClass('submitted')){
						$(this).parents('#Body div.game').find('#Body div.submittedCounter b').show();
					}
				} else {
					$('#Body div.flyWrap').removeClass('open');
					if (($('html').hasClass('ie6') || $('html').hasClass('ie7')) && $(this).parents('#Body div.game').hasClass('submitted')){
						$(this).parents('#Body div.game').find('#Body div.submittedCounter b').hide();
						
					}
					$(this).parents('#Body div.flyWrap').addClass('open');
					if ($(this).parents('#Body div.flyWrap').hasClass('stats') && $(this).parents('div.stats').find('div.predictions table.s1').length > 0){
						var el = $(this).parents('div.stats').find('div.predictions table.s1');
						renderStats(el);
					}
				}
			}
		}
	});

	var start_time = new Date().getTime();
	$(context + ' div.flyBtnWrap > div.flyOver a.flyClose').click(function(e) {
		e.preventDefault();
		if (($('html').hasClass('ie6') || $('html').hasClass('ie7')) && $(this).parents('#Body div.game').hasClass('submitted')){
			$(this).parents('#Body div.game').find('#Body div.submittedCounter b').show();
		}
		$('#Body div.flyWrap').removeClass('open');
	});

	var end_time = new Date().getTime();
	$(context + ' .stats a').click( function() {
		if ( $(this).siblings('input[name=hasStats]').val() != 'true' ) {
			$(this).siblings('input[name=hasStats]').attr('value', 'true');
			SA_request_statistics ( $(this).siblings('input[name=sort]'    )  .val() ,
						$(this).siblings('input[name=saxgame_id]').val() );
		}
	});

	// Matches the last 2 (underscore separated) chunks 
	$(context + " form.box.TCH div.view.full div.wrap > table > tbody > tr > td > input:checkbox").click(function (e) {
		// Regex to pull the row and column values for this checkbox to let us
		// wrap the click into the standard javascript call
		var coupon = getCouponForElement(this);
		var prefix = coupon.subview_states.prefix;
		idRegex = new RegExp("^DATA_"+prefix+"([^_]+)_.*_([0-9]+)_([0-9]+)$");
		var match = this.id.match(idRegex);
		var subview = match[1];
		var x = match[2];
		var y = match[3];
		if (!coupon.tchFullViewClick(subview, x, y)) {
			e.preventDefault();
		}
	});

	$(context + " a.subsAcceptBtn").click(function (e) {
		e.preventDefault();
		getCouponForElement(this).updateSubscriptionCount();
		$("#Body div.flyWrap").removeClass("open");
	});
	$(context + " a.subsCancelBtn").click(function (e) {
		e.preventDefault();
		getCouponForElement(this).resetSubscriptionCountSelection();
		$("#Body div.flyWrap").removeClass("open");
	});
	$(context + " table.subs a.flyClose").click(function (e) {
		e.preventDefault();
		$(".flyWrap").removeClass("open");
	});
	/* To be extended by Orbis */
	$(context + ".game fieldset input:radio").click(function(e) {

		var sourceInfo = this.id.match(".*-(.*)-(.*)-.*");
		var success = false;
		if (sourceInfo != null) {
			var plan_id = sourceInfo[1];

			var success = getCouponForElement(this).switchPlan(plan_id);

		}
		if (!success) {
			printfire("Invalid ID for source element.");
			e.preventDefault();
		}
	});
	$(context + ".game button:reset").click(function(e) {

		e.preventDefault();
		$(this).parents('form')[0].reset();
	});

	// This code will cause the betslip button to flash for a few seconds. It
	// could be used when a bet is added to the betslip. Currently it is *NOT* used.
	$("#Body div.game div.footer button.addToSlip").click(function(e) {
		e.preventDefault();
		
		if (!$('#Body div.betslip').hasClass('open')){
			var el = $('#Body div.betslip div.flyBtnWrap a');
			$(el).animate({
				opacity: 0.1
			}, 150, function() {
				$(el).animate({
					opacity: 1
				}, 150, function() {
					$(el).animate({
						opacity: 0.1
					}, 150, function() {
						$(el).animate({
							opacity: 1
						}, 150);
					});
				});
			});
		}
	});
	
	/* Interface controls */
	$(context + " a.switch").click(function(e) {
		e.preventDefault();
		
		var el = '#' + $(this).attr('name');
		
		$(this).parents('.switch').hide();
		$(el).show();
	});
	$(context + " .tooltip").hover(function(e) {
		$(this).find("span").fadeIn("fast");
	}, function(){
		$(this).find("span").hide();
	});
	$(context + " div.flyWrap div.plans select").click(function(e) {
		$(this).parents("form.common").find("label").removeClass("active");
		$(this).parents("p").find("label").addClass("active");
		var select_type_input = $(this).parents("div.inner").find("input[name=plan_select_type]")[0];
		var select_name = $(this).parents("p").find("select")[0].name;
		select_type_input.value = select_name;
	});
	$(context + " div.flyWrap div.plans p.butts a.loadPlanButton").click(function (e) {
		printfire(e);
		e.preventDefault();
		$("div.flyWrap").removeClass("open");
		this.blur();
		var select_type_input = $(this).parents("div.inner").find("input[name=plan_select_type]")[0];
		var select_type = select_type_input.value;
		var parent = $(this).parents("div.inner");
		var search_string = "select[name="+select_type+"]";
		var plan_select = parent.find(search_string)[0];
		var success = getCouponForElement(this).switchPlan(plan_select.value);
	});
	$(context + " div.flyWrap div.plans p.butts a.cancelPlanSelButton").click(function (e) {
		printfire(e);
		e.preventDefault();
		$("div.flyWrap").removeClass("open");
		this.blur();
	});
/*	$(context + " .classicpools .full input").click(function(e) {

		$(this).parents("div.view").find("table").each(function(){
			if (!$(this).hasClass('plans')){
				$(this).removeClass();
			}
		});
		$(this).parents("div.view").find("table").removeClass();
		$(this).parents("div.view").find("table").addClass($(this).parents("td").attr('class'));
	});*/
	$(context + " a.btnExpand").click(function(e) {
		e.preventDefault();
		$(this).blur();
		
		var parent = $(this).parents("div.game");
		var width = $("#Body div.ghost.c1x1").css("width");
		var height = $("#Body div.ghost.c1x1").css("height");
		
		if (!$(parent).hasClass("full")){
			if ($(parent).hasClass("expandTo2x1")){
				width = $("#Body div.ghost.c2x1").css("width");
				height = $("#Body div.ghost.c2x1").css("height");
			} else if ($(parent).hasClass("expandTo3x1")){
				width = $("#Body div.ghost.c3x1").css("width");
				height = $("#Body div.ghost.c3x1").css("height");
			} else if ($(parent).hasClass("expandTo2x2")){
				width = $("#Body div.ghost.c2x2").css("width");
				height = $("#Body div.ghost.c2x2").css("height");
			} else if ($(parent).hasClass("expandTo3x2")){
				width = $("#Body div.ghost.c3x2").css("width");
				height = $("#Body div.ghost.c3x2").css("height");
			}
			$(parent).addClass("full");
		} else {
			$(parent).removeClass("full");
		}
		expandCoupon(parent, width, height);
		
		$(this).text($(this).text() == 'Expand' ? 'Minimise' : 'Expand');
	});
	$(context + ".game ul.views a").click(function(e) {
		switch_view_tab(e, this);
	});
	$(context + ".game ul.tabs a").click(function(e) {
		e.preventDefault();
		$(this).blur();
		
		$(this).parents("ul").find("li").removeClass("current");
		$(this).parents("li").addClass("current");
		
		var el = 'div.coupon';
		if ($(this).hasClass('rules')){
			el = 'div.rules';
		}
		$(this).parents("form").find("div.toggle").hide();
		$(this).parents("form").find(el).show();
		// Orbis change: hide coupon controls
		if ($(this).hasClass("rules")) {
			$(this).parents("form").find("div.footer").hide();
		} else {
			$(this).parents("form").find("div.footer").show();
		}
	});
	$(context + ".game li.actionLuckyDip a").click(function(e) {
		e.preventDefault();
		SA_luckyDip(e, $(this).parents("div.game"));
	});
	$(context + ".game li.actionReset a").click(function(e) {
		e.preventDefault();
		SA_clearCoupon(e, $(this).parents("div.game"));
	});

	$(context + ".game div.stats select.fixtureDrop").change(function(){
		var target = "div.predictions table." + $(this).attr('value');
		var el = $(this).parents("div.stats").find(target);
		renderStats(el);
	});
	$(context + ".game div.stats > div.flyBtnWrap > a.action").click(function(e){
		e.preventDefault();
		$(this).blur();
		
		$(this).parents('.flyOver').toggleClass('details');
	});

/*	$(context + ".hideConfirmation").click(function(e) {
		e.preventDefault();
		$(this).parents("div.confirmation").hide('fast');
	});
	$(context + "#HideAlert").click(function(e) {
		e.preventDefault();
		$("#Alert").hide('fast');
	});*/
	if (typeof(SA_fixIE6) != "undefined") {
		SA_fixIE6(context);
	}
	if (typeof(SA_refreshCouponBetCounts) != "undefined")
		SA_refreshCouponBetCounts();
}

function renderStats(el){
	$('.visualize').remove();

	if ($(el).parent().hasClass('pie')){
		$(el)
			.visualize({type: 'pie', appendTitle: false, pieMargin: 0, pieLabelPos: 'inside', height: 70, width: 70, colors: ['#e22018','#3399ff','#ffcc00','#99cc00','#cc00cc', '#3300cc']});
	} else {
		$(el)
			.visualize({type: 'bar', appendTitle: true, height: 60, width: 210, barGroupMargin: 1, barMargin: 1, colors: ['#3399ff','#3399ff','#3399ff','#3399ff','#3399ff','#e22018','#e22018','#e22018','#e22018','#e22018']});
	}
}

function expandCoupon(el, width, height){
	$(el).animate({
		width: width,
		height: height
	}, "fast", "swing" );
}

function showPanel(e, panel, close){
	e.preventDefault();
	$(panel).modal({
		overlay:40,
		close:close,
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.fadeIn('fast');
				dialog.data.fadeIn('fast');
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('slow');
			dialog.container.fadeOut('fast', function () {
				dialog.overlay.fadeOut('fast', function () {
					$.modal.close();
				});
			});
		}
	});
}
function showPanelNoEvent(panel, close) {
	$(panel).modal({
		overlay:40,
		close:close,
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.fadeIn('fast');
				dialog.data.fadeIn('fast');
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('slow');
			dialog.container.fadeOut('fast', function () {
				dialog.overlay.fadeOut('fast', function () {
					$.modal.close();
				});
			});
		}
	});
}

function luckyDip(e, form){
}
function makeSelected(e){
	
}
/*
CSS Browser Selector v0.3.5 (Feb 05, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors

Altered by Andy Moreno to spit out Firefox 3.0 separately
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.0')?g+' ff3 ff3_0':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);
/**
*
*	simpleTooltip jQuery plugin, by Marius ILIE
*	visit http://dev.mariusilie.net for details
*
**/
(function($){ $.fn.simpletooltip = function(){
	return this.each(function() {
		var text = $(this).attr("title");
		if(text.length > 0) {
			$(this).hover(function(e){
				var tipX = e.pageX + 12;
				var tipY = e.pageY + 12;
				$(this).attr("title", ""); 
				$("body").append("<div id='simpleTooltip' style='position: absolute; z-index: 100; display: none;'>" + text + "</div>");
				if($.browser.msie) var tipWidth = $("#simpleTooltip").outerWidth(true)
				else var tipWidth = $("#simpleTooltip").width()
				$("#simpleTooltip").width(tipWidth);
				$("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("fast");
			}, function(){
				$("#simpleTooltip").remove();
				$(this).attr("title", text);
			});
			$(this).mousemove(function(e){
				var tipX = e.pageX + 12;
				var tipY = e.pageY + 12;
				var tipWidth = $("#simpleTooltip").outerWidth(true);
				var tipHeight = $("#simpleTooltip").outerHeight(true);
				if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
				if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
				$("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("fast");
			});
		}
	});
}})(jQuery);


function switch_view_tab(e,ele) {
	e.preventDefault();
	$(ele).blur();
	
	var game = $(ele).parents("div.game");
	var cpn_object = getCouponForElement(ele);
	var li = $(ele).parents("li");
	var newClass = "";
	var newView = "";
	var quick = 0;

	if ($(li).hasClass("full")) {
		newClass = "full";
	} else if ($(li).hasClass("numbers")) {
		newClass = "numbers";
	} else {
		newClass = "fixtures";
	}

	if (newClass == "full") {
		newView = "full_A";
	} else {
		newView = newClass;
	}

	var view_changed = cpn_object.changeView(newView);

	if (!view_changed) {
		return;
	}

	cpn_object.cur_view = newView;
	if ($('html').hasClass('ie6')) quick = 1;
	cpn_object.changeTab(newClass,quick);
}


