/* 
 * site.js
 * -----
 * @requires jQuery
 */
if (document.documentElement) {
  document.documentElement.className = 'js';
}

jQuery.noConflict();
jQuery(function($) {

  var main_nav = $('#nav');
  if (main_nav.length) {
    var nav_hover = main_nav.children();
    var timeout;
    nav_hover.hover(function() {
      var el = $(this);
      timeout = setTimeout(function() { el.addClass("over"); }, 200);
    },
    function() {
      clearTimeout(timeout);
      $(this).removeClass("over");
    });
  }
  
  
  /* Misc function to handle tabs */
  if ($('.tabbed-menu').length > 0) {
    $('.tabbed-menu a').click(function() {
      $(this).parents('.tabbed-menu:first').find('li').removeClass('active');
      $(this).parent().addClass('active');
      $('#'+$(this).attr('id')+'-content').siblings('.tabbed-content').hide();
      $('#'+$(this).attr('id')+'-content').show();
      return false;
    });
    $('.tabbed-menu').each(function() {
      $(this).find('a:first').trigger('click');
    });
  }
  $('#search_mini_form').submit(function() {
    var search_type = $(this).find('select').val();
    if (search_type == 'store') {
      $(this).attr('action','/catalogsearch/result/');
    }
    else {
      var query = $(this).find('input').val();
      $(this).find('input').attr('name','q2');
      if (search_type == 'pregnancy') {
        $(this).attr('action','/search/node/'+query+' type:advice,forum,activities');
      }
      else if (search_type == 'help') {
        $(this).attr('action','/search/node/'+query+' type:page');
      }
    }
  });
  /* Home Page */
  if ($('body').hasClass('cms-home')) {
    if ($('#slideshow_container').length > 0) {
      $('#slideshow_container').Switchy({
        display: '#display',	// holds initial image
        store: '#store',		// holds all other images
        thumbs: '#thumbs',		// holds thumbnails
        fadeSpeed: 'fast',		// fading speed
        eventType: 'click',		// event type to use
        delay: 8000,			// interval time in ms
		reset: 5000,			// interval pause timeout,
		thumbClass: 'active'
      });
      $('#thumbs').css('position', '');
    }
    $('#essential-products .widget').hide();
    $('select#essential-select').change(function() {
      $('#essential-products .widget').hide();
      var cat_class = $(this).val();
      $('#essential-products .'+cat_class).show();
      $('#view-essentials-more a').attr('href',$('#essential-products .'+cat_class+'-link').html());
    }).trigger('change');
    
    $('#slideshow_next').click(function() {
      if (!$(this).hasClass('no-more-next')) {
        var id = $('#display div:first').attr('id').replace('id_', '');
        var next_thumb = $('#'+id).parent().next().find('a');
        next_thumb.trigger('click');
        if (next_thumb.parent().next().find('a').length == 0) {
	      $(this).addClass('no-more-next');
         }
        $('#slideshow_prev').removeClass('no-more-prev');
      }
      return false;
    });
    $('#slideshow_prev').click(function() {
    	if (!$(this).hasClass('no-more-prev')) {
    		var id = $('#display div:first').attr('id').replace('id_', '');
    		var prev_thumb = $('#'+id).parent().prev().find('a');
    		prev_thumb.trigger('click');
    		if (prev_thumb.parent().next().find('a').length == 0) {
    			$(this).addClass('no-more-prev');
    		}
    		$('#slideshow_next').removeClass('no-more-next');
    	}
    	return false;
    });
    
    var product_slider = $(".widget-new-products div.widget-products")
    product_slider.jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        visible: 4,
        scroll: 4,
        speed: 800,
        circular: false
    });
  }
  /* Cart Page */
  else if ($('body').hasClass('checkout-cart-index')) {
    
    var whatisthis = $('#what-is-this');
    
    whatisthis.fancybox({
      autoDimensions: false,
      width: 700,
      height: 500
    });
      
    
    
    $('.btn-update').hide();
    $('#shopping-cart-table input.qty').each(function() {
      $(this).before('<a href="#" class="cart-minus-action">-</a><a href="#" class="cart-plus-action">+</a>');
    });
    $('.cart-minus-action').click(function() {
      var qty = $(this).siblings('input').val();
      qty = qty < 1 ? 0 : (qty-1);
      $(this).siblings('input').val(qty);
      $('.btn-update').trigger('click');
      return false;
    });
    $('.cart-plus-action').click(function() {
      var qty = $(this).siblings('input').val();
      $(this).siblings('input').val((parseInt(qty)+1));
      $('.btn-update').trigger('click');
      return false;
    });
    $('#ob-shipping-zip-form .button').hide();
    $('#ob-shipping-zip-form select').change(function() {
      $('#ob-shipping-zip-form .button').trigger('click');
    });
    $('.giftwrap-option').change(function() {
      if ($(this).attr('checked') == true) {
        $(this).siblings('.form-list').show();  
      }
      else {
        if ($(this).hasClass('giftwrap-processed')) {
          $(this).parent().find('.btn-save-gift').trigger('click');
        }
    	$(this).siblings('.form-list').hide();
      }
    }).trigger('change').addClass('giftwrap-processed');
    
    if ($('.giftmessage-area').length > 0) {
      $('.giftmessage-area').each(function() {
    	$(this).NobleCount('#'+$(this).parent().find('.characters-remaining').attr('id'),{
	      max_chars: 200,
	      on_negative: 'go_red',
	      on_positive: 'go_green',
	      block_negative: true
	    });
      });
    }
    if ($('#estimate_method').length > 0) {
    	$('#update-total').hide();
    	$('#estimate_method').change(function() {
          $('#update-total button').trigger('click');
    	});
    }
  }
  /* Checkout page */
  else if ($('body').hasClass('checkout-onepage-index')) {
    
    var details_checkout_form = $('#co-shipping-form');
    var billing_as_shipping = details_checkout_form.find('.form-list > li.control input');
    var details_checkout_form_inputs = details_checkout_form.find('.input-box input');
    billing_as_shipping.bind('click', function(){
      var el = $(this);

      if (!el.is(':checked')) {
        details_checkout_form_inputs.val('');
      }
    });
    
    $('select[name=shipping[country_id]]').change(function() {
      if ($(this).val() == 'GB') {
        $('#shipping-new-address-form select[name=shipping[method]]').show();
      }
      else {
        $('#shipping-new-address-form select[name=shipping[method]]').hide();
      }
    }).trigger('change');
    $('#shipping-address-select').change(function() {
      $('select[name=shipping[method]]').attr('disabled', false);
      $('#shipping-new-address-form select[name=shipping[method]]').attr('disabled', true);
      if ($('#address-country-id-'+$(this).val()).val() == 'GB') {
        $('select[name=shipping[method]]').show();
      }
      else if ($(this).val() == '') { // New address
    	  $('select[name=shipping[method]]').attr('disabled', true).hide();
    	  $('#shipping-new-address-form select[name=shipping[method]]').attr('disabled', false);
    	  $('#shipping-new-address-form select[name=shipping[country_id]]').trigger('change');
      }
      else {
        $('select[name=shipping[method]]').hide();
      }
    }).trigger('change');
    $('#checkout-register-button').click(function() {
      $('#baby-registration').hide();
      if ($('.checkout-register').attr('checked')) {
        $('#baby-registration').show();
      }
    });
    var babies = 1;
    $('#add-another-baby').click(function() {
      babies = babies + 1;
      var newfields = $('.register-baby-fields:first').clone();
      newfields.html(newfields.html().replace(/register-baby-0/g,'register-baby-'+babies));
      newfields.html(newfields.html().replace(/register-baby\[0\]/g,'register-baby['+babies+']'));
      $('.register-baby-fields:last').after(newfields);
      return false;
    });
    if ($('#tradeterms').length > 0) {
      document.getElementById('checkout-button').onclick = function() {
	    if ($('#tradeterms:checked').val() == null) {
	      alert("You must agree to the Tippitoes terms and conditions by checking the box");
	      return false;
	    }
	    else {
          review.save();
	    }
      };
    }
  }
  /* Product Page */
  else if ($('body').hasClass('catalog-product-view')) {
    var page = getParameterByName('p');
    
    var hash = window.location.hash;

    // The larger image is swapped for the smaller image elsewhere on window.onload,
    // so hide the #image until window.onload fires, then fade it in
    $(window).load(function() {
      $('#image').css('display', 'none').addClass('reveal').fadeIn();
    });
    
    
    //$('.view-bundle-details').fancybox();
    $('.review-tab').click(function() {
      $('#product-tab-2').trigger('click');
      var element = $('#product-tab-2');
      $('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'slow', easing: 'swing'});
      return false;
    });
    
    if (hash.length > 0 && (hash == '#product-tab-2' || hash == '#review-form')) {
      $('.review-tab').trigger('click');
    }

    if (page != '') {
      $('#product-tab-2').trigger('click');
      var element = $('#product-tab-2');
      $('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'slow', easing: 'swing'});
    }
  }
  /* Competition Entry */
  else if ($('#block-views-competitions-block_1').length > 0 || $('#competition-entry-button').length > 0) {
    $("a#enter-inline").fancybox({
      autoDimensions: false,
      centerOnScroll: true,
      width: 700,
      height: 540,
      onClosed: function() {
        // On close empty the fields
        $('#competition-entry-form').find('input.form-text, textarea').val('').html('');
      }
    });
  }
  if ($('#edit-submitted-region').length > 0) {
    $('#edit-submitted-region').change(function() {
      if ($("#edit-submitted-region option:last").attr('selected') ==  true) {
    	$('#webform-component-country input').val('');
        $('#webform-component-country').show();
      }
      else {
        $('#webform-component-country').hide();
        $('#webform-component-country input').val('UK');
      }
    }).trigger('change');  
  }

});

function getParameterByName(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
