//Resize Images with Highslide Configuration

hs.graphicsDir = 'http://cdn.pocketfives.com/graphics/';
hs.align = 'center';
hs.transitions = ['expand', 'crossfade'];
hs.outlineType = 'glossy-dark';
hs.wrapperClassName = 'dark';
hs.fadeInOut = true;
hs.showCredits = false;
hs.dimmingOpacity = 0.8;
hs.captionText = 'PocketFives';
hs.lang = {
	cssDirection: 'ltr',
	loadingText : 'Loading...',
	loadingTitle : 'Click to cancel',
	focusTitle : 'Click to bring to front',
	fullExpandTitle : 'Expand to actual size (f)',
	previousText : 'Previous',
	nextText : 'Next', 
	moveText : 'Move',
	closeText : 'Close', 
	closeTitle : 'Close (esc)', 
	resizeTitle : 'Resize',
	playText : 'Play',
	playTitle : 'Play slideshow (spacebar)',
	pauseText : 'Pause',
	pauseTitle : 'Pause slideshow (spacebar)',
	previousTitle : 'Previous (arrow left)',
	nextTitle : 'Next (arrow right)',
	moveTitle : 'Move',
	fullExpandText : '1:1',
	number: 'Image %1 of %2',
	restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
}
// Add the controlbar
if (hs.addSlideshow) hs.addSlideshow({
	interval: 5000,
	repeat: false,
	useControls: true,
	fixedControls: 'fit',
	overlayOptions: {
		opacity: .6,
		position: 'bottom center',
		hideOnMouseOut: true
	}
});
 
