/**
 * Global Variables
 **/

var toolbar_boxes = 'div.module_locale_switcher div.box, div.module_login form, div.module_basket div#mini_basket';


$(function() {
	
	
	/**
	 * Document Setup
	 **/
	
	$('body').removeClass('js_disabled').addClass('js_enabled');
	
	$('div.module_search form input#term').inputHint($('div.module_search form label').hide().text())
										  .parents('form').children('button').hide();
	
	$('div.module_subscribe form').children('label').hide();
	
	$('div#content.wishlist form.email textarea').inputHint($('div#content.wishlist form.email label').text());
	
	$.ajaxSetup({'cache': false,
				 'type': 'POST',
				 'dataType': 'html'});
	
	$('a.print').click(function() {
		
		window.print();
		
		return false;
		
	});
	
	$('div#container div#content.home div#featured p.overlay img').click(function() {
		
		$(this).parent('p').fadeOut(500);
		
		return false;
		
	});
	
	
	/**
	 * Register page Privacy Policy
	 **/
	
	$('.privacy a[href=#policy]').click(function() {
		
		var policy = $('div#policy');
		
		policy.fadeIn({speed: 500, complete: function() { $('html,body').animate({scrollTop: policy.offset().top}, 500); }})
		
		return false;
		
	});
	
	$('#policy p.back-to-top a').text('Close privacy policy');
	
	$('#policy p.back-to-top a').click(function() {
		
		var self = $(this).parents('#policy');
		var target = $('#' + $(this).attr('href').replace('#', ''));
		
		$('html,body').animate({scrollTop: target.offset().top}, {speed: 500, complete: function() { self.fadeOut(500); }});
		
		return false;
		
	});
	
	
	/**
	 * Fade out language warning and geoip notice
	 **/
	
	if($('div.module_language_warning').length > 0) {
		
		var original = $('div.module_language_warning').css('background-color');
		
		$('div.module_language_warning').animate({opacity: 1}, 500) // Delay
										.animate({backgroundColor: "#f27490"}, 2000)
										.animate({backgroundColor: original}, 1000);
		
	}
	
	if($('div.module_geoip_notice').length > 0) {
		
		var original = $('div.module_geoip_notice').css('background-color');
		
		$('div.module_geoip_notice').animate({opacity: 1}, 500) // Delay
									.animate({backgroundColor: "#f27490"}, 2000)
									.animate({backgroundColor: original}, 1000);
		
	}
	
	
	/**
	 * Locale Switcher
	 **/
	
	$('div.module_locale_switcher').children('h2').after('<p class="' + $('div.module_locale_switcher ul li.current').attr('class').replace(' current', '') + '">' + $('div.module_locale_switcher ul li.current a').html() + '</p>')
								   .siblings('ul').wrap('<div class="box"></div>').before('<span class="arrow"></span>').wrap('<div class="drop-shadow"></div>').before($('<ul id="this_locale"></ul>').html($('div.module_locale_switcher div ul li.current').remove())).before('<p>' + $('div.module_locale_switcher h2').text() + ':</p>');
	
	$('div.module_locale_switcher>p').click(function(e) {
		
		e.stopPropagation();
		
		switchToolbarBox($(this).next('div'));
		
	});
	
	
	/**
	 * Login Box
	 **/
	
	if($('div.module_login form p.error').length > 0) {
		switchToolbarBox($('div.module_login form'));
	}
	
	$('div.module_login p.login a').click(function(e) {
		
		e.stopPropagation();
		
		switchToolbarBox($(this).parent('p').next('form'));
		
		return false;
		
	});
	
	
	/**
	 * Mini-Basket
	 **/
	
	// This uses live to be rebinded if first item is added to cart
	
	$('div.module_basket>p:not(#checkout_tab)>a').live('click', function(e) {
		
		e.stopPropagation();
		
		switchToolbarBox($(this).parent('p').siblings('div#mini_basket'));
		
		return false;
		
	});
	
	
	/**
	 * Click anywhere closes toolbar boxes
	 **/
	
	$('html,body').click(function() {
		
		switchToolbarBox();
		
	});
	
	
	/**
	 * IE Drop-Down Helper
	 **/
	
	if($.browser.msie) {
		
		var expand   = function(){ $(this).css({width: 'auto', zIndex: 999}); }
        var contract = function(){ if (!this.noHide) $(this).removeAttr('style'); }
        var focus    = function(){ this.noHide = true; }
        var blur     = function(){ this.noHide = false; contract.call(this); }
       
        $('div#information div .selector div.options select').hover(expand, contract)
															 .focus(focus)
															 .click(focus)
															 .blur(blur)
															 .change(blur);
		
	}
	
	
	/**
	 * Show inform me form on focus of select box or click of anchor link
	 **/
	
	var openInformMeBox = function() {
		
		var inform_me = $('div#information div.module_product_selector').children('form.inform-me');
		
		if(inform_me.length > 0) {
			
			inform_me.fadeIn(500);
			
		}
		
	}
	
	$('div#information div form.buy.selector div.options select').focus(openInformMeBox);
	
	$('a[href=#inform-me]').click(openInformMeBox);
	
	
	/**
	 * Show add to wishlist on click of title
	 **/
	
	$('div#fringe div.module_add_to_wishlist h2 span').after('<i> &raquo;</i>');
	
	$('div#fringe div.module_add_to_wishlist').click(function() {
		
		var element = $(this);
		
		element.unbind('click').addClass('open').children('form').fadeIn(200);
		
		element.children('h2').children('i').remove();
		
	});
	
	
	/**
	 * AJAX Add to Basket
	 **/
	
	$('form.buy').submit(function() {
		
		element = $(this);
		
		$.ajax({'url': '/ajax/addproduct',
				'data': element.find('input, select').serialize(),
				'beforeSend': function() {
					element.children('button').addClass('disabled').attr('disabled', 'disabled');
				},
				'complete': function() {
					element.children('button').removeClass('disabled').removeAttr('disabled');
				},
				'success': function(data) {
					
					element.next('div.drawer.selector').replaceWith($('div.module_product_selector', data).children('div.drawer.selector').hide());
					
					$('div.module_basket').replaceWith($('div.module_basket', data));
					
					element.next('div.drawer.selector').slideDown('slow');
					
					if($('div.module_basket>p:not(#checkout_tab)').attr('class') == 'one') {
						$('div.module_basket p#checkout_tab').hide().fadeIn('slow');
					}
					
					original = $('div.module_basket p#checkout_tab a span').css('background-color');
		
					$('div.module_basket p#checkout_tab').css('z-index', -10)
														 .children('a')
														 	.children('span')
																.css('border-color', '#f27490')
																.children('span')
																	.css({backgroundColor: '#f27490', borderColor: '#f27490'})
																	.animate({marginBottom: 0}, 2000) // Delay, doesn't use opacity as it trips up IE
																	.animate({backgroundColor: 		original, 
																			  borderTopColor: 		original, 
																			  borderRightColor: 	original, 
																			  borderBottomColor: 	original, 
																			  borderLeftColor: 		original}, 1000)
															.parent('span')
																.animate({marginBottom: 0}, 2000) // Delay, doesn't use opacity as it trips up IE
																.animate({borderBottomColor: 	original}, 1000);
				}});
		
		return false;
		
	});
	
	
	/**
	 * AJAX Inform Me
	 **/
	
	$('form.inform-me').submit(function() {
		
		element = $(this);
		
		$.ajax({'url': '/ajax/informme',
				'data': element.find('input, select').serialize() + '&product_selector=' + element.siblings('form.buy').find('input[name=product_selector]').val(),
				'beforeSend': function() {
					element.children('button').addClass('disabled').attr('disabled', 'disabled');
				},
				'complete': function() {
					element.children('button').removeClass('disabled').removeAttr('disabled');
				},
				'success': function(data) {
					
					element.next('div.drawer.inform-me').replaceWith($('div.module_product_selector', data).children('div.drawer.inform-me').hide());
					element.next('div.drawer.inform-me').slideDown('slow');
					
				}});
		
		return false;
		
	});
	 
	 
	
	/**
	 * Product Information - Tabbed Interface
	 **/
	
	if($('div.module_product_information').length > 0) {
		
		$('.open_sizing').click(function() {
			$('div.module_product_information ul.tab-menu li.sizing a').click()[0].scrollIntoView(true);
		});
		
		$('div.module_product_information ul.tabs>li>a.anchor').remove();
		
		if(location.hash) {
			
			var current = location.hash.replace('#', '');
			
			var valid = false;
			
			$('div.module_product_information>ul.tabs>li').each(function() {
				
				if($(this).attr('class') == current) {
					valid = true;
					return false;
				}
				
			});
			
			if(!valid) current = false;
			
		}
		
		if(!current) var current = 'availability';
		
		$('div.module_product_information>ul.tabs>li.' + current).addClass('current');
		
		var html = '';
		
		$('div.module_product_information>ul.tabs>li').each(function() {
			
			var tab = $(this).attr('class').replace(' current', '');
			
			html += '<li class="' + $(this).attr('class') + ($(this).attr('class') == current ? ' current' : '') + '"><a href="#' + tab + '"><span>' + $(this).children('h2').text() + '</span></a></li>';
			
		});
		
		$('div.module_product_information').prepend('<ul class="tab-menu">' + html + '</ul>');
		
		$('div.module_product_information>ul.tab-menu>li>a').click(function() {
			
			if($(this).parent('li').hasClass('current')) return false;
			
			var target = $(this).parent('li').attr('class');
			
			$('div.module_product_information>ul>li.current').removeClass('current');
			
			$('div.module_product_information>ul>li.' + target).addClass('current');
			
		});
		
		
		// Sizing Tables
		
		var current = $('div.module_product_information>ul.tabs>li.sizing ul.tables>li:first').addClass('current').attr('class');
		
		var html = '';
		
		$('div.module_product_information>ul.tabs>li.sizing ul.tables>li').each(function() {
			
			var tab = $(this).attr('class').replace(' current', '');
			
			html += '<li class="' + tab + ($(this).attr('class') == current ? ' current' : '') + '"><span>' + $(this).children('h4').children('a').text() + '</span></li>';
			
		});
		
		$('div.module_product_information>ul.tabs>li.sizing ul.tables>li>h4').remove();
		
		$('div.module_product_information>ul.tabs>li.sizing ul.tables').before('<ul class="tables-menu">' + html + '</ul>');
		
		$('div.module_product_information>ul.tabs>li.sizing ul.tables-menu>li').click(function() {
			
			if($(this).hasClass('current')) return false;
			
			var target = $(this).attr('class');
			
			$('div.module_product_information>ul.tabs>li.sizing .current').removeClass('current');
			
			$('div.module_product_information>ul.tabs>li.sizing li.' + target).addClass('current');
			
		});
		
	}
	
	
	/**
	 * Gallery
	 **/
	
	$('div.module_gallery div.band ul.thumbs').data('thumbsPerSlide', 8);
	
	$('div.module_gallery div.band').prepend('<p class="prev disabled">Previous Images</p>').append('<p class="next' + ($('div.module_gallery div.band ul.thumbs li').size() <= $('div.module_gallery div.band ul.thumbs').data('thumbsPerSlide') ? ' disabled' : '') + '">Next Images</p>');
	
	$('div.module_gallery div.main').hover(function() {
		$(this).children('ul.tools').data('visibility', 'visible').children('li.previous, li.next').children('a')/* .fadeIn() */.show();
	}, function() {
		$(this).children('ul.tools').data('visibility', 'hidden').children('li.previous, li.next').children('a')/* .fadeOut() */.hide();
	});
	
	$('div.module_gallery ul.tools li.zoom:not(.disabled) a').live('click', function() {
		
		var self = $(this);
		main = self.parents('div.main');
		
		main.addClass('loading');
		
		$('<img />').bind('load', function(){
									
									self.parent('li').addClass('disabled');
									
									main.removeClass('loading').children('div.img-wrap').children('img').replaceWith($(this));
									
									main.children('div.img-wrap').scrollview();
									
								})
								.attr('src', self.attr('href'));
		
		
		
		return false;
		
	});
	
	$('div.module_gallery ul.tools li.disabled a').live('click', function() {
		return false;
	});
	
	$('div.module_gallery div.band').children('p.prev, p.next').click(function() {
		
		var self = $(this);
		viewport = self.siblings('div.window');
		
		thumbs = viewport.children('ul.thumbs');
		
		if(thumbs.is(':animated')) {
			return false;
		}
		
		origOffset = parseInt(thumbs.css('margin-left').replace('px', ''));
		
		if(!viewport.data('offset')) {
			viewport.data('offset', 0);
		}
		
		// if cannot be scrolled
		if(self.hasClass('prev') && origOffset == 0 || (self.hasClass('next') && (viewport.data('offset') + 1) >= (thumbs.children('li').size() / thumbs.data('thumbsPerSlide')))) {
			return false;
		}
		
		offset = (self.hasClass('prev')) ? origOffset + 592 : origOffset - 592;
		
		if(self.hasClass('prev')) {
			viewport.data('offset', viewport.data('offset') - 1);
		}
		else {
			viewport.data('offset', viewport.data('offset') + 1);
		}
		
		// if at beginning, disable prev button
		if(offset == 0) {
			viewport.siblings('p.prev').addClass('disabled');
		}
		else {
			viewport.siblings('p.prev').removeClass('disabled');
		}
		
		// if at end, disable next button
		if((viewport.data('offset') + 1) >= (thumbs.children('li').size() / thumbs.data('thumbsPerSlide'))) {
			viewport.siblings('p.next').addClass('disabled');
		}
		else {
			viewport.siblings('p.next').removeClass('disabled');
		}
		
		// scroll thumbs
		thumbs.animate({marginLeft: offset + 'px'}, 500);
		
	});
	
	$('div.module_gallery ul.thumbs li a, div.module_gallery ul.tools li.previous:not(.disabled) a, div.module_gallery ul.tools li.next:not(.disabled) a').live('click', function() {
		
		// remove the zoom 'scrollview' functionality
		$('div.module_gallery div.main img').unbind('mousedown').unbind('mousemove').unbind('mouseout').unbind('mouseup').unbind('dblclick').parent('div').scrollLeft(0).scrollTop(0);
		
		element = $(this);
		main = element.parents('div.module_gallery').children('div.main');
		
		$.ajax({'url': '/ajax/getgalleryimage' + element.attr('href').replace(/^(.*)\?/, '?'), // the replace here fixes IE adding the current url to a relative link automatically, removes everything before ?
				'data': {'entry_id': main.attr('id').replace('gallery-', '')},
				'beforeSend': function() { main.addClass('loading'); },
				'success': function(data) {
					
					$('<img />').bind('load', function(){
									
									main.removeClass('loading').children('div.img-wrap').children('img').replaceWith($(this));
									
									main.children('ul.tools').html($('ul.tools', data).html());
									
									if(main.children('ul.tools').data('visibility') == 'visible') {
										main.mouseover();
									}
									
								})
								.attr('src', $('div.main div.img-wrap img', data).attr('src'));
					
				}});
		
		return false;
		
	});
	
	
	/**
	 * AJAX Report Comment
	 **/
	
	$('form.report-comment').submit(function() {
		
		element = $(this);
		
		$.ajax({'url': '/ajax/reportcomment',
				'data': {'id': element.children('input[name=id]').val()},
				'dataType': 'json',
				'beforeSend': function() {
					element.children('button').addClass('disabled').attr('disabled', 'disabled').children('span').children('span').text(' ');
				},
				'success': function(data) {
					element.children('button').removeClass('disabled').addClass('off').children('span').children('span').text(data);
				}});
		
		return false;
		
	});
	
	
});

function switchToolbarBox(to_open) {
	
	$(toolbar_boxes).unbind('click').click(function(e) { e.stopPropagation(); });
	
	$(toolbar_boxes).filter(':visible').each(function() {
		$(this).fadeOut(200);
	});
	
	if(to_open) {
		
		var is_open = to_open.is(':visible');
		
		if(!is_open) {
			to_open.fadeIn(200);
		}
		
	}
	
	return true;
	
}