jQuery.fn.outerHTML = function() {
return $( $('<div></div>').html(this.clone()) ).html();
}

$(document).ready( function(){ 
	//########################################
	// Set up the live person listener and
	// live chat functions
	//########################################
	inviteTimer = setInterval ( "checkInvite()", 5000 ); 
	
	// hide the live chat of a button
	$('#live_chat_close').live('click', function() {hideChatAlert();});
	$('#live_chat_accept').live('click', function() {hideChatAlert();});

	//########################################
	// Set the current sub nav class up
	//########################################
	var currentURL = $(location).attr('href');
	var currentMarker = '<div id="currentMarker"><img src="http://www.pchprizes.co.uk/images/PCH/Framework/Sub-Nav-Arrow.png" alt="Sub-Nav-Arrow" width="17" height="7" /></div>';
	
	$('#subNav').find('a[href="' + currentURL + '"]').addClass('current');
	$('#subNav').find('a.current').after(currentMarker);
	
	var currentLinkWidth = $('#subNav').find('a.current').width();
	var markerPosition = ((currentLinkWidth + 20) / 2) - 9;
	$('#currentMarker').css("left",markerPosition);
		
	
	//########################################
	// Watermark the form fields
	//########################################

	$("label").inFieldLabels();
	
	//########################################
	// Prize point table toggling
	//########################################
	$("#prize-points-nav a").click(
		function (event) 
		{
			event.preventDefault();
			$("#prize-points-nav a").removeClass("current");
			$(this).parent().parent().addClass($(this).attr('id'));
			$("#textContent table").hide();
			targetID = "#bb-" + $(this).attr('id');
			$(targetID).show();
		});


	
	//########################################
	// Update the Playtech balance every 20s
	//########################################
	setInterval("updatePlaytechBalance()", 20000 );
	
	//########################################
	// Log in form AJAX
	//########################################
	$("a#login-submit").click(
		function (event) 
		{
			event.preventDefault();
			DoLogin();
		}
	);
	
	$('.loginWrapper input#username, .loginWrapper input#password').keypress(function(e){
		if(e.which == 13){
			e.preventDefault();
			DoLogin();
		}
	});
	
	//########################################
	// Call the scrolling footer
	//########################################
	if($.cookie('FooterClosed'))
	{
		$("#footer").width(155);
		$("img#closeFooter").toggle();
		$("img#openFooter").toggle();
	}
	
	scrollFooter(true);
	
	//########################################
	// Close/open the footer
	//########################################
	$("img#closeFooter").click(
		function (event) {
			$("img#closeFooter").toggle();
			$("img#openFooter").toggle();
			$("#footer").animate({width:155}, 1500, 'swing');
			
			// Drop a cookie to say footer is closed and log in GA
			$.cookie('FooterClosed', 'true', { expires: 7,path: '/'});
			_gaq.push(["_trackPageview", "/track/footer-closed/"]);
	});
	$("img#openFooter").click(
		function (event) {
			$("img#closeFooter").toggle();
			$("img#openFooter").toggle();
			$("#footer").animate({width:"100%"}, 1500, 'swing');
			
			// Drop a cookie to say footer is opened and log in GA
			$.cookie('FooterClosed', null, { path: '/'});
			_gaq.push(["_trackPageview", "/track/footer-opened/"]);
	});
	
	//########################################
	// Home page carousel
	//########################################
	
	$("#mycarousel").jcarousel({
        scroll: 1,
        auto: 4,
        wrap: 'last',
        vertical: true,
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null,
        animation: 0
    });
	
	//########################################
	// Home page small promo animtation/hover
	//########################################
	
	$("#home .promoInfo").toggle();
	
	$("#home .promo").hover(
	  function () {
		$(this).find(".promoInfo").show("slide", { direction: "down" },'fast');
	  }, 
	  function () {
		$(this).find(".promoInfo").hide("slide", { direction: "down" },'slow');
	  }
	);
	
	//########################################
	// Content page horizontal frame animation/hover
	//########################################
	
	$("#mainContent .horizontalFrame .promoInfo,#mainContent .horizontalFrameNarrow .promoInfo ").toggle();
	
	$("#mainContent .horizontalFrame").hover(
	  function () {
		$(this).find(".promoInfo").show("slide", { direction: "right" },'fast');
	  }, 
	  function () {
		$(this).find(".promoInfo").hide("slide", { direction: "right" },'slow');
	  }
	);
		
	$("#mainContent .horizontalFrameNarrow").hover(
	  function () {
		$(this).find(".promoInfo").show("slide", { direction: "down" },'fast');
	  }, 
	  function () {
		$(this).find(".promoInfo").hide("slide", { direction: "down" },'slow');
	  }
	);
			
	//########################################
	// Game thumbnail display more info toggle
	//########################################
	
	$(".gameThumbnailInfo a.moreInfo").click(
		function (event) {
			// prevent the actual click
			event.preventDefault();
			
			
			var myGameNumber = $(this).parent().parent().index() + 1;
			
			// If an injected panel is being displayed then there is
			// an additional div in the index that we need to ignore
			// Reduce the index by 1
			if($(".injectedPanel").index() != -1)
			{				
				if($(".injectedPanel").index() < $(this).parent().parent().index())
				{
					myGameNumber --;
				}
			}
			
			// find where we should inject the code	
			var injectionPoint = findInjectionPont(myGameNumber);
			
			// Am I already visible
			if($(this).attr("open")=="true")
			{
				// If so hide me
				$(".injectedPanel").remove();
				$("a.moreInfo").removeAttr("open");
			}
			else
			{
				$(".injectedPanel").remove();
				$("a.moreInfo").removeAttr("open");
				$(this).attr("open","true");
				
				if($(this).parent().parent().parent().children("div").eq(injectionPoint-1).exists())
				{$(this).parent().parent().parent().children("div").eq(injectionPoint-1).after($(this).parent().parent().find('.gameInfo').clone().addClass('injectedPanel').addClass('visible'+myGameNumber));}
				else if($(this).parent().parent().parent().children("div").eq(injectionPoint-2).exists())
				{$(this).parent().parent().parent().children("div").eq(injectionPoint-2).after($(this).parent().parent().find('.gameInfo').clone().addClass('injectedPanel').addClass('visible'+myGameNumber));}
				else if($(this).parent().parent().parent().children("div").eq(injectionPoint-3).exists())
				{$(this).parent().parent().parent().children("div").eq(injectionPoint-3).after($(this).parent().parent().find('.gameInfo').clone().addClass('injectedPanel').addClass('visible'+myGameNumber));}
				else if($(this).parent().parent().parent().children("div").eq(injectionPoint-4).exists())
				{$(this).parent().parent().parent().children("div").eq(injectionPoint-4).after($(this).parent().parent().find('.gameInfo').clone().addClass('injectedPanel').addClass('visible'+myGameNumber));}
				
				
			}
		});
		
		//########################################
		// Game page info panel show/hide
		//########################################
		$("#gameInfoNav a").click(
		function (event) {
			event.preventDefault();
			$("#gameInfoNav li").removeClass("current");
			$(".gameInfoPanel").hide();
			$(this).parent("li").addClass("current");
			var toShow = $(this).attr("rel");
			$("#" + toShow).show();
		});
		
		//########################################
		// Table showing/hiding
		//########################################
		
		$("div#mainContent #column1 table#paymentMethods tr td").not(".paymentMethodDetails td").click(
		function (event) {
			var parentRow = $(this).parent();
			var detailRow = $(parentRow).next();
			
			// Close all open panels and reset all styles
			$("div#mainContent #column1 table tr td").removeClass("current");
			$("div#mainContent #column1 table tr.paymentMethodDetails").not(detailRow).hide();
			

			// Am I already visible
			if($(detailRow).is(":visible"))
			{
				// Yes. Remove classes.
				$(parentRow).find("td").removeClass("current");
				$(detailRow).find("td").removeClass("current");
			}
			else
			{
				// No. Add classes.
				$(parentRow).find("td").addClass("current");
				$(detailRow).find("td").addClass("current");
			}
			
			// Toggle visibility of the detail row
			$(detailRow).toggle();
		});
			
	//########################################
	// Winner page scrolling columns
	//########################################
	$('a.scrollUp').mouseover(function() {scrollWinnerColumn(true,this);});
	$('a.scrollUp').mouseout(function() {$('.winnerScroller').pause();});
	$('a.scrollDown').mouseover(function() {scrollWinnerColumn(false,this);});
	$('a.scrollDown').mouseout(function() {$('.winnerScroller').pause();});
	
	//########################################
	// Bingo promo carousel
	//########################################
	
	// Set the width of the wrapper to 186px times
	// the number of items.
	var numberOfCarouselItems = $('#carouselWrapper ul').children().size();
	var wrapperWidth = numberOfCarouselItems * 186;
	$('#carouselWrapper ul').width(wrapperWidth);
	
	$('#bingoCarousel #leftController').mouseover(function() {scrollBingoCarousel(true,this);});
	$('#bingoCarousel #leftController').mouseout(function() {
		$('#carouselWrapper ul').pause();
	});
	$('#bingoCarousel #rightController').mouseover(function() {scrollBingoCarousel(false,this);});
	$('#bingoCarousel #rightController').mouseout(function() {
		$('#carouselWrapper ul').pause();
	});
	
	//########################################
	// Bingo Schedule
	//########################################
	$('#bingoScheduleFilters a').click(function(event) {
		event.preventDefault();
		$("#bingoScheduleFilters li").removeClass("current");
		$(this).parent().addClass("current");
	});
	
	$('#bingoScheduleFilters #all a').click(function() {
		$("#bingoSchedule tr").show();
		trimBingoSchedule();
	});
	
	$('#bingoScheduleFilters a#ninety').click(function() {
		$("#bingoSchedule tr").not("#bingoSchedule tr#headerRow").not("tr[game-type*='90']").hide();
		$("#bingoSchedule tr[game-type*='90']").show();
		trimBingoSchedule();
	});
	
	$('#bingoScheduleFilters a#eighty').click(function() {
		$("#bingoSchedule tr").not("#bingoSchedule tr#headerRow").not("tr[game-type*='80']").hide();
		$("#bingoSchedule tr[game-type*='80']").show();
		trimBingoSchedule();
	});
	
	$('#bingoScheduleFilters a#seventyfive').click(function() {
		$("#bingoSchedule tr").not("#bingoSchedule tr#headerRow").not("tr[game-type*='75']").hide();
		$("#bingoSchedule tr[game-type*='75']").show();
		trimBingoSchedule();
	});
	
	$('#bingoScheduleFilters a#other').click(function() {
		$("#bingoSchedule tr[game-type*='90'], #bingoSchedule tr[game-type*='80'],#bingoSchedule tr[game-type*='75']").hide();
		$("#bingoSchedule tr").not("#bingoSchedule tr[game-type*='90'], #bingoSchedule tr[game-type*='80'],#bingoSchedule tr[game-type*='75']").show();
		trimBingoSchedule();
	});
	
	//########################################
	// Bingo community
	//########################################
	$('.sectionHeader a').click(function(event) {
		event.preventDefault();
		
		$(this).parent().parent().parent().find(".sectionContent").toggle();
		
		if($(this).parent().parent().parent().find("h2").hasClass('open')) {$(this).parent().parent().parent().find("h2").removeClass('open');}
		else {$(this).parent().parent().parent().find("h2").addClass('open');}
	});
				
	//########################################
	// Video page rating
	//########################################
	$('input.star').rating();
	$('.rating-cancel').remove();
	
	//########################################
	// Shadowbox
	//########################################
	Shadowbox.init({
		modal: true,
		overlayOpacity: 0.8,
		enableKeys: false,
		troubleElements: ["select", "object", "embed", "canvas", "iframe"]
	});
	
	//########################################
	// Game thumbnail hovers
	//########################################	
	$('.gameThumbnail').hover(function() {$(this).find('.gameThumbnailInfo').toggle();});	
		
	//########################################
	// Right column content toggles
	//########################################
	$("p.readMore a").click(
		function (event) {
			event.preventDefault();
			$("#readMoreContent").toggle();
		});
	
	//########################################
	// Auto opening PD's
	//########################################
	if (window.location.hash.length)
	{
		if(window.location.hash.indexOf("#openmodal")==0)
		{
			// Get the PD url
			var pd = GetParameterValue("pd");
			var iw = GetParameterValue("iw");
			var reg = GetParameterValue("reg");
			var pass = GetParameterValue("pass");
			var cashier = GetParameterValue("cashier");
						
			// Open the modal
			if(pd)
			{
				window.onload = function() {
				
					// find the URL of the link we should open and click it
					var link = $("#pd"+pd).attr("href");
					$("#pd"+pd).click();
				};	
			}
			
			if(iw)
			{
				window.onload = function() {
	
				    // find the URL of the link we should open and click it
					var link = $("#iw"+pd).attr("href");
					$("#iw"+iw).click();
	
				};	
			}
			
			if(reg)
			{
				window.onload = function() {$("#regLink").click();};	
			}
			
			if(pass)
			{
				window.onload = function() {$("#passwordReset").click();};	
			}
			
			if(cashier)
			{
				window.onload = function() {$("#cashier").click();};	
			}		
				
		}
	}
	
	//########################################
	// Hiding Live Chat buttons when an
	// operator is not signed in
	//########################################
	$('img[src$="reponline.gif"]').parent().parent().parent().parent().parent().parent().parent().parent().show();
	
	
	//########################################
	// Bingo rooms panel toggle
	//########################################
	$(".bingo-room .bingo-room-header p a").click(function(event) {
		event.preventDefault();
		if($(this).text() == "more")
		{
			$(this).text("close");
			$(this).parent().parent().parent().find('.more').slideDown();	
		}
		else
		{
			$(this).text("more");
			$(this).parent().parent().parent().find('.more').slideUp();
		}	
	});	

});


