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

	// alert('document ready!');

	/*
	----- GENERAL --------------------
	*/
	
	/* aucoin small heart icon */
	$("a.aucoinHartIcon").mouseover(function() {
			$('.aucoinHartDesignsCustomized').show();
			$('.aucoinHartDesignsCustomized').stop().animate({
					bottom: "70px",
					opacity: 1,
					queue: false
				}, {
					duration : "slow", 
					easing : "easeOutQuint"
				});
	}).mouseout(function(){
		$('.aucoinHartDesignsCustomized').stop().animate({
				bottom: "80px",
				opacity: 0,
				queue: false
			}, {
				duration : "slow", 
				easing : "easeOutQuint",
				complete: function() {
					$('.aucoinHartDesignsCustomized').hide();
				}
			});
			
	});
	
	// to detect IE7 & 8 - A PLAGUE ON BOTH YOUR HOUSES!!!!!!!!!!
	function msieversion()
	{
	   var ua = window.navigator.userAgent
	   var msie = ua.indexOf ( "MSIE " )
	
	   if ( msie > 0 )      // If Internet Explorer, return version number
	      return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
	   else                 // If another browser, return 0
	      return 0
	}
	var msieVersion = msieversion();

	/*
	----- PRODUCT ARCHIVE --------------------
	*/
	
	$(window).bind( 'hashchange', function( event ){
	
	  displayProducts();
	  // alert('hashchange');
	  
	})
	
	function bbqChangeState() {
		var currentUrl = '#currentSection=' + currentSection + "&page=" + currentPage;		
		$.bbq.pushState(currentUrl);

	}
	
	// add $ ui dropdowns
	$('#product_dropdowns select').selectmenu({
		/* icons removed by request
		icons: [
			{find: '.shapes-rounds'},
			{find: '.shapes-fancy-shapes'}
		], */
		width: '190'
		
	});

	// Product Archive page vars
	var container = $('#product_container');
	var currentPage = 1;
	var currentSection = '.all';
	var productContainerWidth;
	var numberOfPages = 1;
	var firstRun = true;
	var maxNumberOfPages;
	
	var currentGroup = [];
	var currentGroupOffset = 0;
	var productGroup = [];
	var firstLoad = true;
	
	var $isProductPage = $('body').hasClass('page-template-template-page-product-php');
	
	container.isotope({
		// options
		itemSelector : currentSection,
		layoutMode : 'fitColumns',
		animationEngine : 'css'
	});
	
	function displayProducts() {
	
		var hashOptions = $.deparam.fragment();
		
		if (hashOptions['currentSection']) {
			var $sectionExists = $(hashOptions['currentSection']);
			var $jewelryPage = $('body.slug-all_jewelry');
			if (($sectionExists.length > 1) && $isProductPage) {
				currentSection = hashOptions['currentSection'];
				// alert('section exists ' + currentSection);
			} else if (navigator.userAgent.match(/Mobile/i) && ($jewelryPage.length > 1)) {
				currentSection = '.types_featured';
				currentPage = 1;
				// alert('section does not exist ' + currentSection);
				bbqChangeState();
			} else {
				// alert('all');
				currentSection = '.all';
				currentPage = 1;
				bbqChangeState();
			}
		}
		
		container.isotope({ filter: currentSection });
		
		var $numberOfProducts = $('#product_container div' + currentSection);
		// alert('numberOfProducts' + $numberOfProducts);
		numberOfPages = Math.ceil($numberOfProducts.length / 8);
		// alert('calc number of pages: ' + calculatedNumberOfPages)
		
		processPageHash(hashOptions['page'], numberOfPages);
		
		setContainer();
		
		loadBackgroundImages();
		
		animateProductContainer();
		
		updatePageNumber();
		
		
		// write out select dropdowns
		if (currentSection == '.all'){
			$('#product_utility select').each(function(){
				$(this).val('');
		  	});
			$('#product_utility select').selectmenu("value", '');
		} else {
			currentSelectName = '#product_utility select option' + currentSection;
			$currentSelect = $(currentSelectName).parent();
			
			// set current select to current value
			$currentSelect.val(currentSection);
			$($currentSelect).selectmenu("value", currentSection);
			
			// set siblings to blank value
			$($currentSelect).siblings('select').each(function(){
				$(this).val('');
		  	});
			$($currentSelect).siblings('select').selectmenu("value", '');
		}
		
		if (firstLoad == true) {
			$('.product_loading').hide();
			$('#product_utility').fadeTo('fast', 1);
			$('#product_container').fadeTo('fast', 1);
			firstLoad = false;
		}
		
	}
	if ($isProductPage) {
		// alert('is product onload');
		window.onload=displayProducts;
	}
	
	function processPageHash(pageNumber, theNumberOfPages){
		if (pageNumber){
			if ((0 < pageNumber) && (pageNumber <= theNumberOfPages)) {
				currentPage = pageNumber;
				// alert('page number is a valid.  current page is: ' + currentPage);
			} else if ((pageNumber > theNumberOfPages) && (theNumberOfPages > 0)) {
				currentPage = theNumberOfPages;
				// alert('page number is too large.  current page is: ' + currentPage + "numer of pages: " + theNumberOfPages);
				bbqChangeState();
			} else if ((pageNumber <= 0)) {
				currentPage = 1;
				// alert('too small.  current page is: ' + currentPage);
				bbqChangeState();
			}
		} else if (navigator.userAgent.match(/Mobile/i)) {
			// alert('mobile - ignore page num');
			currentPage = 1;
			currentSection = getQueryVariable('currentSection');	
			bbqChangeState();
		} else if (!pageNumber && $isProductPage) {
			// alert('!pageNumber and it is a product');
			currentSection = '.all';
			currentPage = 1;
			bbqChangeState();
		}
	}
	
	function setContainer() {
		currentGroupOffset = (currentPage - 1) * 8;
		currentContainerPosition = (currentPage - 1) * -980;
		// alert('setting container. groupOffset:' + currentGroupOffset + ' containerPosition:' + currentContainerPosition);
	}

	function loadBackgroundImages() {
		// alert('loading bg images');
		// get all elements
		$currentGroup = $(currentSection);
		
		productGroup = $currentGroup.slice(currentGroupOffset, (currentGroupOffset + 10));
		
		// load images for 8 products in product group
		$.each(productGroup, function() {
			var $product = $(this);
			
			var existingStyle = $product.attr("style");
			var productBackgroundUrl = $product.attr("data-style");
			var newStyle = existingStyle + 'background:' + productBackgroundUrl + ';';
			
			if ((0 < msieVersion) && (msieVersion < 9) && $product.attr("data-style")) {
				$product.css('background-image', productBackgroundUrl);
				$product.removeAttr('data-style');
			} else if ($product.attr("data-style")) {
				$product.attr("style", newStyle);
				$product.removeAttr('data-style');
			}
		});
	}
	
	function animateProductContainer() {
		if(navigator.userAgent.match(/Mobile/i)){
		 		$(container).css('left', currentContainerPosition);
		} else {
			// animate container
			$(container).stop().animate({
			    	left: currentContainerPosition
			    }, {
			    	duration : "slow", 
			    	easing : "easeInOutQuint"
			});
		}
		
	}
	
	function updatePageNumber() {
		var pageOutput = currentPage + ' of ' + numberOfPages;
		$('.page_number').text(pageOutput);
	}
	
	$("#product_dropdowns select").change(function(){
		  currentSection = $(this).attr('value');
		  currentDropdownName = $(this).attr('name');
		  currentPage = 1;
		  
		  if(navigator.userAgent.match(/Mobile/i)) {
		  		if (currentSection == '' && ((currentDropdownName == 'Type') || (currentDropdownName == 'Jewelry Designer') || (currentDropdownName == 'Price Range' ))) {
		  			currentSection = '.types_featured';
		  		} else if (currentSection == '') {
		  			currentSection = '.all'
		  		}
		  		var queryStringUrl = 'currentSection=' + currentSection;
		  		var currentUrl = 'currentSection=' + currentSection + "&page=" + currentPage;
		  		// alert(currentUrl);
				window.location.href = '?' + queryStringUrl + "#" + currentUrl;
				return;
				
			} else if (currentSection == '') {
		  		currentSection = '.all';
		  }
		  
		  bbqChangeState();
		  return false;
	});
	
	$('.next_page a').click(function(e){
		e.preventDefault();
		if (currentPage < numberOfPages) {
			currentPage++;
			bbqChangeState();
		}
	});
	
	$('.previous_page a').click(function(e){
		e.preventDefault();
		if (currentPage > 1) {
			currentPage--;
			bbqChangeState();
		}
	});
	
	
	$('#slides').slides({
				preload: true,
				preloadImage: '/wp-content/themes/aucoinhart/images/loading.gif',
				play: 7000,
				pause: 2500,
				slideSpeed: 700,
				hoverPause: true,
				effect: 'fade'
	});
	
	function getQueryVariable(variable) { 
  		var query = window.location.search.substring(1); 
  		var vars = query.split("&"); 
  		for (var i=0;i<vars.length;i++) { 
    		var pair = vars[i].split("="); 
    		if (pair[0] == variable) { 
      			return pair[1]; 
    		} 
  		}
	} 
	
	/*
	----- Fancybox --------------------
	*/
	
	var select = $('a[href$=".bmp"],a[href$=".gif"],a[href$=".jpg"],a[href$=".jpeg"],a[href$=".png"],a[href$=".BMP"],a[href$=".GIF"],a[href$=".JPG"],a[href$=".JPEG"],a[href$=".PNG"]');
		select.attr('rel', 'fancybox');
		select.fancybox();
	
	$("a.button_email").fancybox({
		'hideOnContentClick' : false
	});
	$("a#button_schedule_consultation").fancybox({
		'hideOnContentClick' : false
	});
	$("li.email_sign_up a").fancybox({
		'hideOnContentClick' : false
	});
	
	$('a[href*="player.vimeo.com"]').fancybox({
      type: 'iframe',
      width: 622, 
      height: 350,
      overlayShow: true,
      overlayOpacity: 0.7
    });
    
	/*
	----- Timeline jscrollpane --------------------
	*/
	
	var current_era;
	
	$('#era_beginnings').click(function(){
		current_era = '#era_beginnings';
		$(this).addClass('current_era');
		$('#era_story').removeClass('current_era');
		$('#era_new').removeClass('current_era');
	});
	$('#era_story').click(function(){
		current_era = '#era_story';
		$(this).addClass('current_era');
		$('#era_beginnings').removeClass('current_era');
		$('#era_new').removeClass('current_era');
	});
	$('#era_new').click(function(){
		current_era = '#era_new';
		$(this).addClass('current_era');
		$('#era_story').removeClass('current_era');
		$('#era_beginnings').removeClass('current_era');
	});
	
	function change_current_era(era) {
		if (era != current_era) {
			$(current_era).removeClass('current_era');
			current_era = era;
			$(current_era).addClass('current_era');
		}
	}

	$('.scroll-pane')
			.bind(
				'jsp-scroll-x',
				function(event, scrollPositionX, isAtLeft, isAtRight)
				{
					if (scrollPositionX < 3895) {
						var era = '#era_beginnings';
						change_current_era(era);
					} else if ((3896 < scrollPositionX) && (scrollPositionX < 10915)) {
						var era = '#era_story';
						change_current_era(era);
					} else if (10916 < scrollPositionX) {
						var era = '#era_new';
						change_current_era(era);
					}
					// 0 - beginning
					// 3896 - love story
					// 10916 - generation
				}
			)
	    .jScrollPane(
	    {
	    	hijackInternalLinks: true
	    }
	);



});
