(function($) {
 /* ==================== */
/*  Fix Content Height  */
  jQuery.contentHfix = function() {
		var windowH = $(window).height();
		var contentColumnH = $("#contentColumn").height() + 100;
		var headerH = $("#header").height();
		var footerH = $("#footer").height();
		var fullContentH = contentColumnH + headerH + footerH;
		var resizeH = windowH - headerH;
		
		if (fullContentH < windowH) {
			$("#content").css({ height: resizeH + "px" });
		}
	};
	
	
 /* =================== */
/*  Fix Content Width  */
  jQuery.contentWfix = function() {
		var windowW = $(window).width();
		var contentW = $("#content").width();
		var marginW = (windowW - contentW) / 2;
		$("#header, #headerBg, #headerFg, #footer, #footerBg, #content").css({ margin: "0 " + marginW + "px 0 " + marginW + "px" });
	};
	
	
 /* ================================= */
/*  Rotate Site's Background Images  */
  jQuery.bg_img_rotate = function(randomImages) {
		var rndNum = Math.floor(Math.random() * randomImages.length);

	  $('<img />').attr('src', "/img/bg/" + randomImages[rndNum] + ".jpg").load(function() {
			$("body, #headerBg").css({ backgroundImage: "url(/img/bg/" + randomImages[rndNum] + ".jpg)" });
		});
		
		return this;
	};
	
	
 /* =========================== */
/*  Rotate Main Page's Images  */
  jQuery.main_img_rotate = function(randomImages) {
  	for (var x = 0; x < 5; x++) {
			$(".main_img_placeholder" + eval(x+1)).html('<a rel="image_group" href="/img/main/' + randomImages[x] + '.jpg"><img class="image_group_img" src="/img/main/' + randomImages[x] + '_sml.jpg" border="0" /></a>');
		}
		
		return this;
	};
	
	
 /* =================== */
/*  Add Magnify Image  */
  jQuery.add_magnify = function(e) {
		for (var x = 0; x < $("a[rel=image_group]").length; x++) {
			var p = $("a[rel=image_group] img.image_group_img").eq(x);
			var pos = p.position();
			
			$("a[rel=image_group]").eq(x).prepend('<img class="magnify" src="/img/plus.png" border="0" />');
			
			$("a[rel=image_group] img.magnify").eq(x).css({'z-index': 1001, 'top': pos.top+p.height()-20, 'left': pos.left+p.width()-20});
		}
		
		return this;
	};
	
	
 /* ========================= */
/*  Ajax load selected Game  */
	jQuery.getGame = function(page) {
		$(".gameDetails").load("partials/" + page + ".html").hide().fadeIn(1000);
		
		$(".gameCoverWrapper img").removeClass("active");
		$(".gameCoverWrapper img:hover").addClass("active");
	};
	
	
 /* ========================= */
/*  Ajax load selected Game  */
	jQuery.getGameForStudio = function(page, base_path) {
		if (!base_path) {
			base_path = "";
		}
		
		$(".studioGameDetails").load(base_path + "partials/" + page + ".html").hide().fadeIn(1000);
		
		$(".studioGamesWrapper img").removeClass("active");
		$(".studioGamesWrapper img:hover").addClass("active");
	};
	
	
 /* ================== */
/*  Timeline Control  */
	jQuery.timelineYears = function(group,goto) {
		$(".timelineYears").removeClass("active");
		
		$(".gameCovers").tinycarousel({start:goto, duration:2500});
		
		$(".gameCoverWrapper img").animate({opacity: 0.50}, 500);
		$("." + group + " .gameCoverWrapper img").animate({opacity: 1}, 250);
	};
	
	
 /* ================== */
/*  Shuffle Elements  */
	$.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length) ? $(this).html($.shuffle(items)): this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
	

 /* ========================================== */
/*  Carousel Fonction for Games and Partners  */
	$.fn.tinycarousel = function(options){
		var defaults = { 
			start: 1, // where should the carousel start?
			display: 1, // how many blocks do you want to move at 1 time?
			axis: 'x', // vertical or horizontal scroller? ( x || y ).
			controls: true, // show left and right navigation buttons.
			pager: false, // is there a page number navigation present?
			interval: false, // move to another block on intervals.
			intervaltime: 250, // interval time in milliseconds.
			animation: true, // false is instant, true is animate.
			duration: 500, // how fast must the animation move in ms?
			callback: null, // function that executes after every move
			itemstoshow: 7
		};
		
		var options = $.extend(defaults, options);  
		var oSlider = $(this);
		var oViewport = $('.viewport', oSlider);
		var oContent = $('.overview', oSlider);
		var oPages = oContent.children().children();
		var oBtnNext = $('.nav_right', oSlider);
		var oBtnPrev = $('.nav_left', oSlider);
		var oPager = $('.pager', oSlider);
		var iPageSize, 
				iSteps, 
				iCurrent, 
				oTimer, 
				bForward = true, 
				bAxis = options.axis == 'x';

		return this.each(function(){
			initialize();
		});
		
		function initialize(){
			iPageSize = bAxis ? $(oPages[0]).outerWidth(true) : $(oPages[0]).outerHeight(true);
			var iLeftover = Math.ceil(((bAxis ? oViewport.outerWidth() : oViewport.outerHeight()) / (iPageSize * options.display)) -1);
			iSteps = Math.max(1, Math.ceil(oPages.length / options.display) - iLeftover + options.itemstoshow);
			iCurrent = Math.min(iSteps, Math.max(1, options.start)) -2;
			oContent.css(bAxis ? 'width' : 'height', (iPageSize * oPages.length));
			move(1);
			setEvents();
		}
		
		function setButtons(){
			if(options.controls){
				oBtnPrev.toggleClass('disable', !(iCurrent > 0));
				oBtnNext.toggleClass('disable', !(iCurrent < iSteps - options.itemstoshow));
			}
		}
		
		function setEvents(){
			if(options.controls && oBtnPrev.length > 0 && oBtnNext.length > 0){
				var gameTimer;
				
				oBtnPrev.click(function(){
					move(-1); return false;
				});
								
				oBtnNext.click(function(){
					move(1); return false;
				});
			}
			
			if(options.pager && oPager.length > 0){
				oPager.click(setPager);
			}
		}
		
		function setPager(oEvent){
			var oTarget = oEvent.target;
			
			if($(oTarget).hasClass('pagenum')){
				iCurrent = parseInt(oTarget.rel) -1;
				move(1);
			}
			
			return false;
		}
		
		function setPagerActive(){
			if(options.pager){
				var oNumbers = $('.pagenum', oPager);
				oNumbers.removeClass('active');
				$(oNumbers[iCurrent]).addClass('active');
			}
		}
		
		function setTimer(bReset){
			if(options.interval && !bReset){
				clearInterval(oTimer);
				oTimer = window.setInterval(function(){
					bForward = iCurrent +1 == iSteps ? false : iCurrent == 0 ? true : bForward;
					move(bForward ? 1 : -1, true);
				}, options.intervaltime);
			}
		}
		
		function move(iDirection, bTimerReset){
			if (iCurrent + iDirection > -1 && iCurrent + iDirection < iSteps){
				iCurrent += iDirection;
				var oPosition = {};
				oPosition[bAxis ? 'left' : 'top'] = -(iCurrent * (iPageSize * options.display));	
				oContent.animate(oPosition,{
					queue: false,
					duration: options.animation ? options.duration : 0,
					complete: function(){
						if (typeof options.callback == 'function') {
							options.callback.call(this, oPages[iCurrent], iCurrent);
						}
					}
				});
				
				setButtons();
				setPagerActive();
				setTimer(bTimerReset);
			}
		}
	};
	
	
 /* ========================= */
/*  Navigation Menu Control  */
	function menu() {
		var defaults = {
			vertical:false,
			menuItemSelector: 'li',
			menuGroupSelector: 'ul',
			rootClass:'menu',
			menuItemClass:'menu-item',
			menuGroupClass:'menu-group',
			verticalClass:'menu-vertical',
			holizontalClass:'menu-holizontal',
			hasVerticalClass:'menu-has-vertical',
			hasHolizontalClass:'menu-has-holizontal',
			hoverClass:'menu-hover',
			groupOffsetHorizontal: 10,
			groupOffsetVertical: 5,
			showDuration: 1000,
			hideDuration: 250
		}
		
		var option = (typeof(arguments[0])!='string') ? $.extend(defaults,arguments[0]) : $.extend(defaults,{});
		var $menu = $(this).addClass(option.rootClass+' '+option.menuGroupClass).addClass((option.vertical) ? option.verticalClass : option.holizontalClass);
		var $menuItems = $menu.find(option.menuItemSelector).addClass(option.menuItemClass);
		var $menuGroups = $menu.find(option.menuGroupSelector).addClass(option.menuGroupClass);
		
		$menuItems.hoverIntent({
      timeout: 500,
      over: function(e) { 
      	$(this).addClass(option.hoverClass); 
      }, 
      out: function(e) { 
      	$(this).removeClass(option.hoverClass); 
      }
    });
		
		$menuGroups.parent().each(function(index){
			var $parentMenuItem = $(this); // menu item that has menu group
			var displayDirection = ($parentMenuItem.parent().hasClass(option.holizontalClass)) ? 'bottom' : 'right';
			$parentMenuItem.addClass((displayDirection=='bottom') ? option.hasVerticalClass : option.hasHolizontalClass);
			var $menuGroup = $parentMenuItem.find(option.menuGroupSelector+':first').addClass(option.verticalClass);
			
			$parentMenuItem.hoverIntent({
	      timeout: 500,
	      over: function(e) { 
					var offset = (displayDirection=='bottom') ? {left:'0',top:''} : {left:$(this).width() + option.groupOffsetHorizontal + 'px',top:option.groupOffsetVertical + "px"};
					$menuGroup.css({left:offset.left,top:offset.top}).fadeIn(option.showDuration);
	      }, 
	      out: function(e) { 
					$menuGroup.fadeOut(option.hideDuration);
	      }
	    });
		});
		
		$menu.find('a[href^="#"]').click(function() {
			$menuGroups.fadeOut(option.hideDuration);
			return ($(this).attr('href') != '#');
		})
		
		return this;
	}
	
	$.fn.extend({
		ptMenu:menu
	});


 /* ========================= */
/*  Mouseover when intended  */
	$.fn.hoverIntent = function(f,g) {
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};

		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		var cX, cY, pX, pY;
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				pX = cX; pY = cY;
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		var handleHover = function(e) {
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			var ev = jQuery.extend({},e);
			var ob = this;

			if (ob.hoverIntent_t) { 
				ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			}

			if (e.type == "mouseover") {
				pX = ev.pageX; pY = ev.pageY;
				$(ob).bind("mousemove",track);
				
				if (ob.hoverIntent_s != 1) { 
					ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );
				}
			} else {
				$(ob).unbind("mousemove",track);

				if (ob.hoverIntent_s == 1) { 
					ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );
				}
			}
		};

		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);


 /* =================== */
