jQuery(document).ready(function($) {

// ===========
// = CLASSES =
// ===========	
	// Add JS enabled class
	$('body').addClass('hasjs');
	
	// Add .first & .last
	function fnl () {
		$('li,article,img,.col,.rounded').firstnlast();
	}
	
	// remove margin-right from every 4th thumbnail on Gallery page.
	$('ul.thumbs li:nth-child(4n+4)').addClass('right-edge');
	
	// Adding parent classes for input fields based on their type attribute
	$('input').each(function(index) {
		$(this).parent().addClass($(this).attr('type'));
	});
// ==============
// = DIMENSIONS =
// ==============
	// Grid, anti img collapse.
	$('.slideshow').not('#slider > .slideshow').tallest('img',50);
	$('.image_group').not('#slider > .slideshow').tallest('img',14);
	if ($('.no_tallest').length) {
		$('.no_tallest').tallest('img',0);
	};

	$('.article_overview').equalHeights();

// =================
// = MANIPULATIONS =
// =================

// ===============
// = VALIDATIONS =
// ===============

// =================
// = RETAILER LIST =
// =================

	function retailers() {
		var list = '#retailer_list',
			links = $('.entry a', list),
			call;
			
			// hide details
			$('#show_retailer article')
				.hide() // hide all retailers when loading the page
				.css({ // stop random jumps when fadeing in elements
					position: 'absolute',
					top:0,
					left:0
				});

			// load
			$('ul.region').next('ul').addClass('cities').hide();
			$('ul.entries').hide();
			
			// stop clicks
			$('a', list).click(function(e) {
				e.preventDefault(); // stop the click
				if ( $(this).parent().hasClass('entry') ) { // if this is an entry go to href
					call = $(this).attr('href');
					if ($('#show_retailer article:visible').length) { // if anything is currently displayed
						$('#show_retailer article:visible').fadeTo(200,0,function() { //fadeOut
							$(this).css('display', 'none');
							$('#show_retailer article#'+call).fadeTo(300,1); // fade in new called entry
						});
					} else { // if nothing is displayed just call the clicked entry
						$('#show_retailer article#'+call).fadeTo(300,1);
					};

				} else {
					if ($(this).parent('h4').next('ul').hasClass('entries')) { // if the clicked ele is a heading / contains children then trigger a slide down.
						$(this).parent('h4').next('ul.entries').slideToggle('fast', function() {$(this).toggleClass('expanded')});
					} else {
						$(this).closest('ul').next('ul').slideToggle('fast', function() {$(this).toggleClass('expanded')});
					};
					
				};
				
			});
		
		
	};
	if ( $('body').hasClass('retailers')) {
		retailers();
	}

// ===================
// = ARTICLE LINKING =
// ===================
$('.article_overview article').each(function(index) {
	$(this).css('cursor', 'pointer');
	$(this).click(function() {
		window.location = $(this).find('a._more').attr('href');
	});
});
// ================
// = QUICK SELECT =
// ================
	var $qs = $('#quick_dd');
	$qs.change(function() {
		if ( $('option:selected').attr('value') != '') { // don't do anything if 'please choose one' remains selected
			window.location = $('select option:selected').attr('value'); // goto page url
		}
	});

// =======
// = NAV =
// =======
	if ( $('#jump_nav').length ) {
		// Attached NAV
		var $navEl 	= '#jump_nav';
		var $navTop = $($navEl).offset().top - parseFloat(20);
	
		// set parent to position:relative
		$($navEl).parent().css('position', 'relative');
		// set next article to not collapse
		var $navPar = $($navEl).parent();
		if ($($navEl+'.fixed')) {
			$($navPar).next().css('float','right');
		}
		$(window).scroll(function() {
		    var y = $(window).scrollTop();
    
		    if (y >= $navTop) {
		        $($navEl).addClass('fixed');
		    } else {
		        $($navEl).removeClass('fixed');
		    }
		});


		// if ($("footer").position().top > $(window).height()) {
		// $(window).resize(function() {
		// 	shiftArticles();
		// });
		// $(window).scroll(function() {
		// 	shiftArticles();
		// });
		// }
	
		// function shiftArticles () {
		// 	var  $nav = $('#jump_nav')
		// 		,$navHeight = $nav.height()
		// 		,$navTop = $nav.offset().top
		// 		,$navBottom = $navTop+$navHeight
		// 		,$footer = $('footer')
		// 		,$footerHeight = $footer.height()
		// 		,$footerTop = $footer.offset().top
		// 		,$parent = $nav.parent().next()
		// 		,$lastArticle = $('article:last-child',$parent)
		// 		,$laHeight = $lastArticle.height()
		// 		,$viewport = window.innerHeight
		// 		,$doc = $(document).height()
		// 		,$difference = null
		// 		;
		// 	
		// 	
		// 				
		// 		$difference = ( $viewport - $footerHeight );
		// 	$(window).scroll(function() {
		// 		$parent.css('padding-bottom', $difference - $footerHeight + 10);
		// 	});
		// 	$(window).resize(function() {
		// 		$parent.css('padding-bottom', $difference - $footerHeight + 10);
		// 	});
		// 
		// };
		// shiftArticles();
	} // close the if statement for the #jump_nav check.
// ==========
// = IMAGES =
// ==========
if ( $.browser.msie != true || $.browser.msie == true && parseInt($.browser.version) >= "9") { // only if not IE 8 and lower (IE 9 support rounded corners)
	// alert('Rounded Actions!');
	// Img rounded corners.
	$('.slideshow:not(".with_caption") img').each(function(index) {

		$this = $(this);
		$src = $(this).attr('src');
		$height = $(this).closest('.slideshow').height();
		$width = $(this).closest('.slideshow').width();
		
		// $(this).wrap(
		// 	$('<div/>', {
		// 	class: 'rounded',
		// 	css: {
		// 		background: 'url('+$src+') repeat center center',
		// 		height:$height,
		// 		width:$width
		// 	}
		// }));
		
		$(this).wrap('<div class="rounded" />');
		$(this).closest('div.rounded').css({
			'background-image':'url('+$src+')',
			'background-position':'center center',
			'background-repeat':'repeat',
			'height':$height,
			'width':$width
		});
	});
	
	$('img.round').each(function(index) {

		$src = $(this).attr('src');
		$height = $(this).height();
		$width = $(this).width();

		if ( $src != '' ) {	// if image src broken display alt text and skip this image
		$(this).wrap('<div class="rounded image"></div>');
		$(this).closest('div.rounded').css({
			'background-image':'url('+$src+')',
			'background-position':'center center',
			'background-repeat':'repeat',
			'height':$height,
			'width':$width
		});
		$(this).hide();
		} // end if
	});
} // close browser sniffing if statement
		
	// Grid background fade
	$('section .product').each(function(index) {
		var container = $(this);
		container.append( $("<div>")
		      .attr('class', 'background')
		      .css({
		        backgroundColor:'black',
				opacity:0,
		        position: 'absolute',
		        top:0,
		        left:0,
		        zIndex:-1,
		        width:container.outerWidth(), 
		        height:container.outerHeight()
		      }) 
		    );
		// Grid Overview - Text reveal
		$(this).hover(function() {
			$('.image_group img.first',$(this)).fadeIn('fast');
			$('.background', container).fadeTo(400, 0.8);
		}, function() {
			$('.image_group img.first',$(this)).fadeOut('fast');			
			$('.background', container).stop().fadeTo(400, 0.0);
		});
	});
	
	
	
	
	// On hover of the item, dim other items of the same type to 50% while keeping the current one at 100%. When non hovered all items are 100%
	$("section.article_overview").delegate("article", "mouseover mouseout", function(e){
	    $(this).siblings().css("opacity", e.type == 'mouseover' ? 0.3 : 1);
	});
	
// =========
// = FORMS =
// =========	
	// DefaultValue for form input labels
	// $('#fullname').defaultValue('Full Name');
	// $('#emailaddress').defaultValue('Email Address');
	$('form div.input label').autoLabel();
	
	// Submit Button opacity control
	$('footer button.submit').fadeTo(0,0.4); // hide the submit button on load
	$('input[type=checkbox]').live('click', function(event) {
		chkbox(); // run checker function on click
	});
	function chkbox () {
		if ( $('#optin:checked').length ) { // if checked
			$('footer button.submit').fadeTo(200,1); // show
		} else if ( $('#optin:not(:checked)').length ) { // if not checked
			$('footer button.submit').fadeTo(200,0.4); // hide
		}
	};
	chkbox(); // run once on load
	
	
	function validator() {
		var form = $('#newsletter-form'),
			fields = form.find('input'),
			isValid = true,
			inputs = fields.serializeArray();
			
			
			function check() {
				isValid = true;
				
				$.each(fields, function(i, item) {
				  	if (item.value == "" || item.className == "error") {
						isValid = false;
					}
					return isValid;
				});
				
			};

			function errorClass() {
				form.find('.error').removeClass('error');
				
				fields.each(function(i) {

					if (this.type == "checkbox" && this.checked != true) {
						$(this).addClass('error');
						$(this).next('label').addClass('error');
					} else if (this.type == "text" && this.value == "") {
						if ($(this).parent('div')) {
							$(this).parent('div').addClass('error');
						} else {
							$(this).addClass('error');
						};
					}
				});
			};

		
			function subscribe() {	
				if ($('#postFrame').length==0) {
			  		var frame = $('<iframe />', {width:'0', height:'0', src:'#', id:'postFrame', name:'postFrame'}).appendTo('body');
			  		$(frame).load(function(){$(this).remove();})
			  		this.target = 'postFrame'; // referencing the name not ID.
				}
				form.fadeOut('slow', function() {
					$(this).remove();
					$('footer .newsletter').append('<p class="success">Thanks, you have subscribed successfully.</p>');
				});
			};
			
		
		fields.live('keydown keyup focus blur', function(event) {
			check();	
		});
		
		form.submit(function(e) {
			errorClass();
			check();
			
			
			if (isValid) {
				// e.preventDefault();
				subscribe();
			} else {
				errorClass();
				e.preventDefault();
			};
		});
		
	};
	validator();

	function contactValidation() {
		var form = $('#contact_form'), // set the form id
			fields = form.find('input[type!="hidden"],textarea'), // get all inputs in the form
			isValid = true; // set isValid switch.
			
			function errorChecker(current) {
				isValid = true;
				
				
				if (current) {

					if (current.val() == "") {
						current.parent().prev('label').addClass('error');
						isValid = false;
					} else {
						current.parent().prev('label').removeClass('error');
					}
				
				} else {
					$.each(fields, function(i, input) {
						if (input.value == "") {
							$(this).parent().prev('label').addClass('error');
							isValid = false;
						}
					});
				}

				if (!isValid) {
					return isValid;
				};
			}
			
			fields.live('focus keyup blur', function(event) {
				if (event.type != 'focusin') {
					errorChecker($(this));
				}
			});
						
			form.submit(function(e) {
				errorChecker(); // check for errors

				if (!isValid) { // if form is invalid
					e.preventDefault(); // stop sending of form.
					// console.log('prevented');
				} else {
					// e.preventDefault();
					// console.log('sent');
					form.fadeOut('slow', function() {
						form.parent().append('<p class="success">Thank you for your email.</p>');
					});
					
				}
			});
	}
	contactValidation();
	
	// Adding focus states
	// $('input,textarea').focus(function() {
	// 	$(this).addClass('active');
	// });
	// $('input,textarea').blur(function() {
	// 	$(this).removeClass('active');
	// });
	
	$('input,textarea').bind('focus blur', function(event) {
		$(this).toggleClass('active');
	});
	
	// On hover of the item, dim other items of the same type to 50% while keeping the current one at 100%. When non hovered all items are 100%
	$("div.articles").delegate("article", "mouseover mouseout", function(e){
	    $(this).siblings().css("opacity",e.type == 'mouseover' ? 0.5 : 1);
	});

// ================================
// = PLUGIN SETTINGS & INITIATION =
// ================================

    // Anchor scrolling
	if ( $('body').hasClass('retailers') == true ) {
		// $('#show_retailer').tallest('article',0);
		// $('#show_retailer > article').height($('#show_retailer').height());
		// $('#retailer_list').localScroll({
		// 	target: '#show_retailer'
		// });
	} else {
    	$.localScroll('div.articles.col');
	}
		$.localScroll.hash(); // look for # in the URL
    	
	// ==========================
	// = GALLERY FADE SLIDESHOW =
	// ==========================
	// Thumbnail hover
	$('ul.thumbs li.active a').fadeTo(0, 1);
	$('ul.thumbs li a').fadeTo(0, 0.3);
	
	$('ul.thumbs li').hover(function() {
		if ($(this).hasClass('active')) {
		} else {
			$(this).find('a').fadeTo("fast", 1);
		};
	}, function() {
		if ($(this).hasClass('active')) {
		} else {
			$(this).find('a').fadeTo("fast", 0.3);
		};
	});


	if ($('.slideshow').length) {
	
		// redefine Cycle's updateActivePagerLink function 
		$.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) { 
		    $(pager).find('li').removeClass('active') 
		        .filter('li:eq('+currSlideIndex+')').addClass('active'); 
		};
		
	if ($('#slider .slideshow').length) {
		$('#slider .slideshow').cycle({ 
		    fx:     'fade', 
		    speed: 	4000,
		    timeout: 2000, 
		    pager:  '#slider ul', 
		    pagerAnchorBuilder: function(idx, slide) { 
		        // return selector string for existing anchor 
		        return '#slider ul li:eq(' + idx + ') a'; 
		    } 
		});
		// Make the click on image trigger url without breaking IE
		function clickImg() {
			$('#slider .slideshow').css('cursor', 'pointer');
			$('#slider .slideshow').find('img,div').click(function() {
				var ele = this.nodeName.toLowerCase();
				if ( ele == 'div') {
					window.location = $(this).find('img').attr('alt');
				} else if ( ele == 'img') {
					window.location = $(this).attr('alt');
				};
			});
		};
		clickImg();
	}
	if ($('section.gallery .slideshow').length) {
		$('section.gallery .slideshow').cycle({ 
		    fx:     'fade', 
		    speed: 	2000, 
		    timeout: 2000,
			before: function() {$('ul.thumbs li.active').find('a').fadeTo(600,0.3)},
			after: function() {$('ul.thumbs li.active').find('a').fadeTo(150,1)},
			pause: 1,
			pauseOnPagerHover: 1,
		    pager:  'ul.thumbs', 
		    pagerAnchorBuilder: function(idx, slide) { 
		        // return selector string for existing anchor 
		        return 'ul.thumbs li:eq(' + idx + ') a'; 
		    } 
		});
	}
	// var slideIndex;
	// function onAfter(curr,next,opts) {
	// 	current = opts.currSlide,
	// 	next	= opts.currSlide+2,
	// 	prev	= opts.currSlide-1,
	// 	thumb	= 'ul.thumbs li';
	// 
	// 	$(thumb).eq(slideIndex+1).children('a').fadeTo('fast', 1);
	// 	$(thumb).eq(slideIndex).children('a').fadeTo('fast', 0.3);
	// 			
	// 	slideIndex = current;
	// 	console.log(slideIndex);
	// };

	if ($('.slideshow.with_caption').length) {
		
		// position the caption properly
		function captions() {
			var show 	=	$('.slideshow.with_caption'),
				slides 	= 	show.children(),
				img 	= 	slides.find('img'),
				caps	=	slides.find('.caption');
				
				$.each(caps, function(i, item) {
					item = $(item);
					$(item).css({
						'position':'absolute',
						'top': $(item).prev('img').attr('height'),
						'width' : $(item).prev('img').attr('width')-10,
						'padding': '5px'
					});
					
				});

		};
		captions();
		
		$('.slideshow.with_caption').cycle({ 
		    fx:     'fade', 
		    speed: 	4000,
		    timeout: 2000,
			before: function() {$('ul.thumbs li.active').find('a').fadeTo(600,0.3)},
			after: function() {$('ul.thumbs li.active').find('a').fadeTo(150,1)},
			pause: 1,
			pauseOnPagerHover: 1,
		    pager:  'ul.thumbs',
		    pagerAnchorBuilder: function(idx, slide) { 
		        // return selector string for existing anchor
		        return 'ul.thumbs li:eq(' + idx + ') a';
		    } 
		});
	}
		
	} // close .slideshow check statement
	// set first on load to full transparency.
	$('ul.thumbs li.active a').fadeTo(0, 1);
// ===========================
// = RE RUN SELECTOR SCRIPTS =
// ===========================
	$('.image,.rounded,li,article').firstnlast();

	fnl(); // first n last

}); // end dom.ready