function tipsy(target_items, name) {
    $(target_items).each(function(i) {
        $(this).tipsy({gravity: $.fn.tipsy.autoNS});
    });
}

//	jquery - qTips/simple tooltip
function simple_tooltip(target_items, name) {
	$(target_items).each(function(i) {
		$("body").append('<div class="' + name + '" id="' + name + i + '"><p>' + $(this).attr('title') + '</p></div>');
		var my_tooltip = $('#' + name + i);

		var height = $('#' + name + i).height();
		var width = $('#' + name + i).width();

		var top  = $(this).offset().top - (height);
		var left = $(this).offset().left + ($(this).width() / 2) + (width / 2);
		
		var tooltipWidth = my_tooltip.outerWidth();

		$(this).removeAttr('title').mouseover(function() {
			my_tooltip.css({'display': 'none', 'left': left, 'top': top}).fadeIn();
		}).mousemove(function(kmouse) {
			my_tooltip.css({left:kmouse.pageX-tooltipWidth, top:kmouse.pageY+30});
		}).mouseout(function() {
			my_tooltip.fadeOut();
		});
	});
}

$(document).ready(function() {
	Shadowbox.init();

	simple_tooltip('.productinfo .bundles .productinfo-button, .cart-product .bundle, #gift_help', 'tooltip');
	$('.status-info').tipsy();

	$('.cart-product').each(function() {
		$(this).bind({
			mouseover: function() {
				$(this).find('.remove').css({'text-indent': '20px', 'width': 'auto'});
			},
			mouseout: function() {
				$(this).find('.remove').css({'text-indent': '-9999em', 'width': '22px'});
			}
		});
	});

	if ($('#discount').length) {
		$('#discount').click(function() {
			$('#redeem-a-voucher').slideToggle('slow');
			$(this).html($(this).html() == 'enter a discount code' ? 'I have no discount code' : 'enter a discount code');
			return false;
		});
	}

	if ($('header .just-added-to-cart').length) {
		$('header .just-added-to-cart').fadeIn();
	}

	if ($('#advanced-search').length) {
		$('#advanced-search').click(function() {
			 $('#adv-search-box').toggle();
			 return false;
		 })
	}

	if ($('#survey-link').length) {
		var display_survey = setInterval("$('#survey-link').click().hide()", 1000);
	}

	if ($('nav .product-search').length) {
		$('nav .product-search a').hover(function() {
			$(this).css('z-index', 50);
			$('nav .product-search form').css({'z-index': 100, 'position': 'absolute', 'top': '0', 'right': '10px'}).show();
			return false;
		});
	}

	if ($('.product-search #search').length) {
		display_product_search = setInterval("$('.product-search #search').fadeOut()", 1000);
		$('.product-search #search').hover(function() {
			clearInterval(display_product_search);
			display_product_search = null;
		}, function() {
			if	(!display_product_search) {
				display_product_search = setInterval("$('.product-search #search').fadeOut()", 1000);
			}
		});
	}

	$('#survey-link').click(function() {
		Shadowbox.open({
        	content:    '/show_survey.php',
	        player:     'iframe',
	        title:      'GameTree Mac survey',
	        width:      800,          
	        height:     480
		});
		clearInterval(display_survey);
	});

	//	Run our display_products() function every 5 seconds
	var display_products_interval = setInterval("$('#mac-games-next').click()", 5000);
	$('#mac-games-thumbnails li:first-child a').addClass('active');
	var promo			=	$('#mac-games-thumbnails .active span').html();
	$('#mac-games span').addClass(promo).fadeIn();

	$('#mac-games-thumbnails li a').hover(function() {
		$('#mac-games span').hide().removeClass();

		var new_alt		=	$(this).find('strong').html();
		var new_src		=	$(this).attr('rel');
		var new_link	=	$(this).attr('href');
		var price		=	$(this).find('em').html();

		$('#mac-games-thumbnails li a').removeClass('active');
		$(this).addClass('active');
		var promo		=	$('#mac-games-thumbnails .active span').html();
		$('#mac-games span').addClass(promo).fadeIn('fast');

		$('#mac-games li a').attr({href: new_link, title: new_alt});
		$('#mac-games li a em').html(new_alt+' - buy now from GameTree Mac');
		$('#mac-games img').attr({src: new_src, alt: new_alt, title: new_alt});
		$('#mac-games-description strong').html(new_alt);
		$('#mac-games-description em').html(price);

		//	Animate the Teaser
		$('#mac-games-description').stop(true, true).fadeIn(500);
	}, function() {
		$('#mac-games-description').fadeOut(750);
		$(this).addClass('active');
	})
	

	//	maybe move this into the .hover() state to get rid of the flickering
	$('#mac-games a').hover(function() {
		$('#mac-games span').fadeOut();
		$('#mac-games-description strong, #mac-games-description em').hide();
		$('#mac-games-description strong').show().html($('#mac-games-thumbnails .active').find('strong').html());
		$('#mac-games-description em').show().html($('#mac-games-thumbnails .active').find('em').html());
		$('#mac-games-description').stop(true, true).fadeIn();
	}, function() {
		$('#mac-games span').stop(true, true).fadeIn();
		$('#mac-games-description').stop(true, true).fadeOut();
	});

	//	pause rotator when the user is selecting a game
	$('#mac-games-rotator').mouseover(function() {
		clearInterval(display_products_interval);
		display_products_interval = null;
	}).mouseout(function () {
		if (!display_products_interval) {
			//Only create a new timer if one doesn't already exist
			display_products_interval = setInterval("$('#mac-games-next').click()", 5000);
		}
	});

	//	tabber
	var tabs = $('.tabber-content');

	$('#tabs a').click(function() {
		tabs.hide();
		tabs.filter(this.rel).show();

		$('#tabs a').removeClass('selected');
		$(this).addClass('selected');
		return false;
	}).filter(':first').click();

	$('#flash').hide().fadeIn('slow');

	if ($('#tweets').length) {
		$("#tweets").tweet();
	}

	$('#can-you-run-it-link').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 1000);
				return false;
			}
		}
	});

	if ($('#datepicker').length) {
		$('#datepicker').datepick({dateFormat: 'MM d, yyyy', showTrigger: '<label for="dp-img">' + tg_lbl_gift_or + ' (up to ' + gift_max_delivery_days + ' days from today):</label><img id="dp-img" src="/skin1/img/calendar.png" alt="calendar" title="calendar" /><span id="dp_text">' + gift_date + '</span>', minDate: 0, maxDate: '+' + gift_max_delivery_days + 'D', onShow: function() { $('#now').attr('checked', false) }, onClose: function() { $('span.datepick-trigger').html($('#datepicker').val()) }});
	}

	if ($('#now').length) {
		$('#now').click(function() {
			$('#datepicker').val('');
			$('span.datepick-trigger').html('');
		});
	}

    function update_optout() {
        $('#email-subscriptions').toggle(!$('#optout').is(':checked'));
    }

    $('#optout').click(function() {
        update_optout();
    });

    update_optout();
    
  $('a.post-link').click(function(event){
    event.preventDefault();
    $this = $(this);
    $this.wrap('<form action="' + $this.attr('href') + '" method="POST" class="post-link-form"></form>');
    $this.closest('form').submit();
  });
  
  $('.wishlist-url').click(function(){
    $(this).focus().select();
  });
  
  
  
  
  
  
  
  // Help Technical Support Page Game Search
  var $helpTechSupport = $('.help-tech-games');
  if ($helpTechSupport.length > 0) {
    
    helpTech = function(){
      $items = $helpTechSupport.find('.help-tech-game-list li');
      $input = $helpTechSupport.find('input:text');
      
      var updateList = function(event, firstRun){
        var value = $input.val().toLowerCase();
        if (value === '' && !firstRun){
          $items.show();
        } else if (value) {
          $items.each(function(){
            $item = $(this);
            var index = $item.find('.help-tech-game-name').text().toLowerCase().indexOf(value);
            if (index === -1){
              $item.hide();
            } else {
              $item.fadeIn(400);
            }
          }); 
        }
      };      
      $input.keyup($.debounce(200, updateList));
      updateList(null, true);
    }
    helpTech();
  }
  
  var $helpFAQ = $('.help-faq-questions');
  if ($helpFAQ.length > 0){
    var $helpFAQTitle = $helpFAQ.find('dt');
    var $helpFAQData = $helpFAQ.find('dd');
    $helpFAQData.hide();
    $helpFAQ.addClass('active');
    $helpFAQTitle.click(function(){
      var $this = $(this);
      $this.toggleClass('opened').next().toggle();
    });
    
    var hash = window.location.hash;
    if (hash !== ''){
      $helpFAQTitle.find('a[name='+ hash.slice(1) + ']').click();
    }
  }
  
  
  
  
  
  
  
  

});

