// LOAD YOUTUBE API;
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// JQUERY EASE
jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeInOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInExpo:function(e,f,a,h,g){return(f===0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f===0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInRegular:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutRegular:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutRegular:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a}});

var buttonNo = 0;
var button = 1;
var	buttonID = 1;
var currentMargin = 0;

function flags(){
	$('#flaglist').css("display", "none");
    $('#flags').hoverIntent(over, out);
    $('#flagssurround').hoverIntent(over2, out2);
    
	function over(event) {
    	$("#flaglist").show("slow");
    }
	function out(event) {
	}
	function over2(event) {
	}
	function out2(event) {
		$('#flaglist').hide("slow");
	}
}
	
function leftMove () {
	var slideSpeed = 700;
	var slideDist = 1140;
	
	$('#thumbHolder').stop();
	button--;	
	currentMargin -= slideDist;
	$('#thumbHolder').css('marginLeft', currentMargin + 'px') 
	$('#thumbHolder > a:last').prependTo('#thumbHolder');
	currentMargin += slideDist;
	
	$('#thumbHolder').animate({ 
		marginLeft: currentMargin + 'px'
	}, slideSpeed);
	
	buttonNo--;
	
	if(button < 1) {
		button = 6;	
	}
	
	$('#bannerBtns div').removeClass('on');
	$('#bannerBtns div#' + button).addClass('on');
}

function rightMove () {
	var slideSpeed = 700;
	var slideDist = 1140;
	
	$('#thumbHolder').stop();
	button++;	
	currentMargin += slideDist;
	$('#thumbHolder').css('marginLeft', currentMargin + 'px') 
	$('#thumbHolder > a:first').appendTo('#thumbHolder');
	currentMargin -= slideDist;
	
	$('#thumbHolder').animate({ 
		marginLeft: currentMargin + 'px'
	}, slideSpeed);
	
	buttonNo++;
	
	if(button > 6) {
		button = 1;	
	}
	
	$('#bannerBtns div').removeClass('on');
	$('#bannerBtns div#' + button).addClass('on');
}



function bannerButtons() {
	imageNo = $('#slideGallery img').size();				
	$('#slideGallery').prepend('<div id="bannerControls"><div id="leftArrow"></div><div id="rightArrow"></div><div id="bannerBtns"></div></div>');
	for(i=0; i<imageNo; i++){
		$('#bannerBtns').append('<div id="' + buttonID + '">' + '</div>');
		buttonID++;
	}
	$('#bannerBtns div:first').addClass('on');
	$('#bannerBtns div').click(function(){
		$('#bannerBtns div').removeClass('on');
		$(this).addClass('on');
		$this = $(this)
		if(button > $(this).attr('id'))	{
			button = parseInt(button);
			slide = parseInt($(this).attr('id'));
			slideMove = button - slide;
			for(i=0; i<slideMove; i++){
				leftMove();			
			}
		}
		else if(button < $(this).attr('id')) {
			button = parseInt(button);
			slide = parseInt($(this).attr('id'));
			slideMove = slide - button;
			
			for(i=0; i<slideMove; i++){
				rightMove();			
			}
		}
	});
	$('#leftArrow').click(function(){
		leftMove();
	});
	$('#rightArrow').click(function(){
		rightMove();
	});
}

function homeCalls() {
	$('#slideGallerySmall li').each(function(){
		if($(this).find('img').size() <= 0){
			$(this).remove();
		}
	})
}


function resizeHome(){
	var windowWidth = $(window).width();
	if(windowWidth < 946){
		windowWidth = 946;
	}
	$('#galleryHolder').css('marginLeft', -(2280 - ((windowWidth - 1140) / 2)) + 'px');
}

function SliderOne(){
	if($('#thumbHolder a').size() > 1){
		$('#galleryHolder').addClass('scroll');
		$('#thumbHolder').css('width', '10000px').css('height', '486px');
		$(window).bind('resize', function(){
			resizeHome();
		});
		resizeHome();
		bannerButtons(); 
	}
}