$(document).ready(function() {
	
	//Skinning Area
	/*
	 * 		$(document).ready(function() {
			$("div#skin-left").click(function() {
				 window.open("http://www.pokerstars.com");
			});
			$("div#skin-right").click(function() {
				 window.open("http://www.pokerstars.com");			
			});
		});
	 */
	    
	    
	//Facebook Load Event
	if ($('div#fb-root').length != 0) {
	    window.fbAsyncInit = function() {
	        FB.init({appId: '126475237401990', status: true, cookie: true,
	                 xfbml: true});
	      };
	      (function() {
	        var e = document.createElement('script');
	        e.type = 'text/javascript';
	        e.src = document.location.protocol +
	          '//connect.facebook.net/en_US/all.js';
	        e.async = true;
	        document.getElementById('fb-root').appendChild(e);
	      }());
	}
	//P5s Training Clickable Div on PF
	$('div.p5t-ad').click(function() {
		window.location.href = "http://training.pocketfives.com";
	});
        
	//Update div header image if sidebar is collapsed
	if($("div.box29 div.box29-top").length > 0) {
		if($("div#content_container").attr("style") == "margin-right: 0pt;" || $("div#content_container").attr("style") == "margin-right: 0px" || $("div#content_container").attr("style") == "margin-right: 0px; ") {
			$("div.box29 div.box29-top").css("background-image", "url(\"http://cdn.pocketfives.com/newlayout/content/box29-top-large.gif\")");
		}else{
			$("div.box29 div.box29-top").css("background-image", "url(\"http://cdn.pocketfives.com/newlayout/content/box29-top.gif\")");
			$("div#sidebar_container").css("width", "324px");
			$("ul#sidebar").show();
		}
	}
	//Hide sidebar on click and update header image
	$('#sidebar_button').click(function() {
		if($("div.box29 div.box29-top").length > 0) {
			if($("div.box29 div.box29-top").css("background-image") == "url(\"http://cdn.pocketfives.com/newlayout/content/box29-top.gif\")"
				|| $("div.box29 div.box29-top").css("background-image") == "url(http://cdn.pocketfives.com/newlayout/content/box29-top.gif)") {
				$("div.box29 div.box29-top").css("background-image", "url(\"http://cdn.pocketfives.com/newlayout/content/box29-top-large.gif\")");
			}else{
				$("div.box29 div.box29-top").css("background-image", "url(\"http://cdn.pocketfives.com/newlayout/content/box29-top.gif\")");
			}
		}
	});
	
	
	//Fix to hide new image on mark read clicked
	$(".markread").click(function(){
		$(".gotonewpost").hide();
    });
	
	
	//Stupid badgebox fix for links
	$('span.badgebox').click(function() {
		var link = $(this).find("a").attr('href');
		if(link != undefined) {
			window.location.href = $(this).find("a").attr('href');
		}
	});
	
	
	//Navbar hover configuration and setup
	var chrome_textfix1 = false;
	var config = {    
	    sensitivity: 1,
	    interval: 150,
	    timeout: 350,
	    over: function() {
			var drop = $(this).find("ul.child");
			var height = $(drop).height();
			if ($.browser.msie && $.browser.version.substr(0,1)<9) {
                $(drop).css({
                    display: "block",
                    height: "0"
                }).stop().animate({
                    "height": height
                },{
	                duration: 260, 
	                queue: false,
	                easing: "easeOutCirc",
	                completed: function () {
	                $(drop).css({
	                   "overflow": "visible"
	                })
                   }
                })
            } else {
            	$(drop).css({
                    display: "block",
                    height: "0"
                }).stop().animate({
                    "height": height,
                    "opacity": 1
                },{
                	duration: 260,
                	queue: false,
                	easing: "easeOutCirc",
                	complete: function () {
                    $(drop).css({
                        "overflow": "visible"
                    })
                  }
                })
            }
		}, 
	    out: function() { 
			if (chrome_textfix1 == false) {
			    var drop = $(this).find("ul.child");
			    if ($.browser.msie && $.browser.version.substr(0, 1) < 9) {
			        $(drop).css({
			            "overflow": "hidden"
			        }).stop().animate({
			            "height": 0
			        }, {
			            duration: 260,
			            queue: false,
			            easing: "easeInCirc",
			            complete: function () {
			                $(drop).css({
			                    "display": "none",
			                    "height": ""
			                })
			            }
			        })
			    } else {
			        $(drop).css({
			            "overflow": "hidden"
			        }).stop().animate({
			            "height": 0,
			            "opacity": 0
			        }, {
			            duration: 260,
			            queue: false,
			            easing: "easeInCirc",
			            complete: function () {
			                $(drop).css({
			                    "display": "none",
			                    "height": ""
			                })
			            }
			        })
			    }
			}
		}
	};
	$("input.searchbox").hover(
			function () {
				chrome_textfix1 = true;
			},function () {
				chrome_textfix1 = false;
	});
	$("div#main-navigation ul li.parent").hoverIntent(config);
	$("div.sub-navigation ul li.parent").hoverIntent(config);
	$("div.title div.controls ul li.parent").hoverIntent(config);
	
	
	//Hide Thread Script
	$(".hide_thread").click(function () {
		$(this).parent().parent().parent().slideUp();
		$('.result_'+$(this).attr('id')).load("pocketfives/hidethread.php?do=add&threadid="+$(this).attr('id'));
	});
	
	
	//Navbar Search box control
	var mouse_is_inside1 = false;
	var chrome_text_fix2 = false;
	var fade_away1;
	$('div.search-form1 div.search-box').hide();
	var config_search = {    
		    sensitivity: 1,
		    interval: 150,
		    timeout: 150,
		    over: function() { 
				$('div.search-form1 div.search-box').stop(true, true).fadeIn("300");
				$('div.login-form1 div.search-box').hide();
		  		$("#navquery").focus();
		  		mouse_is_inside1=true;
		  		clearTimeout(fade_away1);
			}, 
		    out: function() { 
				if(chrome_text_fix2 == false)
					fade_away1 = setTimeout("$('div.search-form1 div.search-box').stop(true, true).fadeOut(\"300\");", 1500);
	 			mouse_is_inside1=false;
		    }
	};
	$("div.search-form1").hoverIntent(config_search)
	$("#navquery").hover(
			function () {
				chrome_text_fix2=true;
				clearTimeout(fade_away1);
			},function () {
	 			chrome_text_fix2=false;
	});

	
	//Navbar Login control
	var mouse_is_inside2 = false;
	var chrome_text_fix3 = false;
	var fade_away2;
	$('div.login-form1 div.search-box').hide();
	$('.user_login').keyup(function(e) {
		if(e.keyCode == 13) {
			$('#signup-form').submit();
		}
	});
	var config_login = {    
		    sensitivity: 1,
		    interval: 150,
		    timeout: 150,
		    over: function() { 
				$('div.login-form1 div.search-box').stop(true, true).fadeIn("300");
				$('div.search-form1 div.search-box').hide();
		  		$("#navbar_username").focus();
		  		mouse_is_inside2=true;
		  		clearTimeout(fade_away2);
			}, 
		    out: function() { 
				if(chrome_text_fix3 == false)
					fade_away2 = setTimeout("$('div.login-form1 div.search-box').stop(true, true).fadeOut(\"300\");", 1500);
	 			mouse_is_inside2=false;
		    }
	};
	$("div.login-form1").hoverIntent(config_login);
	$("#navbar_username").hover(
			function () {
				chrome_text_fix3=true;
				clearTimeout(fade_away2);
			},function () {
				chrome_text_fix3=false;
	});
	$("#navbar_password").hover(
			function () {
				chrome_text_fix3=true;
				clearTimeout(fade_away2);
			},function () {
				chrome_text_fix3=false;
	});
	
	$("body").mouseup(function(){ 
        if(mouse_is_inside1 == false && chrome_text_fix2 == false) $('div.search-form1 div.search-box').stop(true, true).fadeOut("300");
        if(mouse_is_inside2 == false && chrome_text_fix3 == false) $('div.login-form1 div.search-box').stop(true, true).fadeOut("300");
    });
	
	//Homepage sortable rankings control
	var sr_saved = $.cookie("sr_saved");
	if(sr_saved=='show') {
		$('div#sortable-ranking h6').addClass('active');
		$('div#sortable-ranking div.sortable div.inner').show();
	}
	$('div#sortable-ranking div.sortable h6').click(function() {
		if ($(this).hasClass('active'))	{
			$(this).removeClass('active');
			$('div#sortable-ranking div.sortable div.inner').slideUp("300");
			$.cookie("sr_saved", "hide", {expires: 7, path: '/'});
		}else{
			$(this).addClass('active');
  			$('div#sortable-ranking div.sortable div.inner').slideDown("300");
  			$.cookie("sr_saved", "show", {expires: 7, path: '/'});
		};
		return false;
	});
	$("div#sortable-ranking div.form ul li input").click(function(event) {
		$("table#sortable").html("<tbody><tr><td class='last'><center><img src='http://cdn.pocketfives.com/ajax.gif' alt='ajax' /></center></td></tr></tbody>");
		$("table#sortable").load("pocketfives/find_location.php?do=fill&country="+$("#user_country_update").val()+"&region="+$("#user_region_update").val()+"&city="+$("#user_city_update").val());
	});
	
	
	//Bottom toolbar Control
	var mm_saved = $.cookie("mm_saved");
	if(mm_saved=='Show') {
	    $("#bar_bottom").show();
	    $("#min_max").text('Hide');
	}else{
	    $("#bar_bottom").hide();
	    $("#min_max").text('Show');
	}
	$("select#forumjump").change(function() {
		 if ($(this).val()) {
			 window.location.href = $(this).val();
		 }
	});
	$("#min_max").click(function(){
		$("#bar_bottom").slideToggle(300);
	    $(this).text($(this).text() == 'Show' ? 'Hide' : 'Show');

	    var mm_saved = $.cookie("mm_saved");
	    if(mm_saved=='Show') {
	        $.cookie("mm_saved", "Hide", {expires: 7, path: '/'});
	    }else
	        $.cookie("mm_saved", "Show", {expires: 7, path: '/'});

    });
    $("#jump_link").click(function(){
        $("#forum_jump").slideToggle(300);
    });
    $("#jump_col").click(function(){
        $("#forum_jump").slideToggle(300);
    });
	
    
    //Hide Register Block
    $(".reg_hide").click(function(){
    	$("#welcome-header").hide();
    	$.cookie("ref_saved", 6, {expires: 7, path: '/'});
    });
    
    
	//Hide Debug information by default click to expand
	$('table#debuginfo').hide();
	$('img#collapseimg_debuginfo').hide();
	$("#debug").click(function(event) {
		$('table#debuginfo').toggle();
	});
	
	
	//Footer GPWA Window Control
	$("#gpwa").click(function(event) {
		var width = 650;
		var height = 705;
		var left = parseInt((screen.availWidth/2) - (width/2));
		var top = parseInt((screen.availHeight/2) - (height/2));
		var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
		myWindow = window.open("http://certify.gpwa.org/verify/pocketfives.com/", "GPWA", windowFeatures);
	});
	
	//On selecting referal select all text
	$("#referral_link").focus(function(){
 		this.select();
	});
	
	//Force all numeric inputs to be numeric only
	$("input.numeric").numeric();
	
	//Toggle ranked sites on profile page
	$(".toggle_container_sites").hide(); 
	$("span.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("slow");
		 $(this).text(($(this).text() == "Click to view unranked sites") ? "Click to hide unranked sites" : "Click to view unranked sites");			
	});
	
	
	//Load Sortable Rankings Ajax
	$(".go_rank").click(function () {
		rank_date = $("#rankings_dates").val();
		rank_month = rank_date.slice(0, 2);
		rank_day = rank_date.slice(0, 5);
		rank_day = rank_day.slice(3);
		rank_year = rank_date.slice(6);
		$(window.location).attr("href", "http://www.pocketfives.com/pocketfives/rankings.php?type=ranks&month="+rank_month+"&day="+rank_day+"&year="+rank_year);
	});
	
	
	//Hide blocks when clicked
	$("#hideblock").click(function(){
		$("#hideme").hide();
    });
	
	
	//Script for poker site change page
	$(".site_box").keyup(function(){
		var sitename_clean = $(this).attr("id");
		var class_names = $(this).attr("class");
		
		if ($(this).val().length > 0) {
			if(class_names.indexOf("span_ranked") != -1)
				$("#"+sitename_clean+"_span").addClass("ranked");	
			$("#"+sitename_clean+"_check").removeClass("hidden");
		}else{
			$("#"+sitename_clean+"_check").addClass("hidden");
			$("#"+sitename_clean+"_check").removeAttr("checked");
			$("#"+sitename_clean+"_span").removeClass("ranked");
		}
	});
	
	
	//Submit Reccomendation
	$("#submit-rec").click(function () {
		if($("#coaches-replarea").val() == "Enter your Recommendation. Note: You may use links; simple addresses i.e. www.pocketfives.com, and line breaks; hit enter for new lines.") {
			alert("Please enter text in the recommendation area.");
			$("#coaches-replarea").focus();
			return false;
		}
	});
	
	
	//User tooltip on navbar search
	$("a.user-tooltip").tooltip({
		showURL: false
	});
	

	
	//Calculate PLB scores
	$("#calculateplb").click(function(){
		$("#PLBScore").html('<font color="#990000"><strong>' + (Math.round(Math.pow(parseFloat($("#prizePool").val()), .5) / Math.pow(parseFloat($("#placeFinished").val()), .6) * 100) / 100) + '</strong></font>');
	});
	
	
	//When countries clicked update other options
	$("#sortableCountries").change(function(){
		$("#getSortableResults").attr("disabled", "true");
		$("#sortableCountries").attr("disabled", true);
		$('#sortableRegions').attr("disabled", true); 
		$('#sortableCities').attr("disabled", true); 
		$("#sortableRegions").empty();
		$("#sortableCities").empty();
		$("#sortableRegions").append($('<option></option>').html("Loading..."));
	    
		$.getJSON("/pocketfives/sortablerankings.php", { cid: $("#sortableCountries option:selected").val() },
			function(data){
				$("#sortableRegions").empty();
				$.each(data.items, function(i,item){
				$("#sortableRegions").append(
					$('<option></option>').val(item.Value).html(item.Name)
				);
			});		
			$("#sortableCountries").removeAttr("disabled");
			if ($("#sortableCountries option:selected").val() != '')
				$('#sortableRegions').removeAttr("disabled");
			$("#getSortableResults").removeAttr("disabled");
		});
	});

	
	//When regions clicked update other options
	$("#sortableRegions").change(function(){
		$("#getSortableResults").attr("disabled", "true");
		$("#sortableCountries").attr("disabled", true);
		$('#sortableRegions').attr("disabled", true); 
		$('#sortableCities').attr("disabled", true); 
		$("#sortableCities").empty();
		$("#sortableCities").append($('<option></option>').html("Loading..."));
			
		$.getJSON("/pocketfives/sortablerankings.php", { rid: $("#sortableRegions option:selected").val(), cid: $("#sortableCountries option:selected").val() },
				function(data){
					$("#sortableCities").empty();
					$.each(data.items, function(i,item){
						$("#sortableCities").append(
								$('<option></option>').val(item.Value).html(item.Name)
						);
				});
				$("#sortableCountries").removeAttr("disabled"); 
				$('#sortableRegions').removeAttr("disabled");  
				if ($("#sortableRegions option:selected").val() != '')
					$('#sortableCities').removeAttr("disabled");
				$("#getSortableResults").removeAttr("disabled");
		});
	});
	
	//Ajax update sortable results
	$("#getSortableResults").click(function(){
		$("#getSortableResults").attr("disabled", "true");
		$("table.table4 tbody").html("<tr><td colspan=\"6\"><img class=\"ajax\" src='http://cdn.pocketfives.com/ajax.gif' alt='ajax' /></tr></td>");
		var vcid   = ($("#sortableCountries option:selected").val() != null) ? $("#sortableCountries option:selected").val() : "";  
		var vrid   = ($("#sortableRegions option:selected").val() != null) ? $("#sortableRegions option:selected").val() : "";
		var vcity  = ($("#sortableCities option:selected").val() != null) ? $("#sortableCities option:selected").val() : "";
		var vmonth = ($("#sortableMonthlyMonths option:selected").val() != null) ? $("#sortableMonthlyMonths option:selected").val() : "";
		var vyear  = ($("#sortableYears option:selected").val() != null) ? $("#sortableYears option:selected").val() : "";	
                var vsite  = ($("#sortableSite option:selected").val() != null) ? $("#sortableSite option:selected").val() : "";
		$.post("/pocketfives/sortablerankings.php", { cid: vcid, rid: vrid, city: vcity, format: $("#sortableFormats option:selected").val(), year: vyear, month: vmonth,site: vsite },
				function(data){
				    $("#resultsContent").html(data);
				    $("#getSortableResults").removeAttr("disabled");
				 });
	});
		  
	$("#sortableFormats").change(function(){
		if($("#sortableFormats option:selected").val() == "sd"){
			//$("#sortableMonthlyMonths").hide();
			//$("#sortableYears").hide();
			//$("#slidingDate").show();
      $("#sortable_date").hide();
		}else if($("#sortableFormats option:selected").val() == "mt"){
			 $("#sortable_date").show();
      $("#slidingDate").hide();
			$("#sortableMonthlyMonths").show();
			$("#sortableYears").show();
		}else if($("#sortableFormats option:selected").val() == "yl"){
      $("#sortable_date").show();
			$("#sortableMonthlyMonths").hide();
			$("#slidingDate").hide();
			$("#sortableYears").show();
		}
	});
	
	//Hide forum descriptions individually
	$("a.fd-hide").click(function(){
		var load_id = $(this).attr("id");
		$(this).parent().hide();
		$(".fd-ajax").load("/customsettings.php?do=description&fid="+load_id);
	});
});


