/*
 * $Id: main.js,v 1.1.6.11.2.26 2010-09-29 09:30:31 byoung Exp $
 * NextGen main.js
 * Copyright (c) 2010 Orbis Technology Ltd. All rights reserved.
 */

$(function() {
	if ($('#TreeView').length > 0){
		$("#TreeView").find("li").has(".selected").addClass("open");
		$("#TreeView").treeview({
			animated: "fast",
			collapsed: true
		});
	}

	addHandlers();

});

function addHandlers() {
	/* To be extended by Orbis */
	/* Interface controls */
	if ($('input.date-pick').length > 0){
		$('input.date-pick').datePicker(
			{
				startDate: '01/01/2007',
				endDate: (new Date()).asString()
			}
		);
		$('#period_start').bind(
			'dpClosed',
			function(e, selectedDates)
			{
				var d = selectedDates[0];
				if (d) {
					d = new Date(d);
					$('#period_end').dpSetStartDate(d.addDays(0).asString());
				}
			}
		);
		$('#period_end').bind(
			'dpClosed',
			function(e, selectedDates)
			{
				var d = selectedDates[0];
				if (d) {
					d = new Date(d);
					$('#period_start').dpSetEndDate(d.addDays(0).asString());
				}
			}
		);
	}
	$('#Body div.goodcauses li a').click(function(e){
		e.preventDefault();
		$(this).blur();
		
		$('#Body div.goodcauses div.toggle').hide();
		$('#Body div.goodcauses .' + $(this).attr('name')).show();
		
		$('#Body div.goodcauses li').removeClass('current');
		$(this).parent().addClass('current');
	});
	$('#Timeline h4').click(function(){
		if (!$(this).parent().hasClass('current')){
			$('#Timeline li').removeClass('current');
			$('#Timeline div').hide('fast');
			$(this).parent().find('div').show('fast');
			$(this).parents('li').addClass('current');
		}
	});
	$("#Account div.balance a").click(function(e) {
		e.preventDefault();
		$(this).parent("div").find("table").toggle();
		$(this).text($(this).text() == 'Show Balances' ? 'Hide Balances' : 'Show Balances');
		$(this).toggleClass('open');
	});
	$("div.findRadio input").focus(function(e) {
		$(this).parents("div.findRadio").find("input[name=qry_type]").attr("checked", "checked");
	});
	$("div.findRadio select").focus(function(e) {
		$(this).parents("div.findRadio").find("input[name=qry_type]").attr("checked", "checked");
	});
	$("div.findRadio a.dp-choose-date").focus(function(e) {
		$(this).parents("div.findRadio").find("input[name=qry_type]").attr("checked", "checked");
	});
	$("#Body form.lost h3.header").click(function(e) {
		if ($(this).parents("form.lost").hasClass("closed")){
			$(this).parents("div#Body").find("div.content").hide("fast");
			$(this).parents("div#Body").find("form.lost").addClass("closed");
			$(this).parents("form.lost").find("div.content").show("fast");
			$(this).parents("form.lost").removeClass("closed");
		}
	});
	$("#Body a.triggerPanel").click(function(e) {
		var el = "#" + $(this).attr("name");
		var close = true;
		if ($(el).hasClass('noClose')){
			close = false;
		}
		showPanel(e, el, close);
	});
	$("#helpMenu a").click(function(e) {
		e.preventDefault();
		
		$(this).parents("ul#helpMenu").find("li").removeClass("current");
		$(this).parents("li").addClass("current");
		$(this).blur();
		
		var el = "div#" + this.className;
		$(this).parents("div#video").find("div.helpContent").hide();
		$(this).parents("div#video").find(el).show();
	});

	/* Leaderboard */
	if ($('#Leaderboard').length > 0){
		$('#Leaderboard .show li:first').addClass('first');
		var SetTotal = function(){
			var total = $('#Leaderboard .show li').length;
			$('ul.paging span.total').text(total);
		};
		SetTotal();

		// remove paging hrefs if not needed
		$('ul.paging.show a').each(function (e){
			var total = $(this).parent().siblings('li.page').find('span.total').text();
			// always remove the first/prev. Remove the last/next only if needed
			if ((total == 1) || $(this).hasClass('first') || $(this).hasClass('previous')) $(this).addClass('unclickable');
			// Mantis 994 Hide First/Prev/Next/Last if only 1 page of results
			if (total <= 1) {
				$('ul.paging.show a.first').hide();
				$('ul.paging.show a.previous').hide();
				$('ul.paging.show a.last').hide();
				$('ul.paging.show a.next').hide();
			} else {
                $('ul.paging.show a.first').show();
                $('ul.paging.show a.previous').show();
                $('ul.paging.show a.last').show();
                $('ul.paging.show a.next').show();
			}
			// End Mantis 994
		});

		$('#Competition').change(function(){
	 		top.location = $('#Competition').val();
		});
		$('#Period').change(function(){
			$('#Leaderboard div.board').removeClass('show');
			var el = $(this).find('option:selected').val();
			$('#Leaderboard div.' + el).addClass('show');
			$('#Leaderboard .show li:first').addClass('first');
			SetTotal();

			$('#Sidebar div.boxer').removeClass('show');
			// Display same div for this/last months prizes
			if (el.match('(this|last)month')) el = 'thismonth';
			$('#Sidebar div.' + el).addClass('show');
			// MN Changes to remove paging panel when there are 
			// not ldrbrd results
			$('ul.paging').removeClass('show');
			var el = $(this).find('option:selected').val();
			var num = $('#Leaderboard div.board.show tr').length;
			if (num > 2) {
				$('ul.paging.' + el).addClass('show');
			}
			// END MN Changes

			// remove paging hrefs if not needed
			$('ul.paging.show a').each(function (e){
				var total = $(this).parent().siblings('li.page').find('span.total').text();
				// always remove the first/prev. Remove the last/next only if needed
				if ((total == 1) || $(this).hasClass('first') || $(this).hasClass('previous')) $(this).addClass('unclickable');
				// Mantis 994 Hide First/Prev/Next/Last if only 1 page of results
	            if (total <= 1) {
    	            $('ul.paging.show a.first').hide();
        	        $('ul.paging.show a.previous').hide();
            	    $('ul.paging.show a.last').hide();
                	$('ul.paging.show a.next').hide();
	            } else {
    	            $('ul.paging.show a.first').show();
        	        $('ul.paging.show a.previous').show();
            	    $('ul.paging.show a.last').show();
                	$('ul.paging.show a.next').show();
	            }
				// End Mantis 994
			});
			$('ul.paging.show span.current').text(1);
			
		});

		$('ul.paging a').click(function(e){
			e.preventDefault();
			$(this).blur();
			
			var first = $('#Leaderboard .show li:first').index();
			var last = $('#Leaderboard .show li:last').index();
			
			var li = $('#Leaderboard .show li:visible');
			var current = ($(li).index());
			
			var skip = false;
			if ((current == first && ($(this).hasClass('first') || $(this).hasClass('previous'))) || (current == last && ($(this).hasClass('next') || $(this).hasClass('last')))){
				skip = true;
			}
			
			if (!skip){
				$(li).hide();
				if ($(this).hasClass('first')){
					$('#Leaderboard .show li:first').show();
				} else if ($(this).hasClass('previous')){
					$(li).prev().show();
				} else if ($(this).hasClass('next')){
					$(li).next().show();
				} else if ($(this).hasClass('last')){
					$('#Leaderboard .show li:last').show();
				}
			}
			updatePaging();
		});

		$('#Leaderboard a.showUserPosition').click(function(e){
			e.preventDefault();
			var skips = $('#Leaderboard .show .skips').val()*1;
			if( $('ul.paging.show span.current').text() == (skips+1) ) {return;}
			for (i=0; i<skips; i++) {
				li = $('#Leaderboard .show li:visible');
				$(li).hide();$(li).next().show();
				$('ul.paging.show span.current').text(  ($('ul.paging.show span.current').text())*1+1  );
			}
			updatePaging();
		});
		
	}

	function updatePaging() {
		var current = ($('#Leaderboard .show li:visible').index() + 1);
		$('ul.paging span.current').text(current);

		if (current == 1) {
			$('ul.paging.show a.first')   .addClass('unclickable');
			$('ul.paging.show a.previous').addClass('unclickable');
		} else {
			$('ul.paging.show a.first')   .removeClass('unclickable');
			$('ul.paging.show a.previous').removeClass('unclickable');
		}

		if(current == $('ul.paging.show span.total').text() ){
			$('ul.paging.show a.last').addClass('unclickable');
			$('ul.paging.show a.next').addClass('unclickable');
		} else {
			$('ul.paging.show a.last').removeClass('unclickable');
			$('ul.paging.show a.next').removeClass('unclickable');
		}
	}
	
	/* Selected Games */
	/* Selected Games */
	var sHandle = 0;
	var sRunning = true;
	function startSelectedGamesCarousel(el){
		var sTimer = 100;
		var sStep = 50;
		var sCounter = 0;

		var controls = $(el).parents('li').find('.controls');
		var next_step = 1;
		var total_steps = $(el).attr('class').replace('c', '');
		var step_height = ($(el).find('li:first').outerHeight() * 2);
		var steps = [];
		for (var i = 0; i < total_steps; i++){
			steps[i] = -(step_height * i);
		}
		
		var slide = function(step){
			$(el).animate({'top' : steps[step - 1]}, 'fast');
			var li = $(controls).find('a.c' + step);
			if ($(li).length > 0){
				$(controls).find('a.c').removeClass('active');
				$(li).addClass('active');
			}
			sCounter = 0;
		};
		
		var autoslide = function(){
			if (sRunning){
				sCounter++;
				if (sCounter == sTimer){
					next_step++;
					if (next_step > total_steps || next_step < 1){
						next_step = 1;
					}
					slide(next_step);
				}
			}
		};
		
		var clickslide = function(step){
			next_step = step;
			slide(next_step);
		};
		
		$(el).hover(function(){
			sRunning = false;
		},function(){
			sRunning = true;
		});
		
		$('#SelectedGames div.controls a').click(function(e){
			e.preventDefault();
			$(this).blur();
			clickslide($(this).text());
		});
		
		sHandle = setInterval(autoslide, sStep);
	}
	function stopSelectedGamesCarousel(){
		clearInterval(sHandle);
		$('#SelectedGames div.carousel ul').each(function(){
			$(this).css('top', '0px');
		});
		$('#SelectedGames div.controls a.c').removeClass('active');
		$('#SelectedGames div.controls').each(function(){
			$(this).find('a:first').addClass('active');
		});
	}
	if ($('#SelectedGames').length > 0){
		var playMe = false;
		$('#SelectedGames div.carousel ul').each(function(){
			var lis = $(this).find('li').length;
			var count = Math.ceil(lis / 2);
			if (count != (lis / 2)){
				$(this).append('<li class="empty"></li>');
			}
			$(this).addClass('c' + count);
			for (var i = 0; i < count; i++){
				$(this).parents('li').find('.controls').append('<a class="c c' + (i + 1) + '" href="#"><b>' + (i + 1) + '</b></a>');
			}
			$(this).parents('li').find('.controls a:first').addClass('active');
			if ($(this).parents('li').hasClass('open')){
				playMe = $(this);
			}
		});
		
		startSelectedGamesCarousel(playMe);
	}
	$("#SelectedGames span").click(function(e) {
		e.preventDefault();
		$(this).blur();
		
		if (!$(this).parent('li').hasClass("open")){
			stopSelectedGamesCarousel();
			
			$(this).parents('ul').find('div').slideUp('fast');
			$(this).parents('ul').find('li').removeClass("open");
			$(this).parent('li').addClass("open").find('div').slideDown('fast');
			
			startSelectedGamesCarousel($(this).parent('li').find('ul'));
		}
	});
	
	/* Latest Winners */
	$('#LatestWinnersTable select').change(function(){
		$('#LatestWinnersTable table').removeClass('show');
		var el = $(this).find('option:selected').val();
		$('#LatestWinnersTable table.' + el).addClass('show');
	});
	if ($('#Winners').length > 0){
		$("#Winners .carousel li a").each(function(){
			var bg = $(this).find('b').html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
			$(this).css('background-image', 'url('+SA_GIF_URL+'/winners/small/' + bg + '.jpg)');
		});
		var wTimer = 200;
		var wStep = 200;
		var wRunning = true;
		var wCounter = 0;
		var wHandle = 0;
		var doubleWin = function(){
			if (wRunning){
				wCounter++;
				if (wCounter == wTimer){
					clearInterval(wHandle);
					wCounter = 0;
					carousel.next();
				}
			}
		};
		$("#Winners .carousel").hover(function(){
			wRunning = false;
		}, function() {
			wRunning = true;
		});
		function winners_initCallback(carousel, state){
			$('#Winners div.carousel li').each(function(index){
				$(this).find('a').prepend('<b>' + index + '</b>');
			});
			$('#Winners div.carousel a').click(function(e) {
				e.preventDefault();
				clearInterval(wHandle);

				if ($(this).hasClass('previous')){
					carousel.prev();
				} else if ($(this).hasClass('next')) {
					carousel.next();
				} else {
					carousel.scroll($.jcarousel.intval($(this).find('b').text()) + 1);
				}
			});
			wCounter = 0;
			wHandle = setInterval(doubleWin, wStep);
		}
		function winners_itemVisibleInCallback(carousel, item, i, state){
			wCounter = 0;
			wHandle = setInterval(doubleWin, wStep);

			var name = $(item).find('.caption b').html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
			$('#Winners h3').text($(item).find('.header').text());
			$('#Winners blockquote p').text($(item).find('.quote').text());
			$('#Winners div.polaroid img').attr('src', SA_GIF_URL+'/winners/large/' + name + '.jpg');
			$('#Winners div.polaroid span').html($(item).find('.caption').html());
		}
		$('#Winners div.carousel ul').jcarousel({
			scroll: 1,
			wrap: 'circular',
			buttonNextHTML: null,
			buttonPrevHTML: null,
			initCallback: winners_initCallback,
			itemFirstInCallback: winners_itemVisibleInCallback
		});
		var carousel = jQuery('#Winners div.carousel ul').data('jcarousel');
	}
	if ($('#LatestWinners').length > 0){
		var timerLatestWinners = false;
		var startLatestWinners = function(el){
			var lwSpeed = 3000;
			var lwHeight = $(el).find('li:first').outerHeight();
			var lwSlide = function(){
				$(el).animate({'top' : -lwHeight}, 'slow', function(){
					if ($(el).children().size() > 1) {
						$(el).find('li:last').after($(el).find('li:first'));
					}
					$(el).css({'top' : '0px'});
				});
			};
			
			timerLatestWinners = setInterval(lwSlide, lwSpeed);
			
			$(el).hover(function(){
				clearInterval(timerLatestWinners);
			},function(){
				timerLatestWinners = setInterval(lwSlide, lwSpeed);
			});
		};
		startLatestWinners('#LatestWinners ul');
	}

	/* Main Cross Fader Banner */
	if ($('#CrossFader').length > 0){
		var cTimer = 100;
		var cStep = 50;
		var cRunning = true;
		var cCounter = 0;
		var cHandle = 0;
		var doubleCross = function(){
			if (cRunning){
				$("#CrossFader .controls .load").reportprogress(++cCounter);
				if (cCounter == cTimer){
					clearInterval(cHandle);
					cCounter = 0;
					$('#CrossFader ul').cycle('next');
				}
			}
		};
		var cross_before = function(){
			$("#CrossFader div.controls i").css("width", "0");
			cCounter = 0;
			cHandle = setInterval(doubleCross, cStep);
		};
		var cross_controls = function(idx, slide) {
			return '<a href="#"><i></i><b>' + (idx + 1) + '</b></a>';
		};
		var cross_click = function(){
			clearInterval(cHandle);
		};
		$("#CrossFader").hover(function(){
			cRunning = false;
		}, function() {
			cRunning = true;
		});
		$('#CrossFader ul').after('<div class="controls">').cycle({
			timeout: 0,
		    pager:  '#CrossFader div.controls',
		    activePagerClass: 'load',
		    pagerAnchorBuilder: cross_controls,
		    pagerClick: cross_click,
		   	before: cross_before
		});
	}


	
	/* Available to Play Now */
	if ($('#PlayNow').length > 0){
		$("#PlayNow ul.carousel strong").each(function(){
			var bg = $(this).html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
			$(this).parent("a").css('background-image', 'url('+SA_GIF_URL+'/hp_games/' + bg + '.jpg)');
		});
		var count = Math.ceil($('#PlayNow ul.carousel li').length / 4);
		for (i = 0; i < count; i++){
			var y = i * 4 + 1;
			$('#PlayNow ul.controls li.next').before('<li class="c c' + y + '"><a href="#">' + y + '</a></li>');
		}
		function playnow_initCallback(carousel, state){
			$('#PlayNow ul.controls a').click(function(e) {
				e.preventDefault();
				
				if ($(this).parent('li').hasClass('previous')){
					carousel.prev();
				} else if ($(this).parent('li').hasClass('next')) {
					carousel.next();
				} else {
					carousel.scroll($.jcarousel.intval($(this).text()));
				}
			});
			
			carousel.clip.hover(function() {
				carousel.stopAuto();
			}, function() {
				carousel.startAuto();
			});
		}
		function playnow_itemVisibleInCallback(carousel, item, i, state, evt){
			var li = '#PlayNow ul.controls li.c' + i;
			if ($(li).length > 0){
				$('#PlayNow ul.controls li.c').removeClass('active');
				$(li).addClass('active');
			}
		}
	    $('#PlayNow ul.carousel').jcarousel({
	        scroll: 4,
	        wrap: 'both',
	    	buttonNextHTML: null,
	    	buttonPrevHTML: null,
	        initCallback: playnow_initCallback,
	        itemVisibleInCallback: playnow_itemVisibleInCallback
	    });
	}
	
	/* Swap Banners */
	if ($("#SelectedGames").length > 0){
		$("#SelectedGames div.carousel span").each(function(){
			var bg = $(this).html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
// 			$(this).parent("a").find('em').css('background-image', 'url('+SA_GIF_URL+'/instantwins/64x52/' + bg + '.jpg)');
		});
	}
	if ($("div.swapbanner").length > 0){
		$("div.swapbanner h1").each(function(){
			var bg = $(this).html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
			// SA_GIF_URL is handed from the template player elsewhere
			$(this).parent("div.swapbanner").css('background-image', 'url('+SA_GIF_URL+'/banner_headers/swap_' + bg + '.jpg)');
		});
	}
	if ($("div.categories dl").length > 0){
		$("div.categories dd a").each(function(){
			var bg = $(this).html().replace(/<(B|b)[^>]*>[^<]*(<\/B>|<\/b>)/ig,"").replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
	//		$(this).find("b").css('background-image', 'url('+SA_GIF_URL+'/instantwins/110x90/' + bg + '.jpg)');
		});
	}
	if ($("body.instantwins ul.games li.game").length > 0){
		$("body.instantwins ul.games li.game h3").each(function(){
			var bg = $(this).html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
	//		$(this).parent('.game').find(".header").css('background-image', 'url('+SA_GIF_URL+'/instantwins/180x90/' + bg + '.jpg)');
		});
	}
	if ($("body.lotteries ul.games li.game").length > 0){
		$("body.lotteries ul.games li.game h3").each(function(){
			var bg = $(this).html().replace(/\s+/g, '-').replace(/\'/g, '').toLowerCase();
			$(this).parent('.game').find(".header").css('background-image', 'url('+SA_GIF_URL+'/lotteries/' + bg + '.jpg)');
		});
	}


	$('ul.result div.header a').click(function(e){
		// Depricated function kept for reference.
		return;
		// Do an ajax call to get the result
		if ($(this).attr('href')){
			eval($(this).attr('href').split('javascript:')[1]);
		}

		e.preventDefault();
		$(this).blur();
	
		var skip = false;
		if (($(this).parents('li:first-child').length > 0 && $(this).hasClass('next')) || ($(this).parents('li:last-child').length > 0 && $(this).hasClass('previous'))){
			skip = true;
		}

		if (!skip){
			$(this).parent('li').hide();
			if ($(this).hasClass('next')){
				$(this).parent('li').prev().show();
			} else {
				$(this).parent('li').next().show();
			}
		}
	});
	$('div.promotionTable div.header a').click(function(e){
		e.preventDefault();
		$(this).blur();
		
		$(this).parents('div.promotionTable').find('table').toggle('fast');
		$(this).parents('div.promotionTable').toggleClass('open');
		$(this).text($(this).text() == 'Show Details' ? 'Hide Details' : 'Show Details');
	});
	$('body.promotions #Body div.promotion div.section h3 b').click(function(){
		//$(this).parents('.section').find('ul').toggle('fast');
		//$(this).parents('.section').toggleClass('closed');
	});
	$('a.switch').click(function(e) {
		e.preventDefault();
		
		var el = '#' + $(this).attr('name');
		
		$(this).parents('a.switch').hide();
		$(el).show();
	});
	$("#TreeView span").click(function(e) {
		e.preventDefault();
		$(this).blur();
		
		if ($(this).parent("li").hasClass("open") || $(this).parent("li").hasClass("expanded")) {
			$(this).parent('li').find('ul:first').slideUp('fast');
			$(this).parent('li').removeClass("open").removeClass("expanded");
		} else {
			$(this).parent('li').addClass("expanded").find('ul:first').slideDown('fast');
		}
	});

}

function initValidation(){
	var LoginForm = document.getElementById('Login');
	if (LoginForm){
		$("#Login").validate({
			rules: {
				username: {
					required: true,
					rangelength: [2, 20]
				},
				pwd: {
					required: true,
					rangelength: [2, 20]
				}
			},
			messages: {
				username: "",
				pwd: ""
			}
		});
	}
}


/*
 * Copyright (c) 2007 Josh Bush (digitalbush.com)
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE. 
 */
 
/*
 * Progress Bar Plugin for jQuery
 * Version: Alpha 2
 * Release: 2007-02-26
 */ 
(function($) {	
	//Main Method
	$.fn.reportprogress = function(val,maxVal) {			
		var max=100;
		if(maxVal)
			max=maxVal;
		return this.each(
			function(){		
				var div=$(this);
				var innerdiv=div.find("i");
				var width=Math.round(val/max*100);
				innerdiv.css("width",width+"%");	
			}
		);
	};
})(jQuery);





// Do a call to check if the login cookie is valid
doCookieCheck = function () {
	var url = "?action=GoVerifyLogin";
	var r = SA_singleton_request_broker.instance();
	r.send( {
			'priority': 0,
			'method' : 'GET',
			'url' : url,
			'callback': cookieCheckCallback,
			'debug' : true
		} ); 
}

cookieCheckCallback = function (response) {
	var ret_val = response.responseText;
	if (ret_val == "ERR") {
		window.location = "?action=GoAcctHome&login_timeout=1";
	} else {
	}
}

// Do the cookie check once per minute
startCookieCheck = function () {
	setTimeout(function() {
		doCookieCheck();

		setTimeout(arguments.callee, 60000);
	},60000);
}

submitLoginForm = function (source) {
	source.disabled = true;
	source.form.submit();
}