function navInit(){
	$("#topNav ul ul").each(function(){
		var prod = $(this).parent().find('a:first').text().toLowerCase().replace(/ /g, '');
		$(this).find('li:first').addClass('first');
		$(this).find('li:last').addClass('last');
		$(this).prepend("<li class='prodthumb'><img src='/static/images/" + prod + ".jpg' alt='" + prod + "' id='" + prod + "' /></li>");
	})
	
	$('#topNav > ul > li').mouseenter(function(){
		$(this).find('a.off span:first').addClass('on');
		$(this).find('a.off:first').addClass('subOn');
		$(this).find('ul li a.off:first').removeClass('subOn');
		$(this).find('a.off:first').removeClass('off');
		$(this).find('ul li a.drop2:first').addClass('off');
		if($(this).find('ul:first li').size() > 0){
			$(this).find('ul:first').show();
		}
	});
	
	$('#topNav > ul > li').mouseleave(function(){
		$(this).find('ul:first').hide();
		$(this).find('a.subOn:first').addClass('off');		
		$(this).find('a.subOn:first').removeClass('subOn');		
		$(this).find('a.off:first').removeClass('on');
		$(this).find('a.off span:first').removeClass('on');
		$(this).find('a.off span:first').addClass('off');
	});
}

function querySt(value, string){
	valueArray = string.split('?').join('&').split('&');
	for(i=0; i<valueArray.length; i++) {
		result = valueArray[i].split('=');
		if(result[0] == value) {
			return result[1];
		}
	}
}

function loadImage(o, s, d){
	var img = "img" + s.slice(s.lastIndexOf("index.html") + 1, s.lastIndexOf("."));
	eval[img] = new Image();
	eval[img].onload = function(evt){
		if(d == true){
			$(o).empty();
		}
		$(o).append(eval[img]);
		$(o + ' img').fadeTo(0,0,function(){
			$(o).removeClass('loading');
			$(this).fadeTo(500, 1);

		});
	};
	eval[img].src = s;
}

var player;
function productImages(){
	$('#prodscroll a').click(function(){
		zoomed = false;
		var largeImage = querySt('l', '?' + $(this).attr('rel'));
		var zoomImage = querySt('z', '?' + $(this).attr('rel'));
		var imgURL = $(this).attr('href');
		if(imgURL.indexOf('http://www.youtube.com/') > -1){
			window.zoomImage = undefined;
			$('.enlarge').attr('href', imgURL);
			imgURL = imgURL.replace('http://www.youtube.com/embed/', '');
			$('#productimage').empty();
			player = new YT.Player('productimage', {
				height: '100%',
				width: '100%',
				videoId: imgURL,
				events: {}
			});
		}
		else{
			loadImage('#productimage', imgURL, true)
			$('.enlarge').attr('href', largeImage);
			window.zoomImage = zoomImage;
		}
		return false;
	});
}

function checkVariants(){
	v = document.getElementsByName('vid')[0].value;
	id = variants[v];
	images = id.images;
	$('#amount .price').text(id.sellprice);
	$('.wishlist').attr('href', $('.wishlist').attr('href').replace(/\/add\/(.*?)\/?$/, '/add/' + v + '/'));
	if(id.instock == false){
		$('#addtobasket').hide();
	}
	else{
		$('#addtobasket').show();
	}
	if(images.detail.url != ''){
		$('#productimage').html('<img src="' + images.detail.url + '" />');
	}
	if(images.zoom.url != '' && $('#productControls .enlarge').size() > 0){
		$('#productControls .enlarge').attr('href', images.zoom.url);
	}
	else if(images.zoom.url != ''){
		$('#productControls').append('<a target="_blank" rel="width=920&zoom=true" class="arrow enlarge" href="' + images.zoom.url + '">Click to enlarge</a>');
	}
}

function selections(){
	$('#variants').bind('change', function(){
		checkVariants();
	});
	if((typeof variants != 'undefined') && variants.length > 0){
		checkVariants();
	}
}


function tabs(){
	$('.tabContent > div').not(':first').hide();
	$('.tabs li:first').addClass('tabOn');
	$('.tabs a').click(function(){
		$(this).parent().parent().find('li').removeClass('tabOn');
		$(this).parent().addClass('tabOn');
		$('.tabContent > div:visible').hide();
		$($(this).attr('href')).show();
		return false;
	});
}

var timer = "";

function categories(){
	$('.slider > li').mouseover(function(){
		window.clearInterval(timer);
		$(this).addClass('selected').parent().find('> li').not($(this)).removeClass('selected').stop().fadeTo(200,0.5).find('.infoBox').fadeOut(200);
		$(this).stop().fadeTo(200,1,function(){
			var $this = $(this);
			timer = window.setInterval(function(){  
				$this.find('.infoBox').fadeIn(400);
			},500);
		});
	});
	$('.slider').mouseout(function(){
		window.clearInterval(timer);
		$(this).find('> li').removeClass('selected').stop().fadeTo(200,1,function(){
			$(this).find('.infoBox').fadeOut(300);
		});
	});
}

function people(){
	$('.table-person').not(':first').hide();
	$('.people li').click(function(){
		$('.table-person').hide();
		$('.table-person:eq(' + $(this).parent().find('li').index($(this)) + ')').show();
	});
}

