function count() {
	var $count = 0;
	var $tickets = 0;
	var $friends = 0;
	$('.count').each(function(){
		if (this.innerHTML.indexOf('tickets') > 0) {
			$count++;
			var $no = (this.innerHTML.substr(0,this.innerHTML.indexOf(' '))*1);
			$tickets = $tickets + $no;
		} else if (this.innerHTML.indexOf('friends') > 0) {
			var $no = (this.innerHTML.substr(0,this.innerHTML.indexOf(' '))*1);
			$friends = $friends + $no;
		}
	});
	if ($count > 0) {
		alert("Players: "+$count+"\nTickets: "+$tickets+"\n\nTotal Friends: "+$friends);
	}
}

function die() {
	if (typeof FeatureTimer != "undefined") {
		window.clearInterval(FeatureTimer);
	}
	ticker.kill();
	return true;
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
}

function URLDecode (encodedString) {
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	return output;
}

function gotoURL() {
	url = URLDecode(getQueryVariable('url'));
	window.location = url;
}

function increaseTime() {
	// do the time bit first
	var time = {
		hour: $('#current-time span.hour').text(),
		minutes: $('#current-time span.minute').text(),
		ampm: $('#current-time span.meridian').text()
	}
	time.minutes++;
	if (time.minutes == 60) {
		time.minutes = 0;
		time.hour++;
		if (time.hour == 12 && time.ampm == 'PM') {
			time.hour = 0;
			time.ampm = 'AM';
		} else if (time.hour == 12) {
			time.ampm = 'PM';
		} else if (time.hour == 13) {
			time.hour = 1;
		}
	}
	time.minutes = (time.minutes < 10) ? '0'+time.minutes : time.minutes;
	$('#current-time span.hour').text(time.hour);
	$('#current-time span.minute').text(time.minutes);
	$('#current-time span.meridian').text(time.ampm);
	// do the countdown
	var countdown = {
		days: $('#current-time span#countdown-days').text(),
		hours: $('#current-time span#countdown-hours').text(),
		minutes: $('#current-time span#countdown-minutes').text()
	}
	countdown.minutes--;
	if (countdown.minutes < 0) {
		countdown.minutes = 59;
		countdown.hours--;
		if (countdown.hours < 0) {
			countdown.hours = 23;
			countdown.days--;
		}
	}
	if (countdown.days == 0 && countdown.hours == 0 && countdown.minutes == 0) {
		countdown.days = 7;
	}
	$('#current-time span#countdown-days').text(countdown.days);
	$('#current-time span#countdown-hours').text(countdown.hours);
	$('#current-time span#countdown-minutes').text(countdown.minutes);
}

function dotime() {
	var speed = 600;
	var $active = $('#current-time li.active');
	if ( $active.length == 0 ) {
		$active = $('#current-time li:last');
	}
	var $next = $active.next().length ? $active.next() : $('#current-time li:first');
	$active.removeClass('active').fadeOut(speed,function() {
		increaseTime();
		$next.fadeIn(speed).addClass('active');
	});
}

function showSpinner(el) {
	el = document.getElementById(el);
	if ($(el).html() == '') {
		$(el).hide().html('<img src="/img/loading.gif" alt="loading" />').slideDown("slow");
	} else {
		$(el).fadeOut("fast",function(e){
			$(this).html('<img src="/img/loading.gif" alt="loading" />').fadeIn("fast");
		});
	}
}

function updateSurchargePanel(val,el) {
	el = document.getElementById(el);
	var refreshLink = '<a href="#" onclick="return false;"><img src="/img/switch.gif" alt="refresh" style="display: inline; float: none; vertical-align: middle; margin: 0 0 0 10px;" /></a>';
	if (val.substr(0,9) == 'Surcharge') {
		val = val.substr(9);
	}
	if ($(el).html() == '') {
		$(el).hide().html(val).slideDown("slow");
	} else if ($(el).html() == val) {
		return true;
	} else {
		$(el).fadeOut("slow",function(e) {
			$(this).html(val + ' ' + refreshLink).fadeIn("slow");
		});
	}
	return true;
}