//Function to load new rankings when selected
function rankingsByDate(){	
	   $.post("/pocketfives/rankings.php", { date: $("#rankingsDate option:selected").val() },
	   function(data){
		   $("#content").html(data);
	   });
}


//Function to load new location when selected
function showSortableLocation(countryID, regionID, cityID) {
	$.cookie("countryID", countryID, { path: '/' });
	$.cookie("regionID", regionID, { path: '/' });
	$.cookie("cityID", cityID, { path: '/' });
	window.location.href = '/pocketfives/sortablerankings.php';
}


//Play new podcast file when url opened
function playPodcast(filename, action) {
    // If there is already a podcast being played... just changes the URL
    if ((window.parent != null) && (window.parent != window) && (window.parent.frames["podcastFrame"] != null)) {
        window.parent.frames["podcastFrame"].location = "/pocketfives/browseandpodcast.php?reference=" + filename;
    }else{
    	$.post(action, { reference: filename }, function(data){
    		window.location.href = action;
    	});
	    
	}
}

//URL Decode
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;
	}


//URL Encode
function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
	    var match = regex.exec(clearString.substr(x));
	    if (match != null && match.length > 1 && match[1] != '') {
	    	output += match[1];
	      x += match[1].length;
	    } else {
	      if (clearString[x] == ' ')
	        output += '-';
	      else {
	        var charCode = clearString.charCodeAt(x);
	        var hexVal = charCode.toString(16);
	        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
	      }
	      x++;
	    }
	  }
	  return output;
}



