var mouseX = null;
var mouseY = null;
var player = null;
var tabArray = new Array();

jQuery(function(){
	
	/* ---------- NAVIGATION ---------- */
	$("#navigation > li").hoverIntent({
		over: function(){$(this).children("ul").fadeIn();},
		out: function(){$(this).children("ul").fadeOut();}
	});
	
	$("#navigation .shop > ul > li").not(':last').css('border-bottom','1px solid #DEDEDE').css('margin-bottom','1em');
	
	/* ---------- TRADE OVERLAY ---------- */
	$("#trade-popup").fancybox({
		href:				'/shop/trade',
		type:				'iframe',
		width:				550,
		height:				250,
		overlayOpacity:		0.8,
		padding:			15
	});
	$("#overlay #set-trade").click(function(){
		var url = getTradeURL();
		parent.location = url+'trade=true';
		parent.$("#fancybox-overlay").fadeOut();
		parent.$("#fancybox-wrap").fadeOut();
	});
	$("#overlay #not-trade").click(function(){
		var url = getTradeURL();
		parent.location = url+'trade=false';
		parent.$("#fancybox-overlay").fadeOut();
		parent.$("#fancybox-wrap").fadeOut();
	});
	$("#sidebar .categories > ul > li > a").each(function(){
		var txt = $(this).text();
		$(this).replaceWith('<h5>'+txt+'</h5>');
	});

	/* ---------- TABBED CONTENT ---------- */
	$("#tabbed-content .tab-content").each(function(){
		$(this).css("position","relative").hide();
	});
	$("#tabbed-content .tabs li a").click(function(){
		var tabID = 'tab-'+$(this).attr("href").substring(1);
		$("#tabbed-content .tabs li").removeClass("selected");
		$(this).parent().addClass("selected");
		$("#tabbed-content .tab-content").slideUp('slow');
		$("#tabbed-content #"+tabID).slideDown('slow');
	}).each(function(){
		var tab = $(this).attr("href").substring(1);
		tabArray.push(tab);
	});
	
	// Check if we need a specific tab open
	var hash = window.location.hash;
	if(isTab(hash)) {
		hash = hash.replace("#","");
		$('#tabbed-content .tabs li a[href="#'+hash+'"]').parent().addClass("selected");
		$('#tabbed-content #tab-'+hash).show();
	} else {
		$('#tabbed-content .tabs li').first().addClass("selected");
		$('#tabbed-content .tab-content').first().show();
	}


	/* ---------- SHOPPING CART ---------- */
	$("input.empty-basket").click(function(){
		return confirm("Are you sure you want to empty everything from your basket?");
	});
	
	$("#orderCountry").change(function(){
		$("#update-shipping").fadeIn();
	});
	
	/* ---------- PAGINATION ---------- */
	$('select[name="sort"]').change(function(){
		$(this).closest('form').submit();
	});
	
	/* ---------- RATINGS ---------- */
	$(".title ul.rating a").click(function(){
		var id = $(this).closest("ul").attr("id").replace("rating-","");
		var val = $(this).attr("href").replace("#","");
		var data = {
			cmssid: cmssid,
			action:	'title-rating',
			rating:	val,
			title:	id
		};
		ajaxOb.postRequest('/site/assets/ajax.php',data,function(){
			var response = jsonParse(ajaxOb.xmlResponseText);
			if(response.error) {
				alert(response.error);
			} else {
				$("#rating-"+id).after('<div class="rating r'+response.rating+'"></div>');
				$("#rating-"+id).siblings("span").text('('+response.votes+' customer ratings)');
				$("#rating-"+id).remove();
			}
		});
	});
	

	$("#mixedup-gallery ul.rating a").click(function(){
		var id = $(this).closest("ul").attr("id").replace("rating-","");
		var val = $(this).attr("href").replace("#","");
		var data = {
			cmssid: cmssid,
			action:	'mixandmatch-rating',
			rating:	val,
			id:		id
		};
		ajaxOb.postRequest('/site/assets/ajax.php',data,function(){
			var response = jsonParse(ajaxOb.xmlResponseText);
			if(response.error) {
				alert(response.error);
			} else {
				$("#rating-"+id).after('<div class="rating r'+response.rating+'"></div>');
				$("#rating-"+id).siblings("span").text('('+response.votes+' votes)');
				$("#rating-"+id).remove();
			}
		});
	});
	

	$("#tab-comments div a").click(function(){
		var id = $(this).closest("li").attr("id").replace("comment-","");
		var dir = $(this).attr("href").replace("#","");
		var data = {
			action:	'comment-rating',
			id:		id,
			dir:	dir
		};
		ajaxOb.postRequest('/site/assets/ajax.php',data,updateCommentRatingsCallback);
	});
	
	/* ---------- ISSUU OVERLAY ---------- */
	$("#issuu-overlay").click(function(){
		var issuuUrl = 'http://static.issuu.com/webembed/viewers/style1/v1/IssuuViewer.swf?mode=embed&layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&showFlipBtn=true&documentId='+issuuVars.documentId+'&docName='+issuuVars.docName+'&username=topthat&loadingInfoText='+issuuVars.loadingInfoText+'&et='+issuuVars.et+'&er='+issuuVars.er;
		
		$.fancybox({
			href:				issuuUrl,
			type:				'swf',
			margin:				"10%",
			overlayOpacity:		0.8,
			swf:				{
				allowfullscreen:	true
			},
			onStart:			function() {
				$(".details-right iframe").hide();
			},
			onClosed:			function() {
				$(".details-right iframe").show();
			}
		});
	});
	
	/* ---------- YOUTUBE OVERLAY ---------- */
	$("#video-overlay").click(function(){
		$.fancybox({
			padding:		0,
			href:			this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			type:			'swf',
			overlayOpacity:	0.8,
			swf: {
				wmode:				'transparent',
				allowfullscreen:	'true'
			}
		});
		return false;
	});
	
	/* ---------- REVIEW VIDEO ---------- */
	$("#panel-reviews li.video a:first").click(function(){
		$.fancybox({
			padding:		0,
			href:			this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			type:			'swf',
			overlayOpacity:	0.8,
			swf: {
				wmode:				'transparent',
				allowfullscreen:	'true'
			}
		});
		return false;
	});

	/* ---------- LARGE IMAGE ---------- */
	$("a.large-title").fancybox({
		padding:		15,
		overlayOpacity:	0.8
	});
	
	/* ---------- ALTERNATE IMAGES ---------- */
	$("#alternate-images a").fancybox({
		padding:		15,
		overlayOpacity:	0.8
	});
	
	$("#mixedup-gallery a.creature").fancybox({
		padding:		15,
		overlayOpacity:	0.8
	});

	$('a[rel="fancybox"]').fancybox({
		overlayOpacity:		0.8,
		padding:			15
	})
	
	/* ---------- COMMENTS FORM ---------- */
	$("#showform").click(function(){
		$("#comment-form").slideDown();
		$(this).fadeOut();
	});
	
	/* ---------- STORY PAGE ---------- */
	$(".story #upload-story").fancybox({
		type:				'iframe',
		hideOnOverlayClick:	false,
		width:				600,
		height:				500,
		overlayOpacity:		0.8,
		padding:			15,
		'onCleanup':		function() {
			window.location.reload(true);
		}
	}).click(function(){
		$(this).fadeOut();
	});
	$(".story #upload-video").fancybox({
		type:				'iframe',
		hideOnOverlayClick:	false,
		width:				600,
		overlayOpacity:		0.8,
		'onCleanup':		function() {
			window.location.reload(true);
		}
	});
	
	/* ---------- THINGS TO DO RESPONSES ---------- */
	$("#response-gallery li.image-response a").fancybox({
		overlayOpacity:	0.8												
	});
	$("#response-gallery li.text-response a").each(function(){								 
		var overlayContent = '<div style="width:600px;"><h2>'+$(this).siblings('h4').text()+'</h2>'; 
		overlayContent += $(this).siblings('p').html();
		overlayContent += '</div>';
		$(this).fancybox({
			content:			overlayContent,
			overlayOpacity:		0.8,
			hideOnOverlayClick:	false
		});
	});
	$("#response-gallery li.video-response a").click(function() {
		$.fancybox({
			padding:			0,
			autoScale:			false,
			transitionIn:		'none',
			transitionOut:		'none',
			title:				this.title,
			width:				680,
			height:				495,
			overlayOpacity:		0.8,
			href: 				this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			type:				'swf',
			swf: {
				wmode:				'transparent',
				allowfullscreen:	'true'
			}
		});
		return false;
	});
	
	/* ---------- RECIPE PAGE ---------- */
	$(".recipe #upload").fancybox({
		type:			'iframe',
		height:			400,
		width:			600,
		overlayOpacity:	0.8,
		'onCleanup':	function() {
			window.location.reload(true);
		}
	}).click(function(){
		$(this).fadeOut();
	});
	
	/* ---------- VIDEO CONTROLS ---------- */
	$("#skipbar").click(function(e){
		jumpTo((parseInt(e.pageX-parseInt($(this).offset().left))/parseInt($(this).width()))*100);
	});
	
	$("#ctrl-reload").click(function(){
		if(player) {
			player.stopVideo();
			player.cueVideoById(videoID,0);	
		}
	});
	$("#ctrl-back").click(function(){
		if(player) {
			player.seekTo(Math.round(player.getCurrentTime() - 10), true);	
		}
	});
	$("#ctrl-play").click(function(){
		if(player) {
			player.playVideo();
		}
	});
	$("#ctrl-pause").click(function(){
		if(player) {
			player.pauseVideo();
		}
	});
	$("#ctrl-forward").click(function(){
		if(player) {
			player.seekTo(Math.round(player.getCurrentTime() + 10), true);
		}
	});
	
	/* ---------- BLOG ----------- */
	$('.pressitem a img').parent().fancybox({
		overlayOpacity:		0.8,
		padding:			15
	});

	// Setup external links
	$('a[rel="external"]').click(function() {
		window.open($(this).attr('href'));
		return false;
	});

	/* ---------- Froobles APP OVERLAY (No doubt there's a better way .ps) ---------- */
	$("#app-popup").fancybox({
		href:				'/shop/frooble-app',
		type:				'iframe',
		width:				980,
		height:				640,
		overlayOpacity:		0.8,
		padding:			15
	});
	$("#overlay #go-app").click(function(){
		var url = 'http://itunes.apple.com/gb/app/froobles/id484923073?mt=8';
		//var url = getTradeURL();
		parent.location = url;
		parent.$("#fancybox-overlay").fadeOut();
		parent.$("#fancybox-wrap").fadeOut();
	});
	$("#overlay #close-overlay").click(function(){
		//var url = getTradeURL();
		//parent.location = url+'trade=false';
		parent.$("#fancybox-overlay").fadeOut();
		parent.$("#fancybox-wrap").fadeOut();
	});



});
// End jQuery

