$(document).ready(function () {
	var objects = jQuery.makeArray($('aside.section_rhs article.advertising img'));

	// quick links
	$('#expandcollapse,#expandcollapse2,#expandcollapse3').jqcollapse({});
	$("ul.quick_links_tabs").tabs("div.quick_links_panes > section");
	$('#expandcollapse li').click(function(){ 
		$(this).toggleClass('selected');
	});
	$('#expandcollapse2 li').click(function(){ 
		$(this).toggleClass('selected');
	});
	$('#expandcollapse3 li').click(function(){ 
		$(this).toggleClass('selected');
	});

	// results checker
	$(".result_checker h1,.result_checker h2,.result_checker h3,.result_checker ol h3").textShadow();

	// Articles

	$('input').focus(function () {
					$(this).parent().parent().addClass('active');
				}).blur(function () {
					$(this).parent().parent().removeClass('active');
				});
	// Site choice overlay - add back later with spider detection
//	$(".choose_site").colorbox({width:415, inline:true, href:"#choose_site", open:true});
	
	// Scrolling logos home page
	$(".logo_scroller").simplyScroll({
			className: 'custom',
			autoMode: 'loop',
			pauseOnHover: true,
			frameRate: 80,
			speed: 1
	});
	
	// DESIGN Function for Games page	
	$(function() {
	var $menu			= $('.games_list_legend li:not(.inactive)'),
		$container		= $('.games'),
		$content		= $container.find('.list_of_games');
			
			/*
			lets add the classes effect, e-fade, and e-color to some elements.
			e-fade : this will decrease the opacity of the element
			e-color: this will change the color of the element
			*/		
			$content
			.find('li')
			.addClass('effect e-fade')
			.end()
			.find('.game_initial')
			.addClass('effect e-fade');
				
			/*
			elems is all the elements with class effect.
			overlayEffect is our function / module that will take care of the animations
			*/	
			var $elems			= $(document).find('.effect'),
				OverlayEffect 	= (function(){
						//speed for animations
					var speed				= 500,
						//the event that triggers the effect
						eventOff			= 'mouseenter',
						//the event that stops the effect
						eventOn				= 'mouseleave',
						//this is the color that the elements will have after eventOff
						colorOff			= '#AAAAAA',
						//saves the original color of each e-color element,
						//and calls the methos to initialize the events
						init				= function() {
							$elems.each(function(){
								var $el		= $(this);
								if($el.hasClass('e-color'))	
									$el.data('original-color',$el.css('color'));
							});
							initEventsHandler();
						},
						//initializes the events eventOff / eventOn
						initEventsHandler 	= function() {
							$menu
							.delegate('a',eventOff,function(e){
								//relation is the id of the element, 
								//and the class of related elements
								var relation	= $(this).attr('class');
								animateElems('off',relation);
								return false;
							})
							.delegate('a',eventOn,function(e){
								var relation	= $(this).attr('class');
								animateElems('on',relation);
								return false;
							});	
						},
						//animates the color and / or opacity
						animateElems		= function(dir,relation) {
							var $e	= $elems;
							
							switch(dir){
								case 'on'	:
									//if there are elements on the page with class = relation
									//then these elements will be excluded for the animation
									if(relation)
										$e	= $elems.not('.'+relation);
									
									$e.each(function(){
										var $el		= $(this),
											color	= $el.data('original-color'),
											param	= {};
										
										if($el.hasClass('e-color'))
											param.color		= color;
										if($el.hasClass('e-fade'))
											param.opacity	= 1;

										$el.stop().animate(param,speed);	
									});
									
									break;
								case 'off'	:
									if(relation)
										$e	= $elems.not('.'+relation);
									
									$e.each(function(){
										var $el		= $(this),
											param	= {};
										
										if($el.hasClass('e-color'))
											param.color		= colorOff;
										if($el.hasClass('e-fade'))
											param.opacity	= 0.1;

										$el.stop().animate(param,speed);	
									});
									
									break;
							}
						};
						
					return {
						init				: init
					};
				})();
				
			/*
			call the init method of OverlayEffect
			*/
			OverlayEffect.init();
			});
			
			
			

		/*DEV UPDATE: Problem on mobile device. Does not scroll to section =(*/
		$(function() {
        
                function filterPath(string) {
                        return string
                        .replace(/^\//,'')
                        .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
                        .replace(/\/$/,'');
                }
        
                var locationPath = filterPath(location.pathname);
                var scrollElem = scrollableElement('html', 'body');
        
                // Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
                $('a[href*=#]').each(function() {
        
                        // Ensure it's a same-page link
                        var thisPath = filterPath(this.pathname) || locationPath;
                        if (  locationPath == thisPath
                                && (location.hostname == this.hostname || !this.hostname)
                                && this.hash.replace(/#/,'') ) {
        
                                        // Ensure target exists
                                        var $target = $(this.hash), target = this.hash;
                                        if (target) {
        
                                                // Find location of target
                                                var targetOffset = $target.offset().top;
                                                $(this).click(function(event) {
        
                                                        // Prevent jump-down
                                                        event.preventDefault();
        
                                                        // Animate to target
                                                        $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
        
                                                                // Set hash in URL after animation successful
                                                                location.hash = target;
        
                                                        });
                                                });
                                        }
                        }
        
                });
        
                // Use the first element that is "scrollable"  (cross-browser fix?)
                function scrollableElement(els) {
                        for (var i = 0, argLength = arguments.length; i <argLength; i++) {
                                var el = arguments[i],
                                $scrollElement = $(el);
                                if ($scrollElement.scrollTop()> 0) {
                                        return el;
                                } else {
                                        $scrollElement.scrollTop(1);
                                        var isScrollable = $scrollElement.scrollTop()> 0;
                                        $scrollElement.scrollTop(0);
                                        if (isScrollable) {
                                                return el;
                                        }
                                }
                        }
                        return [];
                }
        
        });


	// WRAPPER RELATED --------------------------------------

	// TOOLTIPS
	// tooltip for the region selection
	$("ul.chooseregion li a[title]").tooltip({
		offset: [10, 2],
		effect: 'slide'
	}).dynamic({ bottom: { direction: 'down', bounce: true } });

	// tooltip for social network links
	$("ul.nav li a[title]").tooltip({
		offset: [10, 2],
		effect: 'slide',
		tipClass:'socialnetworks'
	}).dynamic({ bottom: { direction: 'down', bounce: true } });

	// tooltip for interactive map
	$(".select_state a[title]").tooltip({
		offset: [10, 2],
		effect: 'slide',
		position:'center right',
		tipClass:'selectstate_tooltip'
	}).dynamic({ left: { direction: 'down', bounce: true } });


	// LOGIN PANEL

	// Expand Panel
	$("#open").click(function(){
		$("div#login_panel").slideDown("slow");
	});

	// Collapse Panel
	$("#close").click(function(){
		$("div#login_panel").slideUp("slow");
	});

	// Switch buttons from "Log In | Register" to "Close Panel" on click
	$("#toggle a").click(function () {
		$("#toggle a").toggle();
	});

	// Overlay for check which site the user wants, the closest or the current site
	$("#region_choice").overlay({

		// custom top position
		top: 260,

		mask: {
			color: '#fff',
			loadSpeed: 200,
			opacity: 0.5
		},
		closeOnClick: false,
		// load it immediately after the construction
		load: true
	});


	//---------------------------------------------------------------------
	// Code for Member's Account

	// Display the Region box on editing Personal Details
	$("#country").change(function(){
		if ($("#country").val() == 'AU') {
			$('#regionHeading').show();
			$("#regionBoxes").show();
			$('#region_au').show();
			$('#region_ca').hide();
			$('#region_us').hide();
		}
		else if ($("#country").val() == 'CA') {
			$('#regionHeading').show();
			$("#regionBoxes").show();
			$('#region_ca').show();
			$('#region_au').hide();
			$('#region_us').hide();
		}
		else if ($("#country").val() == 'US') {
			$('#regionHeading').show();
			$("#regionBoxes").show();
			$('#region_us').show();
			$('#region_au').hide();
			$('#region_ca').hide();
		}
		else {
			$('#regionHeading').hide();
			$("#regionBoxes").hide();
			$('#region_au').hide();
			$('#region_us').hide();
			$('#region_ca').hide();
		}
	});

	// Do initial hide on startup
	$('#regionHeading').hide();
	$("#regionBoxes").hide();
	$('#region_au').hide();
	$('#region_us').hide();
	$('#region_ca').hide();

	$("#country").change();

	//---------------------------------------------------------------------
	// Code for Contact Us page

	$('select[name="topic"]').change(function(){
		if ($('select[name="topic"]').val() == 'Game Does Not Exist') {
			$('textarea[name="message"]').val('I would like to view the game GAME_NAME_HERE, played in GAME_REGION_INFO_HERE as it does not exist on your website.');
		}
		else {
			$('textarea[name="message"]').val('');
		}
	});


	//---------------------------------------------------------------------
	// FOR USE IN MULTIPLE PAGES ---------------------------------

	// mouseover effect for images named with _up or _down at end of filename (regardless of file extension)
	$("#image_hover img").hover(
		 function() {
			this.src = this.src.replace("_up","_dwn");
		 },
		 function() {
			this.src = this.src.replace("_dwn","_up");
		}
	);

	// refresh page button click
	$('#Refresh').click(function() {
		location.reload();
	});

	// For links where login is required, go to login page if 
	// not already logged in. A span is in wrapper for indicating
	// if logged in.
	$('a.login_required,form.login_required').click(
		function(eventObj) {
			if (! $('#login_indicator').hasClass('logged_in') ) {
				$('#modal_login_original_page').val(eventObj.target.href);

				$.colorbox({width:550, inline:true, href:"#modal_login_display"});
				return false;
			}
			return true;
		}
	);

});