function setUpInputs(){
	$("div.field").find("input, textarea, select").focus(function(e){
		var div = $(this).parents("div.field");
		if ($(div).hasClass("error")) {
			$(div).addClass("activeError");
		} else {
			$(div).addClass("active");
		}
		return true;
	}).blur(function(e) {
		$(this).parents("div.field").removeClass("active activeError");
	});
}

function changeFeature() {
	FeatureRunning = true;
//	FeatureTimer = window.setTimeout("changeFeature()",$speed+1000);
	var $active = $('#feature-rotator li.active');
	if ( $active.length == 0 ) {
		$active = $('#feature-rotator li:last');
	}
	var $next = $active.next().length ? $active.next() : $('#feature-rotator li:first');
	$active.addClass('last-active').removeClass('active');
	$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
		$active.removeClass('active last-active');
		FeatureRunning = false;
	});
}

function setUpInputTabs() {
	if (null != document.getElementById('super-play-box')) {
		$inputs = document.getElementById('super-play-box').getElementsByTagName('table')[0].getElementsByTagName('input');
	} else if ( null != document.getElementById('play-box-new')) {
		$inputs = document.getElementById('play-box-new').getElementsByTagName('table')[0].getElementsByTagName('input');
	}
	if ($inputs.length > 0) {
		$($inputs).keyup(function(e) {
			if (((48 <= e.keyCode) && (e.keyCode <= 57)) || ((96 <= e.keyCode) && (e.keyCode <= 105))) {
				var maxlength = jQuery(this).attr('maxlength'); // get maxlength value
				var inputlength = jQuery(this).val().length; // get the length of the text
				if ( inputlength >= maxlength ){ // if the text is equal of more than the max length
					$($inputs).eq($($inputs).index(this)+1).focus();
				}
			} else {
				$(this).val('');
			}
		});
		$($inputs).keypress(function(e) {
			switch(e.keyCode){
				// ignore the following keys
				case 8: // backspace - tab backwards
					$($inputs).eq($($inputs).index(this)-1).focus();
					return false;
				case 9: // tab
					e.preventDefault()
					return false;
				case 16: // shift
					return false;
				case 20: // capslock
					return false;
			}
		});
	}
}

function setupQuickLogin() {
	$('#header-login input.password').parents('label').append('<input type="text" id="passwordPlaceHolder" value="password" style="display: none; color: #333;" />');
	if ($('#header-login input.password').val() == '' || $('#header-login input.password').val() == 'password') {
		$('#header-login input.password').hide();
		$('#header-login input#passwordPlaceHolder').show();
	}
	$('#header-login input#passwordPlaceHolder').focus(function() {
		$('#header-login input.password').show().focus().val('');
	});
	$('#header-login input.password').focus(function() {
		$('#header-login input#passwordPlaceHolder').hide();
	}).blur(function() {
		if ($(this).val() == '' || $(this).val() == 'password') {
			$(this).hide();
			$('#header-login input#passwordPlaceHolder').show();
		}
	});
	$('#header-login input.username').focus(function() {
		if ($(this).val() == 'username') {
			$(this).val('').css({color: '#000'});
		}
	}).blur(function() {
		if ($(this).val() == 'username' || $(this).val() == '') {
			$(this).val('username').css({color: '#333'});
		}
	}).css({color: '#333'});
}