function isTab(name) {
	name = name.replace("#","");
	for(t in tabArray) {
		if(name == tabArray[t])
			return true
	}
	return false;
}

// Returns a string ready for the &trade parameter
function getTradeURL() {
	var url = parent.location.href;
	var reg = new RegExp('\\b(\\?|\\&)trade=(true|false)\\b');
	url = url.replace(reg,"");
	var pos = url.indexOf('?');
	return (url+(pos!=-1?'&':'?'));
}

// Callbacks
function updateCommentRatingsCallback() {
	var response = jsonParse(ajaxOb.xmlResponseText);
	if(response.error) {
		alert(response.error);
		return false;	
	}
	var cid = response.id;
	var val = response.rating;
	var cls = (val>0?'positive':(val<0?'negative':''));
	$("#comment-"+cid+" div strong").removeClass("positive").removeClass("negative").addClass(cls).text(val);
	$("#comment-"+cid+" div").children("a").remove();
}

/* YouTube API Player */
function onYouTubePlayerReady(id) {
	player = document.getElementById(playerID);			
	if(player) {
		setInterval(updateProgressBars, 200);
		player.cueVideoById(videoID);
	}
}

function updateProgressBars() {
	if(player) {
		if (player.getPlayerState() == 1 || player.getPlayerState() == 2) {
			var bytesloaded = (player.getVideoBytesLoaded() / player.getVideoBytesTotal())*100;
			var width = (player.getCurrentTime() / player.getDuration())*100;
			$("#loaded").width(bytesloaded+"%");
			$("#played").width(width+"%");
		} else if(player.getPlayerState()==5) {
			$("#loaded").width(0);
			$("#played").width(0);
		}
	}
}