/*  On Document Ready  */
$(document).ready(function(){ 
	$('#menu').ptMenu();
	
	$(".popIframe").fancybox({
		'titleShow'		: false,
		'width'					: '90%',
		'height'				: '90%',
		'autoScale'			: false,
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'type'					: 'iframe'
	});
	
	$(document).pngFix();
	
	var bgImages = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o"];
	$.bg_img_rotate(bgImages);

	var mainImages = ["a","b","c","d","e","f","g","h","i"];
	mainImages = $.shuffle(mainImages);
	$.main_img_rotate(mainImages);
	$.add_magnify();
	
	$("a[rel=image_group]").fancybox({
		'titleShow'		: false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'
	});
		
	
	var newsticker = 0;
	$(".news_headlines_imgs a").eq(newsticker).fadeIn(500);
	$(".news_headlines .news_article h3").eq(newsticker++).addClass("active");
	
	newsTimer = setInterval(function(){
		$(".news_headlines_imgs a").hide();
		$(".news_headlines .news_article h3").removeClass("active");
		$(".news_headlines_imgs a").eq(newsticker).fadeIn(500);
		$(".news_headlines .news_article h3").eq(newsticker++).addClass("active");
		
		if (newsticker == 4) {
			newsticker = 0;
		}
	}, 3500);
	
	$(".tab_container .tab_content, img.tab_content").hide();
	$("ul.tabs li:first").addClass("active").show();
	$("ul.tabs li:first a").addClass("active");
	$("img.tab_content:first").show();
	$(".tab_container .tab_content:first").show();

	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active");
		$("ul.tabs li:first a").removeClass("active");
		$(this).addClass("active");
		$(".tab_content").hide();
		
		var activeTab = $(this).find("a").attr("href");
		$(activeTab).fadeIn();

		$.contentHfix();
		$.contentWfix();
		return false;
	});
	

	$.contentHfix();
	$.contentWfix();
	
	$(window).resize(function(){
		$.contentHfix();
		$.contentWfix();
	});
});