function disableSelect(selectors){
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){
				$(this).bind('selectstart',function(){return false;});
			}
			else{
				$(this).mousedown(function(){return false;});
			}
		});
	});
	$(selectors).disableTextSelect();
}

function btnHover(){
	$('#loginSubmitButton').hover(function(){
		$(this).attr('src', 'static/images/btn_login_over.jpg');
	},
	function(){
		$(this).attr('src', 'static/images/btn_login_up.jpg');
	});
	
	$('#submitButton').hover(function(){
		$(this).attr('src', 'static/images/btn_submit_over.jpg');
	},
	function(){
		$(this).attr('src', 'static/images/btn_submit_up.jpg');
	});
	
	$('#registerButton').hover(function(){
		$(this).attr('src', 'static/images/btn_register_over.jpg');
	},
	function(){
		$(this).attr('src', 'static/images/btn_register_up.jpg');
	});
	
	$('#updateButton').hover(function(){
		$(this).attr('src', 'static/images/btn_update_over.jpg');
	},
	function(){
		$(this).attr('src', 'static/images/btn_update_up.jpg');
	});
}

function createBreak() {
	$('.prodback .displaytext').each(function(){
		text = $(this).text().replace('(', '<br />(');
		$(this).html(text);
	})
}

function summarySelect(){
	$('.prodSummary').each(function(){
		if($(this).find('> *').size() > 0){
			$(this).show();
			$(this).parent().find('.fullProdFeatures').hide();
		}
	})
}

function removeEmpty(s){
	$(s).each(function(){
		if($(this).find('> *').size() == 0){
			$(this).remove();
		}
	})
}


/***** SLIDER *****/

var slideInt = ""

function roundNearest(num, acc){
	if(acc < 0){
		return Math.round(num*acc)/acc;
	}else{
		return Math.round(num/acc)*acc;
	}
}

$('.sliderContainer .trackBtn').live('mousedown', function(e){
	$this = $(this);
	$cont = $this.closest('.sliderContainer');
	$slider = $cont.find('.slider');
	$track = $cont.find('.track');
	$li = $cont.find('li:first');
	
	var o = e.pageX - $this.offset().left
	$(document).mousemove(function(e){
		var x = (e.pageX - $track.offset().left) - o;
		$this.css('left', x);
		$cont.find('.lb, .rb').fadeTo(0, 1);
		if($this.offset().left < $track.offset().left){
			$this.css('left', 0);
			x = 0;
			$cont.find('.lb').fadeTo(0, 0.5);
		}
		if(($this.offset().left + $this.width()) > ($track.offset().left + $track.width())){
			$this.css('left', ($track.width() - $this.width()));
			x = ($track.width() - $this.width());
			$cont.find('.rb').fadeTo(0, 0.5);
		}
		var w = $li.outerWidth(true) - $li.outerWidth()
		var t = $track.width() - $this.width();
		var p = (x * (($slider.width() - w) - $cont.width())) / t;
		$('.slider').css('margin-left', -p)
		return false;
	});
	return false;
});

$('.sliderContainer .rb').live('mousedown', function(e){
	$this = $(this);
	$cont = $this.closest('.sliderContainer');
	$slider = $cont.find('.slider');
	$track = $cont.find('.track');
	$btns = $cont.find('.slideControls');
	$btn = $cont.find('.trackBtn');
	$li = $cont.find('li:first');
	
	
	var x = $btn.offset().left - $track.offset().left;
	var w = $li.outerWidth(true);
	var c = w - $li.outerWidth();
	var p = roundNearest(-(x * (($slider.width()) - $cont.width())) / ($track.width() - $btn.width()), w);
	if(-p < (($slider.width() - c) - $cont.width())){
		p -= w;
		var s = -Math.round(((p) * ($track.width() - $btn.width())) / (($slider.width() - c) - $cont.width()))
		$slider.stop().animate({
			marginLeft: p
		}, 700, "easeInOutQuint");
		$btn.stop().animate({
			left: s
		}, 700, "easeInOutQuint");
	}
	if(-p >= (($slider.width() - c) - $cont.width())){
		$slider.stop().animate({
			marginLeft: -(($slider.width() - c) - $cont.width())
		}, 700, "easeInOutQuint");
		$btn.stop().animate({
			left: ($track.width() - $btn.width())
		}, 700, "easeInOutQuint");
		$this.addClass('disabled').fadeTo(0, 0.3);
	}
	$cont.find('.lb').removeClass('disabled').fadeTo(0, 1);
	
	slideInt = window.setTimeout(function(){
		slideInt = window.setInterval(function(){
			x = $btn.offset().left - $track.offset().left;
			p = roundNearest(-(x * (($slider.width()) - $cont.width())) / ($track.width() - $btn.width()), w);
			if(-p < (($slider.width() - c) - $cont.width())){
				p -= (w * 2);
				s = -Math.round(((p) * ($track.width() - $btn.width())) / (($slider.width() - c) - $cont.width()))
				$slider.stop().animate({
					marginLeft: p
				}, 500, "easeOutQuint");
				$btn.stop().animate({
					left: s
				}, 500, "easeOutQuint");
			}
			if(-p >= (($slider.width() - c) - $cont.width())){
				window.clearInterval(slideInt);
				$slider.stop().animate({
					marginLeft: -(($slider.width() - c) - $cont.width())
				}, 500, "easeOutQuint");
				$btn.stop().animate({
					left: ($track.width() - $btn.width())
				}, 500, "easeOutQuint");
				$this.addClass('disabled').fadeTo(0, 0.3);
			}
		},100);
	},250);
	
	return false;
});

