

jQuery(function() {
  
    $('#mainimage-wrap').jqueryzoom({
			xzoom: 410, //zooming div default width (default width value is 200)
			yzoom: 367, //zooming div default height (default height value is 200)
			offset: 0, //zooming div default offset(default offset value is 10)
			position: "right", //zooming div position(default position value is "right")
			preload: 0, // by default preload of big images is 1
			lens: 1, // by default the lens is 1
			positionTop: 0,
			positionLeft: 220,
			hideElement: ".product-pane"
    });
  
  
    function handleAJAXTimeout(sender, e)
    {
        if (e.get_error() != undefined)
       {
           if (e.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException')
           {
                e.set_errorHandled(true);
                alert(ajaxTimeoutError);
           }
           else { }
       }
    }
    
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleAJAXTimeout);
    
  
  var payTypesRequiringExtraOptions = ['688c499e-63dd-4bdd-9ca1-ce8ace2097e8']; // Values of payment options that should show extra credit card fields 

  /* Payment page interaction */
  $('select.sv-card-type').each(function() {
    var showOrHideExtraFields = function() {
      if ( $.inArray( $('option:selected', this).val(), payTypesRequiringExtraOptions ) >= 0 ) { // Show the Start date and issue number fields
        $('#card-options').slideDown();
      } else {
        $('#card-options').slideUp();
      };
    };
    
    $(this).change(showOrHideExtraFields);

    showOrHideExtraFields(); // call for initial page load
  });
  
  if ($.browser.msie && $.browser.version < 7) {
	$("input[src$='.png']").not('.variants input').ifixpng(); 
  }
 

  $('a[href=#terms-and-conditions]').click(function() { 
      $('#terms-and-conditions').slideDown();
      return false;
  });
  
  $('.sv-carousel').each(function() { // requires jCarousel lite
    var visibleItems = $('#content').is('.landing') ? 5 : 4, // 4 items on homepage, 5 on landing pages
        allItems = $('li', this).length;
        additionalItems = (Math.ceil(allItems / visibleItems) * visibleItems) - allItems; // number of items to make up to a multiple of visible items
    
    if (allItems > visibleItems ) { // don't enable for less than 4 items
      var prevButton = $('<span/>').insertBefore(this)
                      .addClass('carousel-prev disabled');

    
      var nextButton = $('<span/>').insertAfter(this)
                      .addClass('carousel-next');

                      
      for (var i=0; i < additionalItems; i++) { // fixes jCarousel lite problem in non-circular mode
        $('ul', this).append('<li />');
      };

      $(this).jCarouselLite({
        visible: visibleItems,
        circular: false,
        btnNext: nextButton.get(),
        btnPrev: prevButton.get(),
        scroll: visibleItems
      });
    }
    
  });


  function pageLoadedHandler () {
    renderLinkButtons();
    disableCheckoutButton();
    $('input.specify-other').each(function() {
		showOrHideOtherTextfield(this);
	});
  
    $('.overlay:not(.sv-overlay)').each(function() { // handle page overlays
      var scrollY = document.body.scrollTop || document.documentElement.scrollTop, // get the vertical scroll position of browser document
          windowHeight = window.innerHeight || document.documentElement.clientHeight,
          overlayHeight = $(this).height();
      
      $(this).css({ // adjust vertical postion in case user has scrolled down
        top:  function() {
                var verticalDistance = ( windowHeight - overlayHeight ) / 3  + scrollY;
                return  (verticalDistance > scrollY) ? verticalDistance : scrollY;
              }
      }).fadeIn('fast', function() {
        if ( $(this).is('.transient') ) { // setup transient overlays to clear automatically
          var tOverlay = $(this);
          setTimeout(function() {
            tOverlay.fadeOut('fast', function() {
				$('input.close', this).click();
            });
          }, 5000);
        };
      });
      
      if ($.browser.msie && $.browser.version < 7) {
		    $(this).bgiframe();
      }
    });
    
    $('span.error').siblings('input.textfield, select').addClass('error'); // 
    
    $('input[id$=ExistingUserRadioButton]').each(function() {   // detect the login page, add focus behaviour
      manageFocusOnLoginPage(this);
    });
    
    $('.star-rating.interactive').each(function() {
      new StarRating(this, $(this).siblings().filter('select'));
    });
    
    insertProductVideoPlayer(); 
  };
  
  $('#slideshow').slideshow(); // requires SV.slideshow 
  
  disableCheckoutButton();  // disables checkout button when basket empty
  
  Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
  
  $('#primary-nav li').hover(function() {   // primary nav dropdown
    $(this).addClass('hover');
    $('ul', this).show();
  }, function() {
    $(this).removeClass('hover');
    $('ul', this).hide();
  });
  

  $('.change-view').click(function() {   // handle product list grid view toggle
    $('ul.product-list').each(function() {
      $(this).toggleClass('grid');
      $('.change-view a').toggleClass('enabled'); // swap view buttons
    });
    return true;
  });


  $('input[id$=ExistingUserRadioButton]').each(function() {   // detect the login page
    manageFocusOnLoginPage(this);
  });

  $('a.sv-print').click(function() { 
    print(); 
    return false;
  });
  
  $('input.specify-other').each(function() {
    showOrHideOtherTextfield(this);
  });
  
  $('.info a[href=#reviews]').click(simulateReviewsTabClick);
  $('.info a[href=#specifications]').click(simulateSpecTabClick);
  
  $('body').keypress(function(e) {
    if (e.keyCode == 27) {  // Escape key pressed
      var overlay =  $('.overlay').eq(0);
      overlay.hide();
      closeOverlay(overlay);
    };
  });

	// Handle showing/hiding the 'Add Address' button on the VAT Exemption page
	$('#content.vat-exemption').each(function() {
		showOrHideAddAddress(this);
	});
	
	// Client side overlay support for VAT exemption page
	window.SV = window.SV || {};
	window.SV.overlays = window.SV.overlays || {}; // Global Ojbect to store overly references
	
	$('.sv-overlay').each(function() {
		var overlay = new Overlay(this); 
		window.SV.overlays[overlay.name()] = overlay; // Store reference to overlay indexed by name
	});
	
	$('a.sv-overlay-trigger').live("click", function() {
		var hrefSegments = $(this).attr('href').split('#');
		var targetOverlayName = hrefSegments[hrefSegments.length -1]; // IE6 somtimes returns an absolute URL, so ensure we just get the fragment ID
		if (window.SV.overlays[targetOverlayName]) {
			window.SV.overlays[targetOverlayName].open();
		}		
		return false;
	});
	
  $('p.zoom a').click( function() { showLargeImage(); return false; } );
  
  
  $('#preferred-greeting').each(function() { // update preferred greetings from user input
    var dropdown = $('select', this); 
    var updatePreferredGreetings = function() {
      var firstName = $('input[id$=FirstName]').val() || 'Firstname';
      var lastName  = $('input[id$=LastName]').val() || 'Lastname';
      var initial   = $('input[id$=FirstName]').val().length > 0 ? firstName.substring(0, 1) : 'Initial';
      var title     = "";

      if ( $('select[id$=Title] option:selected').val() == 'other') {
        title = $('input[id$=OtherTitleTextBox]').val();
      } else {
        title = $('select[id$=Title] option:selected').text();
      }
      
      $('option', dropdown).eq(0).text( '' + title + ' ' + lastName);
      $('option', dropdown).eq(1).text( '' + firstName);
    };
    

    $('input[id$=FirstName], input[id$=LastName], input[id$=OtherTitleTextBox]').keyup(updatePreferredGreetings);
    $('select[id$=Title]').change(updatePreferredGreetings);
    
  });

  /* Specification show/hide for product page */
  $('#specifications').each(function() {
    if ( $('.spec-container', this).length <= 1) {
      return false; // 
    };

    var specDiv = $(this);
    var subNav = $('<ul />').addClass('.subnav').appendTo(this);
    
    $('<h3/>').text('More specifications')
              .addClass('more')
              .insertBefore(subNav);


    $('.spec-container', this).each(function(index) {
      var specContainer = $(this);
      var specTable = $('table', this);
      var specHeading = $('h3', this);
      
      specContainer.hide();
      
      $('<a/>').text( specHeading.text() )  // create subnav
               .attr('href', '#show-'+index)
               .appendTo(subNav)
               .wrap('<li/>')
               .click(function(e) {
                  $('.spec-container:visible', specDiv).slideUp('normal', function() {
                    specContainer.slideDown();
                  });
                    
                  $(this).parent().hide()
                         .siblings().show();                  

                 return false;
               });

    });
    
    $('.spec-container', specDiv).eq(0).show();
    $('li:first', subNav).hide();
  });
  
  
  
  $('.images ul img').each(function() { // image chooser for product page
    $(this).click(function() {
      $('#mainimage').attr({'src': this.src.replace(/_st.jpg/i, '_p.jpg'),
                            'alt': this.alt});
      if ( $(this).hasClass('zoom-enabled') ) {
        $('.zoom-instructions').css('visibility', 'visible');
      } else {
        $('.zoom-instructions').css('visibility', 'hidden');
      }
    });
  });
  
  if ($('#mainimage').length > 0) {
    var mainImageThumbnailSrc = $('#mainimage').attr('src').replace(/_p.jpg/i, '_st.jpg');  
    if ( $('img[src$='+mainImageThumbnailSrc+']').hasClass('zoom-enabled') === false ) {
      $('.zoom-instructions').css('visibility', 'hidden');
    };
    
  };
  

  $('#large-image-container').each(function() { // Image choose for enlarged view on product page
    var largeImage = $('#large-image', this);
    var imageHeading = $('h2', this);

    $('ul a', this).click(function(e) {
      e.stopPropagation();
      var largeImageToShow = $(this).attr('href');
      $(largeImage).attr('src', largeImageToShow);
      imageHeading.text( $('img', this).attr('alt') );
      return false;
    });
  });
  
  


});