//Parse text for SEO
function text2seo(text) {
	text=URLDecode(text);
	text=text.replace(/[^a-zA-Z-0-9]+/g,'-');
	text=text.toLowerCase();
	return text;
}

// Function for new thread post with option to choose the forum

function fn_select_forum(item) {

            document.getElementById("hidden_f").value=item.value;
            document.forms["forum-post"].action="newthread.php?do=postthread&amp;f="+item.value;

}



function global_ad_remove(user_id,ad_id) {
  
  
   $("#p5s-top-ad").remove();
   $.post("/pocketfives/ajax_functions.php", {type : "global_ad_remove", user_id: user_id, ad_id: ad_id },
        function(data) {
          
    });
  
}

function submit_hendonmob_ad() {
    
     //var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
     var RegExp = /http\:\/\/pokerdb\.thehendonmob\.com\/player\.php\?a=r&n=[0-9]+/;


     var hendonmob_url = $("#hendonmob_text").val(); 
     
     // If valid URL
     if(RegExp.test(hendonmob_url)){
        
        $("#hendonmob-box").remove();
        $.post("/pocketfives/ajax_functions.php", {type : "hendonmob", user_url: hendonmob_url},
            function(data) {
                alert(data);
        });
        
     }else{
         alert("Error inserting URL. Please use an URL with this format:  http://pokerdb.thehendonmob.com/player.php?a=r&n=100");
     }   
    
    
    
}
