// Globally Accessed Variables -------------------------
var slidePosition = 1;
var t;
var eventSlidePosition = 1;
var defaultFormValues = new Array();



// On Load ---------------------------------------------

$(document).ready(function() {
	searchFocus();
	mailingListFocus();
	navigationInit();
	designerMenuInit();
	productsInit();
	billMethodInit();
	$('.imagefit').scaleImage({ scale: 'fit' });
	$('.imagefill').scaleImage({ scale: 'fill' });
	$('#navloginform').submit(function(e){
		e.preventDefault();
		storeLogin();
	});
});

function productsInit() {
	if($('.products').length > 0){
		var maxHeight = 0;
		$(".products ul .box").each(function(){
			if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
		});
		$(".products ul .box").height(maxHeight);

	
		if($('.products .image .alternate').length > 0){
			$('.products .image .alternate').each(function(){
				$(this).parent().mouseenter(function(){
					$(this).children('.primary').fadeOut(250);
					$(this).children('.alternate').fadeIn(250);
				});
				$(this).parent().mouseleave(function(){
					$(this).children('.alternate').fadeOut(250);
					$(this).children('.primary').fadeIn(250);
				});
			});
		}
	}
}

function navigationInit() {
	if($('#header .navigation').length > 0){
		
		$('#header .navigation').css({marginLeft: ( ( $('#header .wrapper').width() - $('#header .navigation').width() ) / 2 ) });
		
		if($('.menu-subcategory').parent().length > 0){
			$('.menu-subcategory').parent().mouseenter(function() {
				var subcategory=$(this).children('.menu-subcategory');
				var rel=$(this).attr('rel');
				
				if (rel) {
					$.ajax({
						type: "GET",
						url: "/store/includes/subcategories.php",
						data: ({id : rel}),
						dataType: "html",
						success: function(data) {
							$(subcategory).html(data);
						}
					});
				}
			
				$(subcategory).slideDown(100);
			});
			$('.menu-subcategory').parent().mouseleave(function() {
				$(this).children('.menu-subcategory').slideUp(100);
			});
		}
	}
}

function changeDesigner(designer) {
	$.ajax({
		type: "GET",
		url: "/store/includes/designer-box.php",
		data: ({designer : designer}),
		dataType: "html",
		success: function(data) {
			$('#designer-box').html(data);
			$('#designer-box').show();
		}
	});
}

function designerMenuInit() {
	if($('ul.designermenu').length > 0) {
		changeDesigner($('ul.designermenu li:first a').attr('rel'));
		$('ul.designermenu a').each(function(){
			var designer = $(this).attr('rel');
			$(this).mouseenter( function(){ changeDesigner(designer); });
		});
	}
}

function checkGiftCardBalance() {
	$.ajax({
		type: "POST",
		url: "/store/includes/gift-card-balance.php",
		data: ({code : $('#card-code').val()}),
		dataType: "html",
		success: function(data) {
			$('#card-balance-ajax').html(data);
		}
	});
}

function addToCart() {
	$('#login').slideUp(250);
	$('#cart').slideDown(250);
	$('#cart .loading').show(250);
	$.ajax({
		type: "POST",
		url: "/cgi-bin/commerce.cgi",
		data: $("#cartform").serialize(),
		dataType: "html",
		cache: false,
		success: function(data) {
			$.ajax({
				type: "GET",
				url: "/store/templates/cart.tpl.php",
				data: ({ajax : '1'}),
				dataType: "html",
				cache: false,
				success: function(data) {
					$('#cart .contents').html(data);
					$('#cart .loading').fadeOut(250);
					var t = setTimeout(function() { $('#cart').slideUp(250); }, 2000);
				}
			});
		}
	});
}

function storeLogin() {
	$.ajax({
		type: "POST",
		url: "/cgi-bin/commerce.cgi",
		data: $("#navloginform").serialize(),
		dataType: "html",
		success: function(data) {
			var matches = data.match(/<title>(.*?)<\/title>/);
      		var urlTitle = matches[1];
      		
			if (urlTitle=="You Are Now Logged In") {
				var nameMatches = data.match(/<h3>(.*?)<\/h3>/);
      			if (nameMatches===null) var greeting = "";
      			else var greeting = nameMatches[1];
      			
				$('#navloginmessage').html(greeting);
				window.location.reload();
			}
			else if (urlTitle=="We're Sorry.  We Were Unable to Process Your Login Request") {
				$('#navloginmessage').html("Invalid username or password.");
			}
			else {
				$('#navloginmessage').html("There has been an error, please try logging in again.");
			}
			$('#navloginmessage').show();
		}
	});
}