$('.sliderContainer .lb').live('mousedown', function(e){
	$this = $(this);
	$cont = $this.closest('.sliderContainer');
	$slider = $cont.find('.slider');
	$track = $cont.find('.track');
	$btn = $cont.find('.trackBtn');
	$li = $cont.find('li:first');
	var x = $btn.offset().left - $track.offset().left;
	var w = $li.outerWidth(true);
	var c = w - $li.outerWidth();
	var p = roundNearest(-(x * (($slider.width()) - $cont.width())) / ($track.width() - $btn.width()), w);
	if(-p > 0){
		p += w;
		var s = -Math.round(((p) * ($track.width() - $btn.width())) / (($slider.width() - c) - $cont.width()))
		$slider.stop().animate({
			marginLeft: p
		}, 700, "easeInOutQuint");
		$btn.stop().animate({
			left: s
		}, 700, "easeInOutQuint");
	}
	if(-p <= 0){
		$slider.stop().animate({
			marginLeft: 0
		}, 700, "easeInOutQuint");
		$btn.stop().animate({
			left: 0
		}, 700, "easeInOutQuint");
		$this.addClass('disabled').fadeTo(0, 0.3);
	}
	$cont.find('.rb').removeClass('disabled').fadeTo(0, 1);
	
	slideInt = window.setTimeout(function(){
		slideInt = window.setInterval(function(){
			x = $btn.offset().left - $track.offset().left;
			p = roundNearest(-(x * (($slider.width()) - $cont.width())) / ($track.width() - $btn.width()), w);
			if(-p > 0){
				p += (w * 2);
				s = -Math.round(((p) * ($track.width() - $btn.width())) / (($slider.width() - c) - $cont.width()))
				$slider.stop().animate({
					marginLeft: p
				}, 500, "easeOutQuint");
				$btn.stop().animate({
					left: s
				}, 500, "easeOutQuint");
			}
			if(-p <= 0){
				window.clearInterval(slideInt);
				$slider.stop().animate({
					marginLeft: 0
				}, 500, "easeOutQuint");
				$btn.stop().animate({
					left: 0
				}, 500, "easeOutQuint");
				$this.addClass('disabled').fadeTo(0, 0.3);
			}
		},100);
	},250);
	
	return false;
});

function checkWidths(){
	//$('.slider').not('.nobar').each(function(e){
	$('.slider').each(function(e){
		$this = $(this);
		width = ($this.find('li:first').outerWidth(true) * $this.find('> li').size()) - ($this.find('li:first').outerWidth(true) - $this.find('li:first').outerWidth());
		if(width > $this.parent().width()){
			$this.closest('.sliderContainer').find('.slideControls, .lb, .rb').show();
		}
		else{
			$this.closest('.sliderContainer').find('.slideControls, .lb, .rb').hide();
		}
	});
}

function resetScroll(){
	$('.sliderContainer .slider').css('margin-left', 0);
	$('.sliderContainer .trackBtn').css('left', 0);
	$('.sliderContainer .lb').addClass('disabled').fadeTo(0, 0.3);
	$('.sliderContainer .rb').removeClass('disabled').fadeTo(0, 1);
}

function resizeProducts(){
	var windowWidth = $(window).width();
	if(windowWidth < 946){
		windowWidth = 946;
	}
	$('.productArea').width(windowWidth);
}