ticker = {
	speed: 50,
	delay: 4000,
	cache: 15, // how many items to get from JSON at once
	cached: null,
	timer: null,
	item: null,
	letters: 'start',
	strings: [],
	prefixs: [],
	prefix: null,
	string: null,
	parseJSON: function(data) {
		if (data.winners.length > 0) {
			$.each(data.winners,function(i,winner){
				if (winner) {
					switch(winner.currency) {
	//					case "GBP": var currency = "£"; break;
						default: var currency = "£"; var amount = winner.amount * 0.75; break;
					}
					ticker.prefixs[i] = "<strong>Winner!</strong> ";
					ticker.strings[i] = winner.name +" won "+ currency + amount.toFixed(2) +" in the last Happi 6 game";
				}
			});
			ticker.cached = data.winners.length;
			ticker.item = 0;
			ticker.setItem();
			$('#news-winners ul').empty().append('<li>'+ ticker.prefix +'</li>');
			ticker.timer = window.setTimeout(ticker.go,ticker.speed);
		}
	},
	go: function() {
		if (ticker.letters == 'start') { // get new story
			if (null == ticker.item || ticker.item >= ticker.cached) { // need more stories
//			if (ticker.item >= ticker.cache || null == ticker.item) { // need more stories
				ticker.strings = [];
				ticker.prefixs = [];
				$.getJSON("/scripts/Winners.aspx?q="+ticker.cache, function(data) { ticker.parseJSON(data); });
//				$.getJSON("/scripts/data.js?q="+ticker.cache, function(data) { ticker.parseJSON(data); });
			} else if (ticker.item >= ticker.cache) {
				ticker.kill();
			} else { // pick next story
				ticker.setItem();
				ticker.go();
			}
		} else if (ticker.string.length < ticker.letters) { // string complete - start again :)
			ticker.letters = 'start';
			ticker.timer = window.setTimeout(ticker.go,ticker.delay);
		} else {
			ticker.add();
		}
	},
	add: function() {
		$('#news-winners li').html(ticker.prefix + ticker.string.substring(0,ticker.letters).replace('€','&euro;').replace('£','&pound;'));
		ticker.letters++;
		ticker.timer = window.setTimeout(ticker.go,ticker.speed);
	},
	setItem: function() {
		ticker.prefix = ticker.prefixs[ticker.item];
		ticker.string = ticker.strings[ticker.item];
		ticker.letters = 0;
		ticker.item++;
	},
	kill: function() {
		window.clearTimeout(ticker.timer);
		ticker.timer = null;
	}
}

targets = {
	hostname: window.location.hostname.replace("www.","").toLowerCase(),
	a: document.getElementsByTagName("a"),
	check: function(obj) {
		var href = obj.href.toLowerCase();
		if ((href.indexOf("http")!=-1 && href.indexOf(this.hostname)==-1) || (obj.className.indexOf("external")!=-1)) {
			return 'offsite';
		} else if (obj.className.indexOf("popup")!=-1) {
			return 'popup';
		} else {
			return false;
		}
	},
	set: function(obj) {
		obj.target = "_blank";
		obj.className += " external";
	},
	popup: function(obj) {
		obj.className += " popup";
		obj.href = "javascript:popup('"+obj.href+"','"+obj.title+"','800','450');";
	},
	init: function() {
		for (var i=0;i<this.a.length;i++) {
			if (this.check(this.a[i]) == 'offsite') {
				this.set(this.a[i]);
			} else if (this.check(this.a[i]) == 'popup') {
				this.popup(this.a[i]);
			}
		};
	}
}

posFix = {
	selector: null,
	speed: 500,
	x: null,
	y: null,
	offset: null,
	minGap: 50,
	findPos: function(axis) {
		var obj = $(this.selector).get(0);
		var curtop = 0;
		var curLeft = 0;
		if (obj.offsetParent) {
			do {
				curtop += obj.offsetTop;
				curLeft += obj.offsetLeft
			} while (obj = obj.offsetParent);
			if ('y' == axis) {
				return curtop;
			} else {
				return curLeft;
			}
		}
	},
	init: function(selector) {
		if (selector != '') {
			this.selector = selector;
		} else if (this.selector == null) {
			return false;
		}
		if ($(this.selector).get(0) === undefined) {
			return false;
		}
		this.y = this.findPos('y');
		this.x = this.findPos('x');
		$(this.selector).css({position: "absolute", top: this.y+"px", left: this.x+"px"})
		$(window).scroll(function () {
			if (($(document).scrollTop() + posFix.minGap) > posFix.y ) {
				posFix.offset = $(document).scrollTop() + posFix.minGap;
			} else {
				posFix.offset = posFix.y;
			}
			$(posFix.selector).animate({top:posFix.offset+"px"},{duration:posFix.speed,queue:false});
		});
		return true;
	}
}