function showLargeImage() {
    document.getElementById('large-image-container').style.display = 'block';
    document.getElementById('large-image').src = document.getElementById('mainimage').src.replace("_p", "_l");
    $('h2', '#large-image-container').text( $('#mainimage').attr('alt') );
}


function manageFocusOnLoginPage(existingUserRadioButton) {
  var userNameField                       = $('input.textfield[id$=UserName]');
  var passwordField                       = $('input.textfield[id$=Password]').get();
  var newUserRadioButton                  = $('input[id$=NewUserRadioButton]').get();
  var emailOptIn                          = $('#checkout-login p.checkbox');
  
  $(existingUserRadioButton).bind('change focus', function() { // user chooses to supply a password
    $(passwordField).focus();
    emailOptIn.slideUp();
  }); 
  
  $(newUserRadioButton).bind('change focus', function() { // user wants to create an account
    userNameField.focus().select();
    emailOptIn.slideDown();
  }); 

  
  $(passwordField).bind('click keypress focus', function() { // user enters a password
    $(existingUserRadioButton).attr('checked', 'checked');
    emailOptIn.slideUp();
  });
  
  $(userNameField).bind('click keypress focus', function() {
    $(newUserRadioButton).attr('checked', 'checked');
    emailOptIn.slideDown();
  });

  // Initial state on page load
  if ( userNameField.val() ) { // the user is recognised
    emailOptIn.hide();
    $(passwordField).focus();
  } else {
    userNameField.focus();
  };
};