function jumpTo(pct) {
	if(player) {
		if(player.getPlayerState()!="-1") {
			var sec = player.getDuration()*(pct/100);
			player.seekTo(sec,true);
		}
	}
}


// General Functions
(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        	'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position','relative').css('overflow','hidden').css('height',settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}


// JSON Parse
var jsonParse = (function () {
  var number
      = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
  var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
      + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';


  var string = '(?:\"' + oneChar + '*\")';

  // Will match a value in a well-formed JSON file.
  // If the input is not well-formed, may match strangely, but not in an unsafe
  // way.
  // Since this only matches value tokens, it does not match whitespace, colons,
  // or commas.
  var jsonToken = new RegExp(
      '(?:false|true|null|[\\{\\}\\[\\]]'
      + '|' + number
      + '|' + string
      + ')', 'g');

  // Matches escape sequences in a string literal
  var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');

  // Decodes escape sequences in object literals
  var escapes = {
    '"': '"',
    '/': '/',
    '\\': '\\',
    'b': '\b',
    'f': '\f',
    'n': '\n',
    'r': '\r',
    't': '\t'
  };
  function unescapeOne(_, ch, hex) {
    return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
  }

  // A non-falsy value that coerces to the empty string when used as a key.
  var EMPTY_STRING = new String('');
  var SLASH = '\\';

  // Constructor to use based on an open token.
  var firstTokenCtors = { '{': Object, '[': Array };

  var hop = Object.hasOwnProperty;

  return function (json, opt_reviver) {
    // Split into tokens
    var toks = json.match(jsonToken);
    // Construct the object to return
    var result;
    var tok = toks[0];
    if ('{' === tok) {
      result = {};
    } else if ('[' === tok) {
      result = [];
    } else {
      throw new Error(tok);
    }

    // If undefined, the key in an object key/value record to use for the next
    // value parsed.
    var key;
    // Loop over remaining tokens maintaining a stack of uncompleted objects and
    // arrays.
    var stack = [result];
    for (var i = 1, n = toks.length; i < n; ++i) {
      tok = toks[i];

      var cont;
      switch (tok.charCodeAt(0)) {
        default:  // sign or digit
          cont = stack[0];
          cont[key || cont.length] = +(tok);
          key = void 0;
          break;
        case 0x22:  // '"'
          tok = tok.substring(1, tok.length - 1);
          if (tok.indexOf(SLASH) !== -1) {
            tok = tok.replace(escapeSequence, unescapeOne);
          }
          cont = stack[0];
          if (!key) {
            if (cont instanceof Array) {
              key = cont.length;
            } else {
              key = tok || EMPTY_STRING;  // Use as key for next value seen.
              break;
            }
          }
          cont[key] = tok;
          key = void 0;
          break;
        case 0x5b:  // '['
          cont = stack[0];
          stack.unshift(cont[key || cont.length] = []);
          key = void 0;
          break;
        case 0x5d:  // ']'
          stack.shift();
          break;
        case 0x66:  // 'f'
          cont = stack[0];
          cont[key || cont.length] = false;
          key = void 0;
          break;
        case 0x6e:  // 'n'
          cont = stack[0];
          cont[key || cont.length] = null;
          key = void 0;
          break;
        case 0x74:  // 't'
          cont = stack[0];
          cont[key || cont.length] = true;
          key = void 0;
          break;
        case 0x7b:  // '{'
          cont = stack[0];
          stack.unshift(cont[key || cont.length] = {});
          key = void 0;
          break;
        case 0x7d:  // '}'
          stack.shift();
          break;
      }
    }
    // Fail if we've got an uncompleted object.
    if (stack.length) { throw new Error(); }

    if (opt_reviver) {
      // Based on walk as implemented in http://www.json.org/json2.js
      var walk = function (holder, key) {
        var value = holder[key];
        if (value && typeof value === 'object') {
          var toDelete = null;
          for (var k in value) {
            if (hop.call(value, k) && value !== holder) {
              // Recurse to properties first.  This has the effect of causing
              // the reviver to be called on the object graph depth-first.

              // Since 'this' is bound to the holder of the property, the
              // reviver can access sibling properties of k including ones
              // that have not yet been revived.

              // The value returned by the reviver is used in place of the
              // current value of property k.
              // If it returns undefined then the property is deleted.
              var v = walk(value, k);
              if (v !== void 0) {
                value[k] = v;
              } else {
                // Deleting properties inside the loop has vaguely defined
                // semantics in ES3 and ES3.1.
                if (!toDelete) { toDelete = []; }
                toDelete.push(k);
              }
            }
          }
          if (toDelete) {
            for (var i = toDelete.length; --i >= 0;) {
              delete value[toDelete[i]];
            }
          }
        }
        return opt_reviver.call(holder, key, value);
      };
      result = walk({ '': result }, '');
    }

    return result;
  };
})();


/* ---------- HOVER INTENT ---------- */
(function($){$.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);