function scrollWinnerColumn(up,caller)
{
	var theWrapper = $(caller).parent().find(".winnerScrollerWrapper");
	var theScroller = $(caller).parent().find(".winnerScroller");
	var wrapperHeight = $(theWrapper).height(); // Height of relevant winnerScrollerWrapper div
	var scrollerHeight = $(theScroller).height(); // Height of relevant winnerScroller div
	var scrollDistance = scrollerHeight - wrapperHeight;
	var scrollPoint = 0;
	var scrollSpeed = 0.1;
	
	var currentPosition = $(theScroller).position().top;
	
	if(up)
	{
		scrollPoint = 0 - scrollDistance;
	}
	
	var howFar = currentPosition - scrollPoint;
	howFar = howFar.toString().replace("-","");
	howFar = parseInt(howFar);
	var scrollTime = howFar / scrollSpeed;
		
	$(theScroller).animate({top:scrollPoint}, scrollTime, 'linear');
}


function scrollBingoCarousel(left,caller)
{
	var theWrapper = $(caller).parent().find("#carouselWrapper");
	var theScroller = $(caller).parent().find("#carouselWrapper ul");
	var wrapperWidth = $(theWrapper).width(); // Width of relevant carouselWrapper div
	var scrollerWidth = $(theScroller).width(); // Width of relevant asset li
	var scrollDistance = scrollerWidth - wrapperWidth;
	var scrollPoint = 0;
	var scrollSpeed = 0.1;
	
	var currentPosition = $(theScroller).position().left;
	
	if(!left)
	{
		scrollPoint = 0 - scrollDistance;
	}
	
	var howFar = currentPosition - scrollPoint;
	howFar = howFar.toString().replace("-","");
	howFar = parseInt(howFar);
	var scrollTime = howFar / scrollSpeed;
		
	$(theScroller).animate({left:scrollPoint}, scrollTime, 'linear');
}