function sameAsBilling() {
	/*if ($('#same-billing').is(':checked')) {
		$('#ship-name').val($('#bill-firstname').val()+" "+$('#bill-lastname').val());
		$('#ship-street1').val($('#bill-street1').val());
		$('#ship-street2').val($('#bill-street2').val());
		$('#ship-city').val($('#bill-city').val());
		$('#ship-province').val($('#ship-province').val());
		$('#ship-zip').val($('#bill-zip').val());
		$('#shipstate').val($('#billstate').val());
		$('#shipcountry').val($('#billcountry').val());
	}*/
	if ($('#shiptobilladdr').is(':checked')) {
		$('#shipfirstname').val($('#billfirstname').val());
		$('#shiplastname').val($('#billlastname').val());
		$('#shipstreet1').val($('#billstreet1').val());
		$('#shipstreet2').val($('#billstreet2').val());
		$('#shipcity').val($('#billcity').val());
		$('#shipprovince').val($('#shipprovince').val());
		$('#shipzip').val($('#billzip').val());
		$('#shipstate').val($('#billstate').val());
		$('#shipcountry').val($('#billcountry').val());
		$('#shipphone1').val($('#billphone1').val());
		$('#shipphone2').val($('#billphone2').val());
		$('#shiptext').val($('#billtext').val());
	}
}


function infoTab(tab,boxID) {
	$('#product-info .box').hide();
	$('#productinfo-'+boxID).show();
	$('#product-info .tabs li').removeClass('selected');
	$(tab).parent().addClass('selected');
}

function toggleLogin() {
	$('#cart').slideUp(250);
	$('#login').slideToggle(250);
}

function toggleCart() {
	$('#login').slideUp(250);
	$('#cart').slideToggle(250);
}

function searchFocus() {
	defaultFormValues['headerSearch'] = $('#headersearch').val();
	$('#headersearch').focus(function(){ if($(this).val()==defaultFormValues['headerSearch']) $(this).val(''); });
	$('#headersearch').blur(function(){ if($(this).val()=='') $(this).val(defaultFormValues['headerSearch']); })
}

function mailingListFocus() {
	defaultFormValues['headerEmail'] = $('#headeremail').val();
	$('#headeremail').focus(function(){ if($(this).val()==defaultFormValues['headerEmail']) $(this).val(''); });
	$('#headeremail').blur(function(){ if($(this).val()=='') $(this).val(defaultFormValues['headerEmail']); })
}

function altView(thumbID,imageURL) {
	$('#product-thumbs li').removeClass('selected');
	$('altview-'+thumbID).addClass('selected');
	$('#product-image .image').html('<a href="'+imageURL+'" class="cloud-zoom" rel="position: \'inside\'"><img src="'+imageURL+'" /></a>');
	$('#product-image .image img').load(function(){ 
		$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
	});
}

function featureSlideInit(effectDuration,rotateDuration) {
	t=setTimeout("featuredAutoRotate("+effectDuration+","+rotateDuration+")",rotateDuration);
	var slideCount = $("#featuredslides li").size();
}

function featuredAutoRotate(effectDuration,rotateDuration)
{
	featuredSlide('next',effectDuration);
	t=setTimeout("featuredAutoRotate("+effectDuration+","+rotateDuration+")",rotateDuration);
}

function featuredSlide(direction,effectDuration) {
	clearTimeout(t);
	var targetSlide = '#featureslide_';
	var currentSlide = '#featureslide_'+slidePosition;
	var slideCount = $("#featuredslides li").size();
	if (direction=='previous'){
		if(slidePosition==1) targetSlideID = slideCount;
		else targetSlideID = slidePosition - 1;
	} else if (direction=='next') {
		if(slidePosition==slideCount) targetSlideID = 1;
		else targetSlideID = slidePosition + 1;
	}
	slidePosition = targetSlideID;
	targetSlide = targetSlide + targetSlideID;
	$("#featuredslides li").hide();
	$(currentSlide).show();
	$(targetSlide).show();
	$(currentSlide).css({zIndex:800,display:'block'});
	$(targetSlide).css({zIndex:1,display:'block'});
	$(currentSlide).fadeOut(effectDuration);
}

function toCurrency(num) {
  var sign;
  var cents;
  var i;

  num = num.toString().replace(/\$|\,/g, '');
  if (isNaN(num)) {
    num = "0";
  }
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  cents = num % 100;
  num = Math.floor(num / 100).toString();
  if (cents < 10) {
    cents = '0' + cents;
  }

  for (i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
  }

  return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function imgError(source){
	source.src = "/images/noimage.png";
	source.onerror = "";
	return true;
}

function checkoutType() {
	if($('input[name="checkouttype"]:checked').val()=='register') {
		$('#input-normalcheckout').attr('name','');
		$('#input-checkout').attr('name','');
		$('#input-register').attr('name','register');
	} else {
		$('#input-normalcheckout').attr('name','normalcheckout');
		$('#input-checkout').attr('name','checkout');
		$('#input-register').attr('name','');
	}
}

function scrollPaneInit() {
	if($('.scroll-pane').length > 0){
		$('.scroll-pane').jScrollPane({
			horizontalGutter: 20,
			verticalGutter: 20
		});
	}
}

function billMethodInit() {
	$('#billmethod').change(function(){
		if ($(this).val()=="GC") {
			$('#pay-credit').slideUp(250);
			$('#pay-giftcard').slideDown(250);
		} else {
			$('#pay-giftcard').slideUp(250);
			$('#pay-credit').slideDown(250);
		}
	});
}

function checkDiscountCode() {
	if ($('#discount-code-value').val()=='') {
		alert("Please enter a discount code before submitting.");
		return false;
	}
	else return true;
}
