/* Fashion Photography Exposed JavaScript */

$(document).ready(function(){

	/* default form values to their titles if nothing is set and make grey */
	$('form').find(':input').each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase();
		if (type == 'text' || type == 'password' || tag == 'textarea'){
			if($(this).val() == '' || $(this).val() == $(this).attr('title')){
				$(this).val($(this).attr('title'));
				$(this).css('color', '#7f7f7f');
			}
		}
	});

	/* clear input values on form submit if user has not entered anything */
	$('form').submit(function() {
		$(this).find(':input').each(function() {
			if($(this).val() == $(this).attr('title')){
				$(this).val('');
			};
		});
	});

	/* Form Input defaults */
	$('form input, form textarea').focus(function(){
		if($(this).val() == $(this).attr('title') || $(this).val() == ''){
			$(this).val('');
			$(this).css('color', '#000000');
		}
	});
	$('form input, form textarea').blur(function(){
		if($(this).val() == ''){
			$(this).css('color', '#7f7f7f');
			$(this).val($(this).attr('title'));

		}
	});
    
  /* submit buttons */
  $('.submit').click(function(event){
    event.preventDefault();
    $(this).parents('form:first').submit();
  });

  /* shipping info buttons */
  $('#change_shipping').click(function(event){
    event.preventDefault();
    showShipping();
  });
  $('#use_billing').click(function(event){
    event.preventDefault();
    hideShipping();
  });

  /* billing to shipping */
  $('#billing_fields input').keyup(function(){
    copyAddress();
  });
  $('#billing_fields select').change(function(){
    copyAddress();
  });

  /* delivery radio buttons */
  $('#shipping_options input').change(function(){
    var cost = $(this).next().children('div').html();
    calcTotal(cost);
  });

  /* payment method radio buttons */
  $('#payment_options input').change(function(){
    showHideCardDetailsForm();
  });
  
  //only run this on the "homepage"
  if($('#homepage').length > 0){
    $("a.video").fancybox({
      'overlayShow'	: false,
      'transitionIn'	: 'elastic',
      'transitionOut'	: 'elastic',
      'width' : 1024,
      'height' : 576
    });
  }
  
  
  //only run this on the "cart / billing delivery" page
  if($('#cart_billing_delivery').length > 0){
    
    $('#order_billing_state').change(function(){
      $("#order_billing_state option[value='']").remove();
      $('#order_billing_stateText').css('color', '#000000');
    });
    
    $('#order_shipping_state').change(function(){
      $("#order_shipping_state option[value='']").remove();
      $('#order_shipping_stateText').css('color', '#000000');
    });
    
    $("#order_billing_country").change(buildStateSelect);
    $("#order_shipping_country").change(function() {buildStateSelect('shipping')});   
    
    buildStateSelect();
    buildStateSelect('shipping');
    
  }
  
  //only run this on the "payment summary" page
  if($('#summary_payment_method').length > 0){
    calcTotal();
    showHideCardDetailsForm();
    var cost = $('#shipping_options input:first').next().children('div').html();
    calcTotal(cost);
  }


});

$(window).load(function() {
  
  //only run this on the "homepage"
  if($('#homepage').length > 0){
  
    //get content container positions
    overview_top = ($('#overview').offset().top);
    the_process_top = ($('#the-process').offset().top);
    the_topics_top = ($('#the-topics').offset().top);
    ordering_top = ($('#ordering').offset().top);  

    //main menu fixed position on scroll
    $(window).scroll(function () {
      moveMenu();
    });

    //anchor smooth scrolling
    function filterPath(string) {
      return string.replace(/^\//,'').replace(/(index|default).[a-zA-Z]{3,4}$/,'').replace(/\/$/,'');
    }
    var locationPath = filterPath(location.pathname);
    $('a[href*=#]').each(function() {
      var thisPath = filterPath(this.pathname) || locationPath;
      if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'')) {
        var $target = $(this.hash), target = this.hash;
        if (target) {
          $(this).click(function(event) {
            event.preventDefault();
            var targetOffset = $target.offset().top;
            $('html, body').animate({scrollTop: targetOffset}, 2000, 'easeInOutSine', function() {
              location.hash = target;
            });
          });
        }
      }
    });

    //put menu in the right place
    moveMenu();   
            
    //start the carousels
    initCarousels();

    //topics blinds
    $('.blind a').click(function(event){
      event.preventDefault();
      $(this).toggleClass('closed');
      $(this).next('.blindContent').slideToggle(700, 'easeInOutSine', function(){
        ordering_top = ($('#ordering').offset().top);
      });
    });
   
  }

});

function moveMenu(){
  var scroll_top = $(document).scrollTop();  
  if(scroll_top >= 600){
    $('#main_menu').css('position', 'fixed');
    $('#main_menu').css('top', '0px');
    $('#lead').css('margin-bottom', '92px');
  } else {
    $('#main_menu').css('position', '');
    $('#main_menu').css('top', '');
    $('#lead').css('margin-bottom', '');
  }

  if(scroll_top < 600){
    resetMenu();
  }

  scroll_top = scroll_top+1;
  if(scroll_top > overview_top){resetMenu();$('#main_menu ul li:nth-child(1) a').addClass('selected');}
  if(scroll_top > the_process_top){resetMenu();$('#main_menu ul li:nth-child(2) a').addClass('selected');}
  if(scroll_top > the_topics_top){resetMenu();$('#main_menu ul li:nth-child(3) a').addClass('selected');}
  if(scroll_top > ordering_top){resetMenu();$('#main_menu ul li:nth-child(4) a').addClass('selected');}
}