function scrollFooter(forwards)
{
	// Collect some variables
	var wrapperWidth = $('#footer').width();
	var imgWidth =  $('#footer img').width();
	var scrollerWidth = $('#scroller').width();
	var scrollDistance = scrollerWidth - wrapperWidth + imgWidth;
	var scrollPoint = 0;
	var numberOfItems = $('#scroller > div').length
	var scrollSpeed = numberOfItems * 1000;
	
	// 
	
	// Work out where we are scrolling the footer to
	if(forwards)
	{
		scrollPoint = 0 - scrollDistance;
	}
	else
	{
		scrollPoint = 0;
	}

	// Do the scrolling
	$('#scroller').animate({left:scrollPoint}, scrollSpeed, 'linear', function() {scrollFooter(!forwards)});
	$('#scroller').hover(function() {$('#scroller').pause();}, function() {$('#scroller').resume();});	
}

function findInjectionPont(currentID)
{
	if(currentID > 0)
        return Math.ceil(currentID/4.0) * 4;
    else if( currentID < 0)
        return Math.floor(currentID/4.0) * 4;
    else
        return 4;
}

function mycarousel_initCallback(carousel) {
    $('.jcarousel-control a').bind('click', function() {
    	carousel.startAuto(0);
        carousel.scroll($.jcarousel.intval($(this).text()));
        return false;
    });
    
    $('#mycarousel-next').bind('click', function() {
    	carousel.startAuto(0);
        carousel.next();
        return false;
    });
 
    $('#mycarousel-prev').bind('click', function() {
    	carousel.startAuto(0);
        carousel.prev();
        return false;
    });
    
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {carousel.stopAuto();}, function() {carousel.startAuto();});
};