function showOrHideOtherTextfield (textfield) { // show or hide the textfield for the 'Other' option in  dropdown menus
  var dropdown = $('select', $(textfield).parent()).get(0);
  
  if (!dropdown) { // exit if can't find a sibling dropdown to trigger the textfield
    return false;
  };
  
  function showOrHideTextfield () {
    if ( $('option:selected', dropdown).val() == 'other' ) {
      $(textfield).show();
    } else {
      $(textfield).hide();
    }
  }
  
  $(dropdown).change(showOrHideTextfield);

  showOrHideTextfield(); // set correctly for initial page load

}

function disableCheckoutButton() {  // disables the view & checkout button when basket is empty
$("#header .basket a.disabled")
  .css("opacity", .65)
  .click(function() { return false; });  
}

function renderLinkButtons() {  // turn buttons with class "link-button" into a text link
  $(".link-button").each(function() {
    var btn = this;
    $(this).removeClass("link-button");
    $("<a/>").attr( { href : '#',
                      title: btn.alt || btn.title,
                      'class': btn.className } )
              .append( this.value )
              .bind( "click", function() {
                      btn.click();
                      return false; })
              .insertBefore(this);
    $(this).hide();
  });
}

function closeOverlay(overlayElement) {
  return $('input.cancel, input.close', overlayElement).eq(0).click();
}