function resetMenu(){
  $('#main_menu a').removeClass('selected');
}

function initCarousels(){
  $('#carousel_left #slides').cycle({
    fx: 'scrollVert',
    speed: 1000,
    timeout: 0,
    next: '#carousel_left .next',
    prev: '#carousel_left .prev'
  });
  
  $('#carousel_right #slides').cycle({
    fx: 'scrollVert',
    speed: 1000,
    timeout: 0,
    next: '#carousel_right .next',
    prev: '#carousel_right .prev'
  });
}

function showShipping(){
  $('#shipping_box').hide();
  $('#shipping_fields').show();
  $('#order_shipping_same_as_billing').attr('value', '0');
}

function hideShipping(){
  $('#shipping_fields').hide();
  $('#shipping_box').show();
  $('#order_shipping_same_as_billing').attr('value', '1');
  copyAddress();
}

function checkShipping(){
  if($('#order_shipping_same_as_billing').attr('value') == 1){
    hideShipping();
  } else {
    showShipping();
  }
}

function copyAddress(){
  var company = $('#order_billing_company').attr('value');
  if(company!=$('#order_billing_company').attr('title')){$('#plain_company').html('<p>' + company + '</p>');}  
  
  var first = $('#order_billing_first_name').attr('value');
  var middle = $('#order_billing_middle_name').attr('value');
  var last = $('#order_billing_last_name').attr('value');
  if(first==$('#order_billing_first_name').attr('title')){first = '';}
  if(middle==$('#order_billing_middle_name').attr('title')){middle = '';}
  if(last==$('#order_billing_last_name').attr('title')){last = '';}
  $('#plain_name').html('<p>' + first + ' ' + middle + ' ' + last + '</p>');
  
  var address1 = $('#order_billing_address1').attr('value');
  var address2 = $('#order_billing_address2').attr('value');
  var city = $('#order_billing_city').attr('value');
  var state = $('#order_billing_state').attr('value');
  var zip = $('#order_billing_zip').attr('value');
  var country = $('#order_billing_country option:selected').text() + ' (' + $('#order_billing_country').val() + ')';
  
  var address = '';
  if(address1 != $('#order_billing_address1').attr('title')){address += '<p>' + address1 + '</p>';}
  if(address2 != $('#order_billing_address2').attr('title')){address += '<p>' + address2 + '</p>';}
  if(city != $('#order_billing_city').attr('title')){address += '<p>' + city + '</p>';}
  if(state != $('#order_billing_state').attr('title')){address += '<p>' + state + '</p>';}
  if(zip != $('#order_billing_zip').attr('title')){address += '<p>' + zip + '</p>';}
  if(country != $('#order_billing_country').attr('title')){address += '<p>' + country + '</p>';}
  
  $('#plain_address').html(address);  
  
}

function showHideCardDetailsForm(){
  if($('#payment_options input:checked').attr('value') == 'express'){
    $('#card_details_form').hide();
    $('#paypal_instructions').show();
  } else {
    $('#card_details_form').show();
    $('#paypal_instructions').hide();
  }
}

function calcTotal(shippingCost){
  if(shippingCost){
    $('#subtotal_shipping').html('$' + shippingCost);
  }
  
  var subtotal = parseFloat($('#subtotal').html().replace('$', ''));
  var shippingCost1 = parseFloat($('#subtotal_shipping').html().replace('$', ''));
  
  var ny_tax_perc = parseFloat($('#ny_tax_perc').html());
  var tax_total = (((subtotal+shippingCost1)/100)*ny_tax_perc).toFixed(2);
  $('#subtotal_tax').html('$' + tax_total);
  
  var tax = parseFloat($('#subtotal_tax').html().replace('$', ''));
  
  var total = (subtotal+shippingCost1+tax).toFixed(2);
  
  $('#grand_total').html('$' + total);  
}

function buildStateSelect(type) {
		
		if (type == "shipping") {
			var stateCodeNode = $("#order_shipping_state");
			var zipCodeNode = $("#order_shipping_zip");
			var countryCodeNode = $("#order_shipping_country");
      var selectText = $('#order_shipping_stateText');
		} else {
			var stateCodeNode = $("#order_billing_state");
			var zipCodeNode = $("#order_billing_zip");
			var countryCodeNode = $("#order_billing_country");
      var selectText = $('#order_billing_stateText');
		}
		var htmlStateOptions = "<option value=\"\">Choose...</option>";
		var countryCode = countryCodeNode.val();
		
		if (countryCode == "" || !countryCode || COUNTRIES[countryCode] == undefined || COUNTRIES[countryCode]['states'] == undefined) {
			
			stateCodeNode.attr('disabled', 'disabled');
			stateCodeNode.html(htmlStateOptions);
	    //stateCodeNode.val("");
			
			return;
		}
		
		currentCountryHasStates = false;
		
		$.each(COUNTRIES[countryCode]['states'], function(stateCode, state) {
			htmlStateOptions += "<option value=\"" + stateCode + "\">" + state["name"] + "</option>";
			currentCountryHasStates = true;
		});

		stateCodeNode.html(htmlStateOptions);
		
		if (currentCountryHasStates == false) {
      selectText.html('Choose...');
      selectText.css('color', '#BFBFBF');
      stateCodeNode.val("");
			stateCodeNode.attr('disabled', 'disabled');
			return;
		} else {
      selectText.html('Choose...');
			stateCodeNode.removeAttr('disabled');
      selectText.css('color', '#7F7F7F');
			stateCodeNode.show();
		}
		
	}