// JQuery tipsy plugin
(function(b){function a(d,c){this.$element=b(d);this.options=c;this.enabled=true;this.fixTitle()}a.prototype={show:function(){var f=this.getTitle();if(f&&this.enabled){var e=this.tip();e.find(".tipsy-inner")[this.options.html?"html":"text"](f);e[0].className="tipsy";e.remove().css({top:0,left:0,visibility:"hidden",display:"block"}).appendTo(document.body);var i=b.extend({},this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight});var c=e[0].offsetWidth,h=e[0].offsetHeight;var g=(typeof this.options.gravity=="function")?this.options.gravity.call(this.$element[0]):this.options.gravity;var d;switch(g.charAt(0)){case"n":d={top:i.top+i.height+this.options.offset,left:i.left+i.width/2-c/2};break;case"s":d={top:i.top-h-this.options.offset,left:i.left+i.width/2-c/2};break;case"e":d={top:i.top+i.height/2-h/2,left:i.left-c-this.options.offset};break;case"w":d={top:i.top+i.height/2-h/2,left:i.left+i.width+this.options.offset};break}if(g.length==2){if(g.charAt(1)=="w"){d.left=i.left+i.width/2-15}else{d.left=i.left+i.width/2-c+15}}e.css(d).addClass("tipsy-"+g);if(this.options.fade){e.stop().css({opacity:0,display:"block",visibility:"visible"}).animate({opacity:this.options.opacity})}else{e.css({visibility:"visible",opacity:this.options.opacity})}}},hide:function(){if(this.options.fade){this.tip().stop().fadeOut(function(){b(this).remove()})}else{this.tip().remove()}},fixTitle:function(){var c=this.$element;if(c.attr("title")||typeof(c.attr("original-title"))!="string"){c.attr("original-title",c.attr("title")||"").removeAttr("title")}},getTitle:function(){var e,c=this.$element,d=this.options;this.fixTitle();var e,d=this.options;if(typeof d.title=="string"){e=c.attr(d.title=="title"?"original-title":d.title)}else{if(typeof d.title=="function"){e=d.title.call(c[0])}}e=(""+e).replace(/(^\s*|\s*$)/,"");return e||d.fallback},tip:function(){if(!this.$tip){this.$tip=b('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>')}return this.$tip},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled}};b.fn.tipsy=function(g){if(g===true){return this.data("tipsy")}else{if(typeof g=="string"){var i=this.data("tipsy");if(i){i[g]()}return this}}g=b.extend({},b.fn.tipsy.defaults,g);function f(k){var l=b.data(k,"tipsy");if(!l){l=new a(k,b.fn.tipsy.elementOptions(k,g));b.data(k,"tipsy",l)}return l}function j(){var k=f(this);k.hoverState="in";if(g.delayIn==0){k.show()}else{k.fixTitle();setTimeout(function(){if(k.hoverState=="in"){k.show()}},g.delayIn)}}function e(){var k=f(this);k.hoverState="out";if(g.delayOut==0){k.hide()}else{setTimeout(function(){if(k.hoverState=="out"){k.hide()}},g.delayOut)}}if(!g.live){this.each(function(){f(this)})}if(g.trigger!="manual"){var c=g.live?"live":"bind",h=g.trigger=="hover"?"mouseenter":"focus",d=g.trigger=="hover"?"mouseleave":"blur";this[c](h,j)[c](d,e)}return this};b.fn.tipsy.defaults={delayIn:0,delayOut:0,fade:false,fallback:"",gravity:"n",html:false,live:false,offset:0,opacity:0.8,title:"title",trigger:"hover"};b.fn.tipsy.elementOptions=function(d,c){return b.metadata?b.extend({},c,b(d).metadata()):c};b.fn.tipsy.autoNS=function(){return b(this).offset().top>(b(document).scrollTop()+b(window).height()/2)?"s":"n"};b.fn.tipsy.autoWE=function(){return b(this).offset().left>(b(document).scrollLeft()+b(window).width()/2)?"e":"w"}})(jQuery);

/*
  * jQuery throttle / debounce - v1.1 - 3/7/2010
  * http://benalman.com/projects/jquery-throttle-debounce-plugin/
  * Required for Help Technical Support Page
*/
 (function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);