function setupResultsPageNav(rows) {
	if (rows < ($("#historical-results div.result").length)) {
		resultsNavAnimRunning = false;
		$rowHeight = 210;
		$cells = $("#historical-results div.result").length;
		$rows = $cells;
		$maxDistance = 0 - (($rows - rows)*70);
		$speed = 800;
		$effect = 'easeInOutExpo';
		// we have enough to do some sort of a ting ting
		$("#historical-results").css({position: "relative"}).after('<p class="pageNav"><a class="disabled" id="pageNavBtnPrev" href="#"><img src="/img/prev.gif" alt="previous"/></a><a class="disabled" id="pageNavBtnNext" href="#"><img src="/img/next.gif" alt="next"/></a></p>')
		$("#historical-results .container").css({position: "absolute",top: "0"})
		$("#pageNavBtnNext").bind('click',function(e){
			if (false == resultsNavAnimRunning) {
				resultsNavAnimRunning = true;
				var curr = $("#historical-results .container").css("top");
				curr = curr.replace(/[a-zA-Z]/g,"");
				if (curr > $maxDistance) {
					$("#historical-results .container").animate({
						top: curr-$rowHeight
					},$speed,$effect,function() { resultsNavAnimRunning = false; });
				} else { resultsNavAnimRunning = false; }
			}
			return false;
		});
		$("#pageNavBtnPrev").bind('click',function(e){
			if (false == resultsNavAnimRunning) {
				resultsNavAnimRunning = true;
				var curr = $("#historical-results .container").css("top");
				curr = curr.replace(/[a-zA-Z]/g,"");
				if (curr < 0) {
					$("#historical-results .container").animate({
						top: curr-(-$rowHeight)
					},$speed,$effect,function() { resultsNavAnimRunning = false; });
				} else { resultsNavAnimRunning = false; }
			}
			return false;
		})
	}
}

function setupSubsLinesNav() {
// New Code
	subsAnimating = false;
	$("#numbersContainer div.content").hide();
	$("#numbersContainer").wrapInner('<div class="content" style="display: none;"></div>').prepend('<h4 style="float: left;"><img src="https://media.happi6.com/pp/showTickets.png" alt=""/></h4>');
	$("#paymentContainer").wrapInner('<div class="content"></div>').prepend('<h4 style="float: left; display: none;"><img src="https://media.happi6.com/pp/showPayment.png" alt=""/></h4>');
	$("#numbersContainer > h4").click(function() {
		if (!(subsAnimating) && $("#numbersContainer div.content").css("display") != 'block') {
			subsAnimating = true;
			$(this).slideUp(500, function() {
				$("#paymentContainer div.content").slideUp(500);
				$("#numbersContainer div.content").slideDown(500, function() {
					$("#paymentContainer h4").slideDown(500, function() {
						subsAnimating = false;
					});
				});
			});
		}
	});
	$("#paymentContainer > h4").click(function() {
		if (!(subsAnimating) && $("#paymentContainer div.content").css("display") != 'block') {
			subsAnimating = true;
			$("#paymentContainer h4").slideUp(500, function() {
				$("#numbersContainer div.content").slideUp(500);
				$("#paymentContainer div.content").slideDown(500, function() {
					$("#numbersContainer h4").slideDown(500, function() {
						subsAnimating = false;
					});
				});
			});
		}
	});
	// Old Code
/*
	rows = 5;
	if (rows < ($('#numbersContainer tr').length)) {
		subsNavAnimRunning = false;
		$rowHeight = 52;
		$cells = $("#numbersContainer tr").length;
		$rows = $cells;
		$maxDistance = 0 - (($rows - rows)*26);
		$speed = 800;
		$effect = 'easeInOutExpo';
		// we have enough to do some sort of a ting ting
		$("#numbersContainer").css({position: "relative"}).wrapInner(document.createElement("div")).after('<p class="pageNav"><a class="disabled" id="pageNavBtnPrev" href="#"><img src="/img/pp/prev.png" alt="previous"/></a><a class="disabled" id="pageNavBtnNext" href="#"><img src="/img/pp/next.png" alt="next"/></a></p>');
		$("#numbersContainer div").addClass("container");
		$("#numbersContainer .container").css({position: "absolute",top: "0"});
		$("#pageNavBtnNext").bind('click',function(e){
			if (false == subsNavAnimRunning) {
				subsNavAnimRunning = true;
				var curr = $("#numbersContainer .container").css("top");
				curr = curr.replace(/[a-zA-Z]/g,"");
				if (curr > $maxDistance) {
					$("#numbersContainer .container").animate({
						top: curr-$rowHeight
					},$speed,$effect,function() { subsNavAnimRunning = false; });
				} else { subsNavAnimRunning = false; }
			}
			return false;
		});
		$("#pageNavBtnPrev").bind('click',function(e){
			if (false == subsNavAnimRunning) {
				subsNavAnimRunning = true;
				var curr = $("#numbersContainer .container").css("top");
				curr = curr.replace(/[a-zA-Z]/g,"");
				if (curr < 0) {
					$("#numbersContainer .container").animate({
						top: curr-(-$rowHeight)
					},$speed,$effect,function() { subsNavAnimRunning = false; });
				} else { subsNavAnimRunning = false; }
			}
			return false;
		})
	}
End Old Code */
}