function initSlider(selector){
	$(selector + ' .slider').not('.nobar').each(function(e){
		$this = $(this);
		width = $this.find('li:first').outerWidth(true) * $this.find('> li').size();
		if(width > $this.parent().width()){
			//$this.parent().removeClass('noScroll');
			$this.width(width);
		}
		else{
			$('.viewtext, .viewimage').hide();
		}
		$this.wrap('<div class="sliderContainer"></div>');
		$('<div class="slideControls"><div class="lb"></div><div class="track"><div class="trackBtn"></div></div><div class="rb"></div></div>').insertAfter($this);
	});
	$(selector + ' .slider.nobar').each(function(e){
		$this = $(this);
		width = $this.find('li:first').outerWidth(true) * $this.find('> li').size();
		if(width > $this.parent().width()){
			$this.wrap('<div class="sliderContainer prodScroll"></div>');
			width = $this.find('li:first').outerWidth(true) * $this.find('> li').size();
			$this.width(width);
			$('<div class="lb"></div>').insertBefore($this);
			$('<div class="rb"></div><div class="slideControls"><div class="track"><div class="trackBtn"></div></div></div>').insertAfter($this);
			$this.wrap('<div class="prodItems"></div>');
		}
	});
	$('.lb').addClass('disabled').fadeTo(0, 0.3);
	checkWidths();
	$(document).bind('mouseup', function(e){
		$(document).unbind('mousemove');
		window.clearInterval(slideInt);
	});
	if($('.productArea').size() > 0){
		$(window).bind('resize', function(){
			checkWidths();
			resetScroll();
			//resizeProducts();
		});
	}
	$(window).bind('unload', function(){
		resetScroll();
	});
}

$('.viewimage').live('click', function(e){
	if($('.noScroll').size() > 0){
		$('.productArea').removeClass('noScroll');
		$(this).removeClass('nogrid');
		$('.viewtype').html('Grid View:&nbsp;&nbsp;');
		checkWidths();
	}
	else{
		$('.productArea').addClass('noScroll');
		$(this).addClass('nogrid');
		$('.viewtype').html('List View:&nbsp;&nbsp;');
	}
	return false;
});

$('.viewimage').live('mousemove', function(e){
	return false;
});

function twitter(){
	$('#twitter_update_list').html('<li>Loading Twitter feed</li>');
	if($('#twitter_update_list').size() > 0){
		$.getScript("http://twitter.com/javascripts/blogger.js", function(){
			$.getScript("http://twitter.com/statuses/user_timeline/gear4.json?callback=twitterCallback2&amp;count=2");
		});
	}
}


/***** FEEDBACK *****/


function initFeedback(){
	function checkFeedback(){
		$('.feedbackError').html('&nbsp;');
		var feedbackName = $('#mod_signup_feedbackname').val();
		var feedbackEmail = $('#mod_signup_feedbackemail').val();
		var feedbackMessage = $('#mod_signup_feedbackmessage').val();
		var errors = false;
		if(feedbackEmail.length > 0){
			if(feedbackEmail.indexOf('@') <= -1 || feedbackEmail.indexOf('.') <= -1){
				$('#mod_signup_feedvackemail').next('.feedbackError').html('Your email is invalid');
				errors = true;
			}
		}
		if(feedbackMessage.length <= 0){
			$('#mod_signup_feedbackmessage').next('.feedbackError').html('Please enter a message');
			errors = true;
		}
		if(errors === true){
			return false;
		}
		else{
			if(feedbackEmail.length <= 0){
				feedbackEmail = "noemail@feedbackforum.com";
			}
			$.post('feedback-form.html', { mod_signup_feedbackname: feedbackName, mod_signup_email: feedbackEmail, mod_signup_feedbackmessage: feedbackMessage, mod_signup_confirm: 'Yes' },
			function(data){
				$('#lightBoxInner').fadeTo(500, 0, function(){
					$data = data;
					if($($data).find('#feedbackError"').size() > 0){
						$('#lightBoxInner').html('<p>The following errors occured while processing your feedback.</p>' + $($data).find('#feedbackError').html() + '<p>Please try again later.</p>');
					}
					else{
						$('#lightBoxInner').html($($data).find('#feedBackResponse').html());
					}
					$('#lightBoxInner').fadeTo(500, 100);
				});
			});
		}
	}
	$('#feedbackLink a').live('click', function(){
		if(typeof(pageTracker) != 'undefined'){
			pageTracker._trackPageview('feedback-form.html');
		}
	});
	$('#feedbackSubmit').live('click', function(){
		checkFeedback();
		return false;
	});
}