// Gets a given parameter from the URL querystring
function GetParameterValue(parameterName)
{
	url = document.URL;
	
	var start = url.indexOf(parameterName + '=');
	
	if (start == -1)
	{return("");}
	
	start += parameterName.length + 1;
	
	var end = url.indexOf('&',start);
	
	if (end == -1)
	{
		end = url.length;
	}
	
	var toReturn = url.substring(start,end);
	return(toReturn);
}

// Updates a PT balance
function updatePlaytechBalance()
{$('#ptHeaderBalance').load("http://www.pchprizes.co.uk/mss/get-playtech-balance/");
} 

jQuery.fn.exists = function(){return jQuery(this).length>0;}

// Trims the bingo schedule to a number of items
function trimBingoSchedule()
{
	$("#bingoSchedule tr:visible:gt(7)").hide();
}



// Function to show live chat
function showChatAlert() 
{
	$('body').prepend("<div id='live_chat'><div id='live_chat_container'><img src='http://www.pchprizes.co.uk/images/PCH/Livechat/icon.png' alt='' width='277' height='82' /><p>Chat live with one of our PCH Prizes representatives and they'll be happy to help you</p><a href='#' class='chat_now' id='live_chat_accept'>Chat Now</a><div id='live_chat_close'>close</div></div></div>");
	var lpAccept = $('.chatInvite').attr('ia');
	var lpReject = $('.chatInvite').attr('ir');
	$('#live_chat_accept').attr('onClick', lpAccept);
	$('#live_chat_close').attr('onClick', lpReject);
	$('#live_chat').slideDown();
}