function insertProductVideoPlayer() {
  $('#product-video').each(function() {
    var videoUrl = $('input#videoUrl', this).val();
    if (videoUrl.length > 0) {
      swfobject.embedSWF("/Assets/CIL/Flash/video-player.swf", 'flash', "480", "320", "9.0.0", "/Assets/CIL/Flash/expressInstall.swf", {videoSrc: videoUrl}, {wmode: "transparent"} );
    }
  });
};

function simulateReviewsTabClick() { // show the Reviews panel when the user has clicked down via the 'Average Reviews' link
  $('.idTabs a[href=#reviews]').click();
}

function simulateSpecTabClick() { // show the Specifications panel when the user has clicked down via the 'Specifications' link
  $('.idTabs a[href=#specifications]').click();
}

function StarRating(element, selectElement) { // used for Write a Review

  var elementW    = jQuery(element).width(),            // star-rating element
    offsetLeft    = jQuery(element).offset().left;
    ratingElement = jQuery('.rating', element).eq(0),       // pinks stars element
    dropdown      = selectElement || jQuery(element).siblings().find('select'),
    currentStep   = 0,
    selectedStep  = $('option:selected', dropdown).val() || 0,
    setDisplayedStarRating = function(rating) {
		jQuery(ratingElement).attr('class', 'rating is-' + rating );
    };
    
  if (dropdown.length == 0) { // don't continue if the select element is not present
    return false;
  };


  jQuery(element).hover(function() {
  
  }, function() {
    //jQuery(ratingElement).attr('class', 'rating is-' + selectedStep );
    setDisplayedStarRating(selectedStep);
  });

  jQuery(element).click(function() { 
    selectedStep = currentStep; // store the rating the user selects
    jQuery('option', dropdown).eq( selectedStep ).attr('selected', 'selected'); // set the dropdown so the rating will be posted back to the server
  }).css('cursor', 'pointer'); 

  jQuery(element).mousemove(function(e) {
    var pos = e.clientX - offsetLeft;

    currentStep = Math.round( (pos / elementW) * 100 / 20 );  // calculate number of stars out of 5

    jQuery(ratingElement).attr('class', 'rating').addClass('is-' + currentStep); // set the class to show the number of stars
	setDisplayedStarRating(currentStep);
  });
  
  setDisplayedStarRating(selectedStep);

  return element;
}

function showOrHideAddAddress(contentDiv) {
	var addAddressRadioValue = "VATAddressIsDifferent";
	$('fieldset', contentDiv).each(function() {
		var fieldset = this;
		
		if ( $('input:checked', fieldset).val() == addAddressRadioValue ) {
			$('p.specify-address', fieldset).show();
		} else {
			$('p.specify-address', fieldset).hide();
		};
		
		$('input:radio', fieldset).click(function() {
			if ( this.value == addAddressRadioValue ) {
				$('p.specify-address', fieldset).show();
			} else {
				$('p.specify-address', fieldset).hide();
			}
		});
	});
}

function Overlay(rootElement) { // general purpose overlay element behaviour
  var overlay = this;
  
  $(rootElement).addClass('sv-enabled');
  
  if ( !$(this).is('.sv-enabled') ) {
	var closeButton = $('<a />').text('Close').attr('href', '#close').addClass('cancel');
	$('.wrap', rootElement).append(closeButton);
	$(rootElement).addClass('overlay overlay-narrow');
	
	if ($.browser.msie && $.browser.version < 7) {
		$(rootElement).bgiframe();
	}
  }
  
  this.close = function() {
    $(rootElement).fadeOut('fast');
  }
  
  this.open = function() {
      var scrollY = document.body.scrollTop || document.documentElement.scrollTop, // get the vertical scroll position of browser document
          windowHeight = window.innerHeight || document.documentElement.clientHeight,
          overlayHeight = $(rootElement).height();
      
      $(rootElement).css({ // adjust vertical postion in case user has scrolled down
        top:  function() {
                var verticalDistance = ( windowHeight - overlayHeight ) / 3  + scrollY;
                return  (verticalDistance > scrollY) ? verticalDistance : scrollY;
              }
		})
  
	$(rootElement).fadeIn();

  }
  
  this.name = function() {
	return $(rootElement).attr('id');
  }
  
  $(closeButton).click(function() { 
	overlay.close();
	return false; 
  });
  
  return this;
}