function colourPick(){
                $('.showimage #Map3 area').click(function(){
                                var newImageSrc = $(this).attr('href');
                                $('.showimageover img').fadeOut(500,function(){
                                                var img = "img" + newImageSrc.slice(newImageSrc.lastIndexOf("index.html") + 1, newImageSrc.lastIndexOf("."));
                                                eval[img] = new Image();
                                                eval[img].onload = function(evt){
                                                                $('.showimageover').html(eval[img]);
                                                                $('.showimageover img').fadeTo(0,0,function(){
                                                                                $(this).fadeTo(500, 1);
                                                                });
                                                };
                                                eval[img].src = newImageSrc;
                                })
								return false;
                })
}


/***** BASKET *****/

var totalItems = 0;
var totalAmount = 0;
var basketInt = "";
var errorInt = "";

function addBasket(itemName, itemCost, itemImg){
	var errorMsg = '';
	var variant = document.getElementsByName('vid')[0].value;
	clearTimeout(basketInt);
	$.post("content/2/ecom-basket/index.html", { action: "add", vid: variant },
	function(data){
		$('#ajaxBasket').slideDown(function(){
			basketInt = setTimeout(function(){
				$('#ajaxBasket:visible').slideUp();
			},2000);
			if(data.status == 'noaction'){
				errorMsg = 'This item is already in your basket.';
				
			}
			else if(data.status == 'outofstock'){
				errorMsg = 'Sorry this item is currently out of stock but you can still add it to your wishlist.';
			}
			else if(data.status == 'fail'){
				errorMsg = 'Sorry there was an error, please try again.';
			}
			if(data.status == 'ok'){
				totalItems += 1;
				totalAmount = totalAmount + parseFloat(itemCost.toString().replace(/[^0-9]/g, ''))
				$('#basketRows').prepend('<div class="basketRow" style="display:none;"><table id="' + variant + '"><tr><td class="basketImg">' + itemImg + '</td><td class="basketName">' + itemName + '</td><td class="basketPrice">' + itemCost + '</td><td class="basketRemove"><img src="/static/images/basket_remove.gif" /></td></tr></table></div>');
				$('#basketitems .items').text(totalItems);
				$('#basketitems .price span').text((totalAmount/100).toFixed(2));
				$('#basketRows .basketRow:first').slideDown(function(){
					
				})
			}
			else{
				clearTimeout(errorInt);
				if($('#basketRows .basketInfo').size() > 0){
					$('#basketRows .basketInfo').text(errorMsg);
				}
				else{
					$('#basketRows').prepend('<div class="basketRow basketInfo" style="display:none;">' + errorMsg + '</div>');
					$('#basketRows .basketInfo').slideDown();
				}
				errorInt = setTimeout(function(){
					$('#basketRows .basketInfo').slideUp(function(){
						$(this).remove();
					});
				},2000);
			}
		});
	}, "json");
}

function initBasket(){
	totalItems = $('#basketRows .basketRow').size();
	totalAmount = parseFloat($('#basketitems .price span').text().replace(/[^0-9]/g, ''));
	$('#basketitems').hover(function(){
		clearTimeout(basketInt);
		$('#ajaxBasket:hidden').slideDown();
	},function(){
		$('#ajaxBasket:visible').slideUp();
	})
	$('#basketRows .basketRemove img').live('click', function(){
		var variant = $(this).closest('.basketRow').find('> table').attr('id').replace(/vid/, '');
		$.post("content/2/ecom-basket/index.html", { action: "remove", vid: variant },
		function(data){
		}, "json");
		var itemCost = $(this).closest('.basketRow').find('.basketPrice').text();
		totalItems -= 1;
		totalAmount = totalAmount - parseFloat(itemCost.toString().replace(/[^0-9]/g, ''))
		$(this).closest('.basketRow').slideUp(function(){
			$(this).remove();
			$('#basketitems .items').text(totalItems);
			$('#basketitems .price span').text((totalAmount/100).toFixed(2));
		});
		return false;
	})
	$('#addtobasket').click(function(){
		var itemName = $('#productname h1').text();
		var itemCost = $('#price .price').text();
		var itemImg = $('<div>').append($('#prodscroll img:first').clone()).remove().html();
		addBasket(itemName, itemCost, itemImg);
		return false;
	})
}

/***** DESIGNERS *****/

function designers(){
	$('#designerBox').hide();
	$('.designer').click(function(){
		$('#designerBox').slideToggle(500);
		return false;
	})
}

var $$ = $.fn;

