//////////////////////////////////////////
//  Delay Plugin
/////////////////////////////////////////
(function($){
	$.fn.delay = function(time, callback){
		jQuery.fx.step.delay = function(){};
		return this.animate({delay:1}, time, callback);
	}
})(jQuery);
////////////////////////////////////////
// Over Label
////////////////////////////////////////
jQuery.fn.overlabel = function() {
    this.each(function(index) {
        var label = $(this); var field;
        var id = this.htmlFor || label.attr('for');
        if (id && (field = document.getElementById(id))) {
            var control = $(field);
            label.addClass("overlabel-apply");
            if (field.value !== '') {
                label.css("display", "none");
            }
            control.focus(function () {label.css("display", "none");}).blur(function () {
                if (this.value === '') {
                    label.css("display", "block");
                }
            });
            label.click(function() {
                var label = $(this); var field;
                var id = this.htmlFor || label.attr('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            });
        }
    });
};
//////////////////////////////////////////
// Tool Tip
/////////////////////////////////////////
(function($){
	$.fn.tooltip = function(options) {
		var defaults = {  
			contentToFetch : '.itemInfo h1',
			contentToShow: 'h3, h4, .price',
			classToShow: 'tt'  
		};  
		var options = $.extend(defaults, options);
		
		var loaderPath = '/media/images/loaderSmall.gif';

		this.each(function() {

			var $this = $(this);
			var $url = $this.attr('href');

			if($this.is('a')) {
                
				var $content = $this.siblings(options.contentToShow);
	
				// Remove default attribute behaviour
				this.title = '';

				$this.hover(function(e){
 
					// Make sure previously displayed tip is out of DOM
					$('.tt').remove();
					// Create Tool Tip
					$('<div class="'+options.classToShow+'" />').appendTo('body').hide().html($content)
					// Position tool tip and fade it in
					.css({ top: e.pageY - 130, left: e.pageX - 265})
					// Fade it in
					.delay(500).fadeIn(100);

				}, function(e){
					$('.tt').remove();
				});

				// Mouse Move
				$this.mousemove(function(e) {
					$('.tt').css({
						top: e.pageY - 130,
						left: e.pageX - 265
				     });
				});

			}
			
			
			
			
		  });
		  return this;
	}
})(jQuery);
//////////////////////////////////////////
// Page Slicer
/////////////////////////////////////////
(function($){

	
	
	var overlay = '<div id="sliceOverlay" class="loading"><div class="wrapper"></div></div>';
	
	$.fn.pageSlice = function(options) {
		var defaults = {  
			contentToFetch : '.content',
			overlayColor : '#111',  
			onAfter : function(){} ,
			onBefore : function(){}  
		};  
		var options = $.extend(defaults, options);

		this.live('click', function() {
			var $this = $(this);
			
			var winY = $(window).height();
			var winX = $(window).width();
			
			
			
			// Append Overlay to body
			$('body').prepend(overlay);
			// Set up Dimensions and Hide
			$('#sliceOverlay').css({
				'width' : winX,
				'height' : 20,
				'backgroundColor' : options.overlayColor,
				'top' : $(window).scrollTop()
			});
			// Begin Ajax Request
			$.ajax({
				type: 'get',
				url: $(this).attr('href'),
				dataType: 'html',
				success: contentLoaded
			});
			// Ajax Success
			function contentLoaded(html) {
				
				options.onBefore.call();
				
				var $html = jQuery('<div>'+html+'</div>').find(options.contentToFetch);
				// Remove loader and Attach fetched content to tool tip
				$('#sliceOverlay .wrapper').append($html);
				// Slide Down Overlay
				$('#sliceOverlay').delay(500, function(){
					$(this).removeClass('loading').animate({'height' : winY});
				});
				
				options.onAfter.call();
			
			}
			
			// remove default link functionality
			return false;
			
		});
		return this;
	}
	// overlay window events
	$(window).scroll(function(){
		// Simulate Position : Fixed for overlay
		$('#sliceOverlay').css('top', $(window).scrollTop() + "px");
		// Scroll Content
		$('#sliceOverlay .wrapper').css('top', - $(window).scrollTop()  + "px");
	});
	$(window).resize(function(){
		$('#sliceOverlay').css({
			'width' : $(window).width() + "px",
			'height' : ($(window).height() + 20) + "px"
		});
	});
	// Close Button
	$('#sliceOverlay, #sliceOverlay a.close').live('click', function(){
		// Slide Overlay up
		$(this).parents('#sliceOverlay').slideUp()
		// wait half a second and remove it from DOM
		.delay(500, function(){
			$(this).remove();
		});
	});
})(jQuery);

//////////////////////////////////////////
// Document Ready
/////////////////////////////////////////
$(document).ready(function(){

	$('a[rel=external]').click(function(){
		window.open(this.href);
		return false;   
	}); 
	
	//////////////////////////////////////////
	//  Contact Overlay
	/////////////////////////////////////////
	$('#primeNav #contactBu a').pageSlice({
		contentToFetch : '.formWrap',
	 	onAfter : initForm 
	});
	//////////////////////////////////////////
	//  Mailing list Overlay                   
	$('a[href=/mailing-list]').pageSlice({
		contentToFetch : '.formWrap'//,  KMB
		//onAfter : initForm   KMB
	});
	//////////////////////////////////////////
	//  Size Chart Overlay
	/////////////////////////////////////////
	$('#sizechart').pageSlice({
		contentToFetch : '.formWrap',
	 	onAfter : initForm 
	});

	// Initialize From
	function initForm() {
		$('.formWrap form').before('<a class="close">Close</a>'); 
		$('#sliceOverlay label.ol').overlabel();
		$.getScript("/includes/js/jquery.validate.js", function(){
			$('#sliceOverlay form').validate({ submitHandler : ajaxSubmit });
			$('#sliceOverlay form').validate();
		});
	}
	// ajax Submit
	function ajaxSubmit(form){

		var name = $('#name').val(); 
		var email = $('#email').val();  
		var data = $(form).serialize();

		$(form).addClass('working');

		$.ajax({
			type: "POST",
			url: "/testForm.php",
			data: data,
			success: function() {
				$(form).removeClass('working').find('p').remove();
				$('#contactForm .legend').text('Thanks!').after('<p class="success">We will be in touch shortly.<br /><br /><a class="close">Close</a></p>');
				$('#mailForm .legend').text('Thanks!').after('<p class="success">A confirmation email has been sent to:<br />'+email+'<br /><br /><a class="close">Close</a></p>');
			}
		});
		return false;
	}
	$('.success p a').live( 'click', function(){
		$('a.close').trigger('click');
	});


	
	
	//////////////////////////////////////////
	//  Feeds (hover + click functionality)
	/////////////////////////////////////////
	$('.feed li').hover(function(){
		$(this).addClass('hover');
	}, function(){
		$(this).removeClass('hover');
	});

	$('.dealers li').each(function(){	
		$(this).click(function(){
			var $link = $(this).children('a').attr("href");		
			if($link!='#')
			{
				window.open($link);
				return false; 
			}
		});
	});
	
	$('.news li').each(function(){	
		$(this).click(function(){
			var $link = $(this).find('a').attr("href");		
			window.location = $link;
			return false;
		});
	});
	
	$('.relatedCarousel .feed li').each(function(){	
		$(this).click(function(){
			var $link = $(this).find('a').attr("href");		
			window.location = $link;
			return false;
		});
	});

	//////////////////////////////////////////
	//  Home Slide Show init
	/////////////////////////////////////////
	$('div.slide img').hide();
	$('#homePage #siteHeader').addClass('loading');
	// Check for plugin and cycle
	if(jQuery.fn.cycle) {
		$('#homePage div.slide').delay(5000, function(){
			$(this).cycle({ 
				speed : 1000, 
				timeout : 5000 
			});
		});
	}

	//////////////////////////////////////////
	//  Store Page Tool Tip init
	/////////////////////////////////////////
	// Remove alt Attribute Functionality
	$('#storePage .grid img').attr('alt', '');
	$('#storePage .grid li a').tooltip();
	
	$('.cvv').tooltip({
		contentToFetch : '.cvv',
	 	contentToShow : '.cvv-image',
	 	classToShow : 'cvv-hover'
	});

	
	//////////////////////////////////////////
	//  Item Detail
	/////////////////////////////////////////
	// Selectbox Replacement
	if(jQuery.fn.selectbox) {
		$('#product-size').selectbox();
	}
	// Size Hover
	$('#product-size_container li').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
	// Size Validate
	function validateOpts() {
		var formId = $(this).parents('form').attr('id');
		$('#'+formId).submit(function(){
			if($('#product-size').val() === 'none') {
				$('#product-size').after('<p class="error">Please Select a Size.</p>');
				return false;
			}
		});
	}
	$('.itemPurchase button').click(validateOpts);
	
	$('#product-size_container li').click(function(){
		$('p.error').remove();
	});
	
	// Item Image Viewer
	var cycleOpts = {
		fx:     'fade', 
		speed:  500, 
 		timeout: 0, 
		next: '.slide img', 
		pager:  '.slideThumb ul',
		pagerAnchorBuilder: function(idx, slide) { 
			return '.slideThumb ul li:eq(' + idx + ') a'; 
		}
	}
	if(jQuery.fn.cycle) {
		$('.itemPic.slide').cycle(cycleOpts);
	}
	//////////////////////////////////////////
	//  Carousels
	///////////////////////////////////////// 
	$('#storePage .carousel').each(function(){ 
        var $scrollID = $(this).parents('div').attr('id');
		var $items = $('#'+$scrollID+' .carousel ul');
		var carouselNav = '<span class="prev"><a>Previous</a></span><span class="next"><a>next</a></span>';

		if ($items.length > 1) {
			$(this).parents('#'+$scrollID).append(carouselNav);
			$('#'+$scrollID+' .carousel').cycle({ 
				fx:     'scrollHorz', 
				speed:  500, 
				timeout: 0,
				prev: '#'+$scrollID+' .prev a',
				next: '#'+$scrollID+' .next a'
			});
		}  

	});
	// Gallery Psuedo Load
	$('#galPage #siteHeader').addClass('loading'); 
	$('.col-1-gal #primaryContent img').hide();
	//////////////////////////////////////////
	//  Collections
	/////////////////////////////////////////
	var $collections = $('#collectionPage .carousel ul');

	if ($collections.length > 1) {
		$('div#secondaryContent').after('<div class="controls"><ul class="carsouselControl"></ul></div>');
		$('.carsouselControl').append('<li class="prev"><a>Previous</a></li><li class="next"><a>Next</a></li>');
		$('#secondaryContent .carousel').cycle({ 
			fx:     'scrollHorz', 
			speed:  500, 
			timeout: 0,
			prev: '.controls .prev a',
			next: '.controls .next a'
		});
	}
	
	$('#collectionPage #primaryContent>a, #collectionPage #secondaryContent li>a').pageSlice({
		contentToFetch : '.tools, .slide, .slideControl, #collectionInfo',
		overlayColor : '#FFFFFF',
		onAfter : initCollection
	});
	
	function initCollection() { 
		$('#collectionPage .slide').cycle({
			timeout: 0,
			prev: '.slideControl .prev a',
			next: '.slideControl .next a' 				
		});
		
		$('#collectionPage .slide img').each(function(){	
			var $l = (900 - $(this).width())/2;
			var $t = (600 - $(this).height())/2;
			$(this).css('left', $l);
			$(this).css('top', $t);		
		});
	}
	
	//////////////////////////////////////////
	//  Related Stories Carousel
	/////////////////////////////////////////	
	var $stories = $('#newsPage .relatedCarousel ul.feed');	

	if ($stories.length > 1) {
		$('.relatedStories').append('<div class="controls"><span class="prev"><a>previous</a></span><span class="next"><a>next</a></span></div>');
		$('#newsPage .relatedCarousel').cycle({ 
			fx:     'scrollHorz', 
			speed:  500, 
			timeout: 0,
			prev: '.prev a',
			next: '.next a'
		});
	}
			
   
	
	//////////////////////////////////////////
	//  Product Size Select
	/////////////////////////////////////////
	$('#product-size_container ul li').live('click', function(){		
		$this = $(this);
		$id = $this.attr("id");		
		$splitId = $id.split('_');		
		$('#item_size').val($splitId[$splitId.length-1]);
		$('#submit-error').hide();
	});
	
	//////////////////////////////////////////
	//  Check Size Select
	/////////////////////////////////////////
	$('#item-submit').click(function(){
		$this = $(this);
		if($('#item_size').val()=='null')
		{
			$('#submit-error').show();		
			return false;
		}
		else
		{
		
		}	
	});
	
	//////////////////////////////////////////
	//  Shipping Billing
	/////////////////////////////////////////
	$('#sameAs').click(function(){	
		var $fields = new Array('name','company','address','address_2','city','state','state_txt','country','phone','zip');
		for (var q in $fields) {
			$('#shipping_'+$fields[q]).val($('#billing_'+$fields[q]).val());
		}
		jQuery("#shipping_country").trigger('change');
	});

	
});

//////////////////////////////////////////
// Psuedo Loader
/////////////////////////////////////////
var i = 0;
var int = 0; // for IE
function loadPic() {
	var $slides = $('div.slide img').length;
	if (i >= $slides) {
		clearInterval(int);
	}
	$('div.slide, .col-1-gal #primaryContent').find('img:hidden').eq(0).fadeIn(500);
	$('#siteHeader').removeClass('loading');
	i++;
}
$(window).bind('load', function() {
	var int = setInterval('loadPic(i)', 100);
});