// Function to hide live chat alert
function hideChatAlert() 
{
	$('#live_chat').slideUp(function () {$(this).remove();});
}

// Function to check for an invite
function checkInvite()
{
	if ($('.chatInvite').length)
	{
		showChatAlert();
		clearInterval(inviteTimer);
	}
} 

//Function to log in
function DoLogin()
{
	// Hide all error messages
	$("p.login-error span").hide();
	
	// AJAX submit the form
	$.ajax(
	{
		type: "POST",
		url: "http://www.pchprizes.co.uk/mss/login/",
		data: "username=" + $("input#username").val() + "&password=" + $("input#password").val() ,
		success: function(msg)
		{
			if(msg=="true")
			{
				document.location = document.location.href.split('#')[0];
			}
			else
			{
				var reason = msg.split("|")[1];
				$("span#account-not-found").text(reason);
				$("span#account-not-found").fadeIn();
			}
		}
	});
	
	

}
$(document).ready( function(){ 
if($(".clicker").length > 0){
	$(".clicker").click(function(){
		$(".reveal-text").fadeIn("slow");
		$(".tandc-content").fadeIn("slow");
		$(".over-image").fadeOut("slow", function () {$(".over-image").remove();});
		$(".clicker").fadeOut("slow", function () {$(".clicker").remove();});
			return false;
		});
	}
});