$$.extend({
  SplitID : function()
  {
    return this.attr('id').split('-').pop();
  },

  Slideshow : {
    Ready : function()
    {
      $('div.tmpSlideshowControl')
        .hover(
          function() {
            $(this).addClass('tmpSlideshowControlOn');
          },
          function() {
            $(this).removeClass('tmpSlideshowControlOn');
          }
        )
        .click(
          function() {
            $$.Slideshow.Interrupted = true;

            $('div.tmpSlide').hide();
            $('div.tmpSlideshowControl').removeClass('tmpSlideshowControlActive');

            $('div#tmpSlide-' + $(this).SplitID()).show()
            $(this).addClass('tmpSlideshowControlActive');
          }
        );

      this.Counter = 1;
      this.Interrupted = false;

      this.Transition();
    },

    Transition : function()
    {
      if (this.Interrupted) {
        return;
      }

      this.Last = this.Counter - 1;

      if (this.Last < 1) {
        this.Last = 5;
      }

      $('div#tmpSlide-' + this.Last).fadeOut(
        'slow',
        function() {
          $('div#tmpSlideshowControl-' + $$.Slideshow.Last).removeClass('tmpSlideshowControlActive');
          $('div#tmpSlideshowControl-' + $$.Slideshow.Counter).addClass('tmpSlideshowControlActive');
          $('div#tmpSlide-' + $$.Slideshow.Counter).fadeIn('slow');

          $$.Slideshow.Counter++;

          if ($$.Slideshow.Counter > 5) {
            $$.Slideshow.Counter = 1;
          }

          setTimeout('$$.Slideshow.Transition();', 5000);
        }
      );
    }
  }
});

function support(){
	var height = 0;
	var items = 10;
	$('#supportLeft .faqList:visible li:lt(' + items + ')').each(function(e){
		height += $(this).outerHeight(true);
	})
	$('#supportLeft .faqList:visible').height(height-1);
	
	
	//  FAQ search code
	var $ajaxFaqList 	= $('#ajaxFaqList');
	var $defaultFaqList = $('#defaultFaqList');
	var $searchMessage	= $('#searchMessage');
	var $faqBox			= $('#faqBox');
	
	var $searchField 	= $('#faqSearchField');		//  Textbox containing the search string
	var minSearchLength	= 3;						//  Shortest search string length
	var requestTimer 	= false;					//  Variable to hold the timer
	var searchDelay		= 1250;						//  Delay between keyup and doing the search
	
	var showAjaxResults = function () {				//  Function to switch the list to the Ajax results
		$defaultFaqList.hide();
		$ajaxFaqList.show();
	}
	
	var showDefaultList = function () {				//  Function to switch the list to the one generated at page load
		$ajaxFaqList.hide();
		$defaultFaqList.show();
	}
	
	var hideFaqLists = function () {				//  Function hide both generated and Ajax-powered searches
		$ajaxFaqList.hide();
		$defaultFaqList.hide();
	}
	
	var showSearchMessage = function ( msg ) {		//  Function to display a message for the search
		
		msg = msg || '';
		
		if ( msg != '' ) {
			$searchMessage.text( msg );
		}
		
		$searchMessage.show();
	}
	
	var hideSearchMessage = function () {		//  Function to hide the search message
		$searchMessage.hide();
	}
	
	var sendRequest = function () {					//  Function to collect and parse the FAQ data
		
		var searchString = $searchField.val();
				
		$ajaxFaqList.empty();
		hideSearchMessage();
		hideFaqLists();
		
		if ( searchString == '' ) {
			showDefaultList();
			return;	
		}
		
		if ( searchString.length < minSearchLength ) {
			showSearchMessage( 'Please enter a search term of at least ' + minSearchLength + ' characters' );
			return;
		} else {
			hideSearchMessage();
		}
		
		$searchField.css({
			'background': 'transparent url( "/static/images/faq_loader.gif" ) 98% 50% no-repeat'
		});
		
		$.ajax({
			'type': 'post',
			'url':	'http://www.gear4.com/content/' + locale + '/ecom-faq/search/',
			'data': 'type=' + type + '&id=' + id + '&search=' + searchString,
			'dataType': 'xml',
			'success': function ( data ) {
				
				var faqs = $( data ).find( 'faq' );
				
				if ( faqs.length == 0 ) {
					
					showSearchMessage( 'Sorry.  We don\'t have any FAQs related to "' + searchString + '".' );
					
				} else {
				
					faqs.each( function () {
						
						var ref 		= $( this ).find( 'ref' ).text();
						var question 	= $( this ).find( 'question' ).text();
						var by			= $( this ).find( 'by' ).text();
						
						$ajaxFaqList.append( '<li><a href="#faqBox" id="faq-' + ref + '" class="faqLightBox">' + question + '</a></li>' );
						
					});
				
					showAjaxResults();
				
				}
			},
			'complete': function () {
				$searchField.css({
					'background': 'transparent'
				});
			}
		});
		
		
	}
	
	$searchField.keyup( function ( ev ) {			//  Function to observe the search text field
		
		if ( requestTimer !== false ) {
			clearTimeout( requestTimer );
		}
		
		requestTimer = setTimeout( sendRequest, searchDelay );
		
	});
	
	
	$('#search2').click( function ( ev ) {			//  Do FAQ search when you click the submit button
		ev.preventDefault();
		sendRequest();
	});
	
	
	$('a.faqLightBox').live( 'click', function ( ev ) {
		
		ev.preventDefault();
		
		var $link 	= $( this );
		var ref 	= $link.attr( 'id' ).split( '-' )[1];
		
		$.ajax({
			'type': 'post',
			'url':	'http://www.gear4.com/content/' + locale + '/ecom-faq/answer/',
			'data': 'ref=' + ref,
			'dataType': 'xml',
			'success': function ( data ) {
				
				var $result = $( data ).find( 'result' );
				
				var question 	= $link.text();
				var answer 		= $result.find( 'answer' ).text();
				var answeredBy	= $link.parent().find( 'span.answeredBy' ).text();
				
				$faqBox.html(
					'<p class="question">' + question + '</p>'
					+ answer
				);
				
				openLightBox( '#' + $faqBox.attr( 'id' ) );
				
			}
		});
		
	});
	
	
	//  More items
	$('.moreItems').click(function(){
		
		var $list  = $ajaxFaqList.is( ':visible' ) ? $ajaxFaqList : $defaultFaqList;
		var listId = $list.attr( 'id' );
		
		if(items < $('#' + listId + ' li').size()){
			items += 3;
			var oldHeight = $list.height()-1;
			var height = -1;
			$('#' + listId + ' li:lt(' + items + ')').each(function(){
				height += $(this).outerHeight(true);
			})
			$list.animate({
				height:(height-1)
			}, 600,  "easeInOutRegular");
			$('body').animate({
				scrollTop: ($('body').scrollTop() + ((height) - oldHeight))
			}, 600);
			$('html').animate({
				scrollTop: ($('html').scrollTop() + ((height) - oldHeight))
			}, 600);
		}
		if(items >= $('#' + listId + ' li').size()){
			$(this).fadeTo(0,0.3).addClass('disabled');
		}
		return false;
	});
	
}