function popup(mypage,myname,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2: 100;
	TopPosition = (screen.height) ? (screen.height-h)/2: 100;
	settings = 'width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,location=yes,directories=no,status=yes,menubar=no,toolbar=no,resizable=yes';
	win = window.open(mypage,myname,settings);
}


function rotateRotator() {
	var $active = $('.rotator li.active');
	if ( $active.length == 0 ) {
		$active = $('.rotator li:last');
	}
	var $next = $active.next().length ? $active.next() : $('.rotator li:first');
	$active.addClass('last-active').removeClass('active');
	$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
		$active.removeClass('active last-active');
	});
}

function makeRotators() {
	$('.rotator').each(function() {
		var height = 0;
		$(this).find('img').each(function() {
			if ($(this).height() > height) {
				height = $(this).height();
			}
		});
		if (0 === height) {
			height = 150;
		}
		$(this).height(height+'px');
	});
	window.setInterval(rotateRotator,10000);
}

$(document).ready(function () {
	setUpInputs();
	if (null != document.getElementById('play-box') || null != document.getElementById('play-box-new')) {
		setUpInputTabs();
	}
	if (null != document.getElementById('header-login')) {
		setupQuickLogin();
	}
	if (null != document.getElementById('news-winners') && getQueryVariable('noTicker') != 'true') {
		ticker.go();
	}
	if (null != document.getElementById('feature-rotator')) {
		$speed = 7000;
		FeatureTimer = window.setInterval("changeFeature()",$speed);
		FeatureRunning = false;
		$('#feature-rotator').bind('mouseover',function(e) {
			if (null != FeatureTimer) {
				window.clearInterval(FeatureTimer);
				FeatureTimer = null;
			}
		}).bind('mouseout',function(e) {
			FeatureTimer = window.setInterval("changeFeature()",$speed);
		});
	}
	if ($('div.FAQs').length > 0) {
		$('div.FAQs a').click(function() {
			var q = $(this).text();
			var a = $(this).parent("li").children("span.answer").text();
			new Boxy("<h3>"+q+"</h3><p>"+a+"</p>", {title: "Happi 6 FAQs"});
			return false;
		})
	}
	if ($('.hidePhoneNumberUsernames').length > 0) {
		$('.hidePhoneNumberUsernames td').each(function() {
			var contents = $(this).html();
			if (contents.match(/^\d{12}$/)) {
				$(this).html('SMS Player');
			}
		});
	}
	makeRotators();
	$('a.lightbox').each(function(){
		$(this).lightBox();
	});
	targets.init();
	posFix.init("#genealogyDetail");
	if (getQueryVariable('countTickets') == 'true') {
		count();
	}
	if (null != document.getElementById("historical-results")) {
		setupResultsPageNav(3);
	}
	if (null != document.getElementById("numbersContainer")) {
		setupSubsLinesNav();
	}
});

function urlencode(str) {
    str = escape(str);
    str = str.replace('+', '%2B');
    str = str.replace('%20', '+');
    str = str.replace('*', '%2A');
    str = str.replace('/', '%2F');
    str = str.replace('@', '%40');
    return str;
}