// parse the entry type numbers so it's humanely readable
// separated by the sets
// TODO: may move to elsewhere
function textReadableEntryTypeNumbers(numbers) {
	var output = "";
	for (var i = 0; i < numbers.length; i++) {
		var set = numbers[i];
//		output += "Set " + (i + 1) + ": ";
		for (var j = 0; j < set.length; j++) {
			output += set[j];

			if (j < set.length - 1)
				output += " - ";
		}

		if ( i < numbers.length - 1)
			output += " | ";
	}
	return output;
}

// Function used by front page and also by game pages to set todays
// date to have 0 time.

function fpt_today() {
	// Truncate the current timestamp to today's date
	var today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);
	return today;
}
// Dreamweaver image routines
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// Javascript Cookies

function createCookie(name, value, days) {
	var expires = "";

	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}

	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var namePart = name + "=";
	var cookieArray = document.cookie.split(";");
	var cookie = $.grep(
		cookieArray, 
		function(element, index) {
			var cookieText = $.trim(element);
			return cookieText.indexOf(namePart) == 0;
		}
	);
	
	if (cookie) {
		var cookieText = $.trim(cookie);
		return cookieText.substring(namePart.length, cookieText.length);
	}

	return "";
}

function deleteCookie(name) {
	createCookie(name, "", -1);
}