$(document).ready(function() {
    var pathname = window.location.pathname;
	var pathfull = ("<iframe src='http://www.facebook.com/plugins/like.php?href=http://www.gear4.com" + pathname + "&layout=standard&show_faces=true&width=450&action=like&colorscheme=light' scrolling='no' frameborder='0' allowTransparency='true' style='border:none; overflow:hidden; width:450px; height:60px'></iframe>");
	$("#produrl").replaceWith(pathfull);
});

$(document).ready(function(){

	(function($){
		$.fn.fblikecount = function(options){
			var defaults = {
				baseUrl: 'http://graph.facebook.com/?ids='
			};
			var options = $.extend(defaults, options);
			var count = 0;
			return this.each(function(){
				var $this = $(this);
				$this.hide();
				var objLink = $(this).attr('title');
				if(objLink.indexOf('http') === 0){
					$.getJSON(defaults.baseUrl + objLink + '&callback=?', function(json){
						if(json[objLink] && json[objLink].shares){
							$this.html(json[objLink].shares);
							$this.show();
						}
					});				
				}
			});
		}
	})(jQuery);

	$('span.likebox').fblikecount();


    $$.Slideshow.Ready();
	twitter();   
	initFeedback();
	navInit();
	colourPick();
	homeCalls();
	initSlider('body');
	flags();
	selections();
	categories();
	people();
	SliderOne();	
	//SliderTwo();
	//SliderThree();
	//thumbButtons();
	productImages();
	tabs();
	//numberJobs();
	createBreak();
	btnHover();
	summarySelect();
	initBasket();
	removeEmpty('#topNav ul');
	removeEmpty('.proditemquote blockquote');
	removeEmpty('.tabBox .tabContent');
	$('#imageText').text($('#thumbHolder a:first').attr('name'));
	$('#galleryImage img:first').attr('src', $('#thumbHolder a:first').attr('rel'));
	designers();
	support();
	
	//  Do tooltips if tooltip plugin is installed
	if ( $().qtip ) {
		$( '.tooltip-trigger' ).qtip({
			position: {
				my: 'bottom center',
				at: 'top center',
				adjust: {
					y: -4
				}
			},
			style: {
				classes: 'ui-tooltip-rounded',
				tip: {
					corner: false
				},
				widget: true
			}
		});
	}
	
});
