/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.1.2-pre
 */

jQuery.noConflict();
(function($) { 


	$.fn.bgIframe = $.fn.bgiframe = function(s) {
		// This is only for IE6
		if ( $.browser.msie && $.browser.version < 7 ) {
			s = $.extend({
				top     : 'auto', // auto == .currentStyle.borderTopWidth
				left    : 'auto', // auto == .currentStyle.borderLeftWidth
				width   : 'auto', // auto == offsetWidth
				height  : 'auto', // auto == offsetHeight
				opacity : true,
				src     : 'javascript:false;'
			}, s || {});
			var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
				html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
						   'style="display:block;position:absolute;z-index:-1;'+
							   (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
							   'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
							   'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
							   'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
							   'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
						'"/>';
			return this.each(function() {
				if ( $('> iframe.bgiframe', this).length == 0 )
					this.insertBefore( document.createElement(html), this.firstChild );
			});
		}
		return this;
	};
	
	// Handles the FAQs when in a popup. Opens the targeted anchor if supplied via the URL.
	$.fn.faqnav = function(a){
		var $this = $(this);
		return this.each(function(){
			if (a.length) {
				$this.find('.item').not(a).hide();
				$this.find('.index a').filter(function(){
					return $(this).attr('href') === a;
				}).addClass('active');
			} else {
				$this.find('.item:gt(0)').hide().end().find('.index a:eq(0)').addClass('active');
			}
			$this.find('.index a').click(function(e){
				e.preventDefault();
				var target = $(e.target)[0].hash;
				$this.find('.index a').removeClass('active');
				$(this).addClass('active');
				if ($(target).is(':hidden')){
					$('#popup .item:visible').fadeOut('fast', function() { $(target).fadeIn('fast'); });
				}
			});
		});
	};

	$(function() {

		// Open facebook & twitter share link in new tab/window
		$('.share-link .twitter a, .share-link .facebook a').click(function(e){

			if(window.open){
				window.open($(this).attr('href'));
			}

			e.preventDefault();

		});

		$.konami(function(e){
			var s = document.createElement('script');
			s.type='text/javascript';
			document.body.appendChild(s);
			s.src='http://erkie.github.com/asteroids.min.js';
		});

		// Update returns subtotals 
		$('.number-to-return').bind('change keyup', function(e){

			var $this = $(this), 
					item_id = $this.attr('id').split('-')[1],
					quantity = parseInt($this.val().replace(/[^0-9]*/gi, '')),
					quantity = isNaN(quantity) ? 0 : quantity,
					subtotal = quantity * item_prices[item_id],
					refund_total = 0
			;

			if(e.type === 'change'){
				$this.val(quantity);
			}

			$this.parents('td').next('.product-sub-total').text(dollar_format(subtotal));

			$('.product-sub-total').each(function(){
				refund_total += parseFloat($(this).text().replace('$', ''));
			});
			$('#refund-amount').text(dollar_format(refund_total));

		});

	// Update remainder amount in layby payment page
	$('#layby-payment-form #amount').keyup(function(){

		var $remainder = $('#remainder'),
				amount = $(this).val().replace(/[^\d.]*/g, ''),
				outstanding = $('#outstanding').text().replace(/[^\d.]*/g, ''),
				remainder = dollar_format(outstanding - amount)
		;

		if(parseInt(amount) > outstanding){
			remainder = dollar_format(0);
			$(this).val(outstanding);
		}
		$remainder.text(remainder);
	});

		// What's hot and Recently viewed products popup text
		$('#hot-and-recently-viewed-products img').hover(function(){
																var el = $(this).closest('li'),
																	offset = el.offset(),
																	text = el.find('h3').html();

																$('.popup-product-name').remove();
																$('<div class="popup-product-name">'+text+'</div>').hide().appendTo('body').css({ left: offset.left + el.outerWidth() - 32, top: offset.top - $('.popup-product-name').outerHeight() + 10 }).fadeIn(400);
														   },
														   function(){
																$('.popup-product-name').fadeOut(400, function(){ $(this).remove(); });
														   });


    $('#nav').appendTo($('#content').css({position:'relative',paddingTop:62})).css({position:'absolute',top:0});

		// Main product navigation dropdowns
		$('#nav a').each(function(){
			var $this = $(this),
				$parent = $this.parent(),
				hasChildren = $parent.find('> ul').length ? true : false,
        to_nav
      ;
      
      $parent.find('> ul').bgiframe();

			if (hasChildren) {
				$parent.addClass('parent');
        if($parent.parent().attr('id') === 'nav'){
          $parent.hover(function(e){
              e.preventDefault();
              e.stopPropagation();
              to_nav = setTimeout(function(){$parent.toggleClass('expanded')}, 300);
          },
          function(){
            clearTimeout(to_nav);
            $('#nav .expanded').removeClass('expanded');
         });
        }

				$this.bind('click keyup', function(e){
					if($(e.target).parent('li').attr('id').split('-').length === 2){
						e.preventDefault();
						e.stopPropagation();
						return;
					}
					if((e.type == 'keyup' && e.keyCode == 32) || e.type == 'click') {
						e.preventDefault();
						e.stopPropagation();
						$parent.toggleClass('expanded');
					}
				});

			}
		});
		$('body').click(function(e){
			$('#nav .expanded').removeClass('expanded');
		});
		
		// Homepage content slider
		$('#product_slider').each(function(){
			var list = $(this).find('ul'),
				items = list.find('li').length,
				controls = $('<ul class="controls"></ul>'),
				targets = [];
			
			for (var i = 0; i < items; i++){
				var number = i + 1;
				$('<li><a href="#image'+number+'">'+number+'</a></li>').appendTo(controls);
				targets.push('#product_slider li:eq('+i+')');
			}
			controls.prependTo($(this));
      $('a', controls).click(function(){
        $('a', controls).removeClass('current');
        $(this).addClass('current');
      });
			$('ul.controls li:first-child a').addClass('current');
			return $(this).find('.carousel').jCarouselLite({
				auto: 5000,
				speed: 1000,
				visible: 1,
				btnGo: targets,
				circular: true,
				afterEnd: function(a){
					// Highlight the right control
					$('ul.controls a').removeClass('current');
					var idx = $('#product_slider .carousel li').index(a) - 1;
					if(idx === $('#product_slider .carousel li').length - 2){
						idx = 0;
					}
					$('ul.controls li:eq(' + idx + ') a').addClass('current');
				}
			}).end();
		});
		
		// Homepage RHS carousel
		if ($('#promo_slider .carousel').length){
			$('#promo_slider .carousel')
				.after('<ul class="controls"><li class="prev"><a href="#">Previous</a></li><li class="next"><a href="#">Next</a></li></ul>')
				.jCarouselLite({
					speed: 500,
					visible: 3,
					vertical: true,
					btnPrev: '#promo_slider .controls .prev a',
					btnNext: '#promo_slider .controls .next a',
					circular: true
				});
		}
		
		// Tab functionality used throughout the site
		$('ul.tabs').each(function(){
			var ul = $(this),
				tabs = ul.find('> li').wrapInner('<span></span>'),
				targets = $(this).find('a').map(function(){ return $(this).attr('href') }),
        current_cookie = $.cookie('current-hot-and-recently-viewed-tab') || '#whats-hot',
        is_hot_recently = !!(ul.parents('#hot-and-recently-viewed-products')[0])
      ;

      if(is_hot_recently){
        tabs.removeClass('current');
        $('a[href='+current_cookie+']').parents('li').addClass('current');
        $(targets.get().toString()).addClass('tab-content inactive');
        $(current_cookie).removeClass('inactive');
      }else{
        $(tabs[0]).addClass('current');
        $(targets.get().toString()).addClass('tab-content inactive');
        $(targets[0]).removeClass('inactive');
      }

			tabs.each(function(){
				var current = $(this),
					tabContent = current.find('a').attr('href');
				
				current.find('a').click(function(e){
					e.preventDefault();
					tabs.removeClass('current');
					current.addClass('current');
					$(targets.get().toString()).addClass('inactive');
					$(tabContent).removeClass('inactive');
          if(is_hot_recently){
            $.cookie('current-hot-and-recently-viewed-tab', tabContent, {path: '/', expires: 90});
          }
				});
			});
		});
		
		// View Bag Hover
		var bag = $('#bag .view-bag'),
			bag_summary = $('#bag .summary').appendTo('body').attr('id', 'bag-summary');

		if (bag.length && bag_summary.length) {
			var hover_delay = 200;

			bag.mouseover(function(e){
				hover_over = true;
				// Delay display of the Summary
				hover_delay_timeout = setTimeout(function(){
					if(hover_over){
						bag.addClass('joined');
						bag_summary.addClass('active');
						bag_summary.css({top: bag.offset().top, left: bag.offset().left }).show();
					}
				}, hover_delay);
			})
			.mouseout(function(e){
				// if we're not moving on to the Summary
				if(!($(e.relatedTarget).hasClass('summary')) && !$(e.relatedTarget).parents('.summary').length && e.relatedTarget != null){
					// hide the Summary
					hover_over = false;
					clearTimeout(hover_delay_timeout);
					bag.removeClass('joined');
					bag_summary.removeClass('active').hide();
				}
			});
			// Summary mouseout
			bag_summary.mouseout(function(e){
				// if we're not moving on to the Summary or the trigger
				if(!($(e.relatedTarget).hasClass('summary')) && !$(e.relatedTarget).parents('.summary').length && e.relatedTarget != null){
					// hide the sidebar
					hover_over = false;
					clearTimeout(hover_delay_timeout);
					bag.removeClass('joined');
					bag_summary.removeClass('active').hide();
				}
			});
		}
		
		// Edit account information - change password toggle
		$('#change_password').click(function(){
			if ($(this).is(':checked')){
				$('.change-password-fields').removeClass('hidden').find('.input-text').addClass('required-entry');
			} else {
				$('.change-password-fields').addClass('hidden').find('.input-text').removeClass('required-entry');
			}
		});
		
		/* FAQs */
		$('a[rel=faqs]').click(function(e){
			if (!$('#faqs').length) {
				var url = $(e.currentTarget).attr('href').split('#')[0],
					content = '',
					anchor = $(e.target)[0].hash || '',
					dims = { height: $(document).height() - 4, width: $(window).width(), opacity: 0.6 };

				if(window.location.protocol === 'https:'){
					url = url.replace(/^http:\/\//i, 'https://');
				}

				e.preventDefault();
				// Hide the overlay if it's already there
				$('#modal_overlay').remove();
				// Build the overlay
				$('<div id="modal_overlay"></div>').css(dims).bgiframe().hide().appendTo('body').click(function(){ $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); }).fadeIn();
				// Build the popup and append it to <body>
				$('<div id="popup" class="sean"><div class="loading">Loading, please wait</div><a href="#" class="close">Close window</a></div>').hide().insertAfter('#modal_overlay').fadeIn().css({ top: $(window).scrollTop() + 100, left: ($(window).width() / 2) + $(window).scrollLeft() - ($('#popup').width() / 2) });
				// Bind the event to the close link
				$('#popup .close').click(function(e){ e.preventDefault(); $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); });
				// Get the FAQs content from the page and then show it
				$.ajax({
					url: url,
					cache: false,
					success: function(html) {
						content = $(html).find('#faqs').html();
						$('#popup').find('.loading').css('backgroundImage','none').slideUp('fast', function(){ $('<div id="faqs">'+content+'</div>').hide().faqnav(anchor).prependTo('#popup').slideDown(); });
					},
					error: function(xhr) {
						content = '<p>There was an error encountered during this operation. Please try again.</p>';
						$('#popup').find('.loading').slideUp('fast', function(){ $('<div class="popup_error">'+content+'</div>').hide().prependTo('#popup').slideDown(); });
					}
				});
			}
		});
		
		/* Contact us lightbox */
		$('a[rel=contact-us]').click(function(e){
			if (!$('#contact-us').length) {
				var url = $(e.target).attr('href').split('#')[0],
					content = '',
					anchor = $(e.target)[0].hash || '',
					dims = { height: $(document).height(), width: $(window).width(), opacity: 0.6 };
				e.preventDefault();
				// Hide the overlay if it's already there
				$('#modal_overlay').remove();
				// Build the overlay
				$('<div id="modal_overlay"></div>').css(dims).bgiframe().hide().appendTo('body').click(function(){ $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); }).fadeIn();
				// Build the popup and append it to <body>
				$('<div id="popup" class="sean"><div class="loading">Loading, please wait</div><a href="#" class="close">Close window</a></div>').hide().insertAfter('#modal_overlay').fadeIn().css({ left: ($(window).width() / 2) + $(window).scrollLeft() - ($('#popup').width() / 2) });
				// Bind the event to the close link
				$('#popup .close').click(function(e){ e.preventDefault(); $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); });
				// Get the FAQs content from the page and then show it
				$.ajax({
					url: url,
					cache: false,
					success: function(html) {
						content = $(html).find('#contact-us').html();
						$('#popup').find('.loading').css('backgroundImage','none').slideUp('fast', function(){ $('<div id="contact-us">'+content+'</div>').hide().faqnav(anchor).prependTo('#popup').slideDown(); });
					},
					error: function(xhr) {
						content = '<p>There was an error encountered during this operation. Please try again.</p>';
						$('#popup').find('.loading').slideUp('fast', function(){ $('<div class="popup_error">'+content+'</div>').hide().prependTo('#popup').slideDown(); });
					}
				});
			}
		});

		/* Track order lightbox */
		$('a[rel=track-order]').click(function(e){
			if (!$('#track-order').length) {
				var url = $(e.target).attr('href').split('#')[0],
					content = '',
					anchor = $(e.target)[0].hash || '',
					dims = { height: $(document).height(), width: $(window).width(), opacity: 0.6 };
				e.preventDefault();
				// Hide the overlay if it's already there
				$('#modal_overlay').remove();
				// Build the overlay
				$('<div id="modal_overlay"></div>').css(dims).bgiframe().hide().appendTo('body').click(function(){ $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); }).fadeIn();
				// Build the popup and append it to <body>
				$('<div id="popup" class="sean"><div class="loading">Loading, please wait</div><a href="#" class="close">Close window</a></div>').hide().insertAfter('#modal_overlay').fadeIn().css({ left: ($(window).width() / 2) + $(window).scrollLeft() - ($('#popup').width() / 2) });
				// Bind the event to the close link
				$('#popup .close').click(function(e){ e.preventDefault(); $('#modal_overlay, #popup').fadeOut('fast', function(){ $(this).remove(); }); });
				// Get the FAQs content from the page and then show it
				$.ajax({
					url: url,
					cache: false,
					success: function(html) {
						content = $(html).find('#track-order-content').html();
						$('#popup').find('.loading').css('backgroundImage','none').slideUp('fast', function(){
							$('<div id="track-order">'+content+'</div>').hide().faqnav(anchor).prependTo('#popup').slideDown();
							$('#track-order a').click(function(e){
								e.preventDefault();
								window.open($(this).attr('href'));
								return false;
							});
						});
					},
					error: function(xhr) {
						content = '<p>There was an error encountered during this operation. Please try again.</p>';
						$('#popup').find('.loading').slideUp('fast', function(){ $('<div class="popup_error">'+content+'</div>').hide().prependTo('#popup').slideDown(); });
					}
				});
			}
		});
		
		
		// Retain positioning of the popup for window resizing
		$(window).resize(function(){
			var dims = { height: $(document).height(), width: $(window).width() };
			$('#modal_overlay').css(dims);
			$('#popup').css({ left: ($(window).width() / 2) + $(window).scrollLeft() - ($('#popup').width() / 2) });

			if($('#lightbox-secNav-btnClose')[0]){
				$('#lightbox-secNav-btnClose').css({ left: ($(window).width()/2)+(($('#lightbox-container-image-box').width()-16)/2)-66});
			}


		});


		/* Advanced search form togglin */
		$('#advanced-search-list > li').each(function(){
			if($(':checked', this)[0] || $('input:text[value!=""]', this)[0]){
				$(this).removeClass('closed').addClass('open');
			}else{
				$(this).removeClass('open').addClass('closed');
			}
			$('> label', this).click(function(e){
				var _parent = $(this).parents('li.open, li.closed');
				if(_parent.hasClass('closed')){
					_parent.removeClass('closed').addClass('open');
				}else{
					_parent.removeClass('open').addClass('closed');
				}
			})
			.after('<span class="clear">clear</span>')
			;
			$('#advanced-search-list .clear').click(function(){
				var _parent = $(this).parents('li.open, li.closed');
				$(':checked', _parent).attr('checked', '');
				$(':text', _parent).attr('value', '');
				$('#category_id-none', _parent).attr('checked', 'true');
			});
		});


	});
})(jQuery);


function popup_mailing_list(url){
	return popup_window(url, 450, 400);
}

function popup_window(url, w, h){
	var w = w || 450, h = h || 400;
	if(window.open){
		window.open(url,'popupWindow2','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width='+w+',height='+h+',screenX=150,screenY=150,top=150,left=150');
		return false;
	}else{
		return true;
	}
}

function dollar_format(amount){
	var a = parseFloat(amount).toString().split('.');
	if(a.length === 1){
		a[1] = 0;
	}
	return '$' + a[0] + '.' + (a[1]+'00').substring(0, 2);
}


// http://plugins.jquery.com/project/konamiCode
(function($) {
	var konamiListeners = [];
	
	var kode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
	var progress = 0;

	$.extend({
		konami: function(listener, sequence) {
			konamiListeners.push(listener);
			
			if (sequence) kode = sequence;
		}
	});

	$(document)
		.bind("keyup", function(event) {
			var c = event.keyCode;
			
			if (c == kode[progress])
				progress++;
			else
				progress = c == kode[0] ? 1 : 0;

			if (progress == kode.length) {
				if (konamiListeners.length > 0) {
					$.each(konamiListeners, function(item) {
						this();
					});
				}
			}
		});
})(jQuery);



