// Slider
(function($){$.fn.slider=function(options){var animater=function(e,settings){$holder=$(e);if(settings.vertical){var tf=-(settings.cHeight-settings.tHeight);}else{var tf=-(settings.cWidth-settings.tWidth);};if(settings.direction=='ltr'){if(settings.vertical){$holder.css({top:0});$holder.animate({top:tf},settings.speed,settings.easing,function(){animater(e,settings);});}else{$holder.css({left:0});$holder.animate({left:tf},settings.speed,settings.easing,function(){animater(e,settings);});}}else{if(settings.vertical){$holder.css({top:tf});$holder.animate({top:0},settings.speed,settings.easing,function(){animater(e,settings);});}else{$holder.css({left:tf});$holder.animate({left:0},settings.speed,settings.easing,function(){animater(e,settings);});}}};return this.each(function(){var settings={direction:'ltr',vertical:false,speed:20000,easing:'linear'};$.extend(settings,options);settings.tHeight=$(this).height();settings.tWidth=$(this).width();var $kids=$(this).children();if(settings.vertical){settings.cWidth=settings.tWidth;settings.cHeight=settings.tHeight*($kids.length+1);}else{settings.cWidth=settings.tWidth*($kids.length+1);settings.cHeight=settings.tHeight;};$kids.wrapAll('<div></div>');var $holder=$(this).find('div:first');$holder.css({position:'relative'});$holder.css({width:settings.cWidth,height:settings.cHeight});if(settings.direction=='ltr'){$holder.append($kids.first().clone());}else{$holder.prepend($kids.last().clone());};var $kids=$holder.children();$(this).css({overflow:'hidden',whiteSpace:'nowrap'});$(this).css({width:settings.tWidth,height:settings.tHeight});$kids.css({'float':'left'});$kids.css({width:settings.tWidth,height:settings.tHeight});animater($holder,settings);});};}(jQuery));
// Cookie
jQuery.cookie=function(d,e,b){if(arguments.length>1&&String(e)!=="[object Object]"){b=jQuery.extend({},b);if(e===null||e===undefined){b.expires=-1}if(typeof b.expires==="number"){var g=b.expires,c=b.expires=new Date();c.setDate(c.getDate()+g)}e=String(e);return(document.cookie=[encodeURIComponent(d),"=",b.raw?e:encodeURIComponent(e),b.expires?"; expires="+b.expires.toUTCString():"",b.path?"; path="+b.path:"",b.domain?"; domain="+b.domain:"",b.secure?"; secure":""].join(""))}b=e||{};var a,f=b.raw?function(h){return h}:decodeURIComponent;return(a=new RegExp("(?:^|; )"+encodeURIComponent(d)+"=([^;]*)").exec(document.cookie))?f(a[1]):null};
//Cycle scroll both ways
$.fn.cycle.transitions.scrollBothWays=function(b,c,a){b.css("overflow","hidden");a.before.push($.fn.cycle.commonReset);a.fxFn=function(r,k,d,g,j){var q=b.width();d.cssFirst={left:0};d.animIn={left:0};if(j){d.cssBefore={left:q,top:0};d.animOut={left:0-q}}else{d.cssBefore={left:-q,top:0};d.animOut={left:q}}var p=$(r),l=$(k);var f=d.speedIn,o=d.speedOut,i=d.easeIn,n=d.easeOut,e=d.animOut,h=d.animIn;l.css(d.cssBefore);var m=function(){l.show();l.animate(h,f,i,g)};p.animate(e,o,n,function(){if(d.cssAfter){p.css(d.cssAfter)}if(!d.sync){m()}});if(d.sync){m()}}};

$(document).ready(function(){  

  // Search submit
  $("#search .submit").click(function(e) {
    e.preventDefault();
    $(this).closest("form").submit();
  });

  // Add first child class 
  $(".sub-nav li:first-child").addClass("first-child");
  $(".sub-nav .sub-nav li:first-child").addClass("first-child");
  
  // Clear textbox and return to default (focus/blur)
  $(".textbox-auto-clear").each(function(){
    var searchOrigVal = $(this).val(); // Store the original value
    $(this).focus(function(){
      if($(this).val() == searchOrigVal) {
        $(this).val('');
      }
    });
    
    $(this).blur(function(){
      if($(this).val() == '') {
        $(this).val(searchOrigVal);
      }
    });
  });
  
  // Get started link animations
  $("#get-started > li")
  .hover(function() {
    $(this).children(".icon").stop().animate({
      top: -12
    }, 300);
  },function() {
    $(this).children(".icon").stop().animate({
      top: -7
    }, 300);
  })
  .click(function() {
    window.location = $(this).children(".icon").attr("href");
  });
  
  // Top navigation
  $(function() {
    $("#nav li").hover(function() {
      $(this).children("a").addClass("hover");
      $(this).parent().children("a").addClass("hover");
      $("ul:first", this).css('visibility', 'visible');
    }, function() {
      $(this).children("a").removeClass("hover");
      $(this).parent().children("a").removeClass("hover");
      $("ul:first", this).css('visibility', 'hidden');
    });
  });
  
  // Home Cycle 
  $("#slideshow").cycle({
    fx: 'fade',
    timeout: 7000
  });

  // About Gallery Fancybox 
  $("#sub-images li a").fancybox({
    width: 800,
    height: 600,
    autoDimensions: false
  });
  
  $("#news ul").cycle({
    fx: 'scrollBothWays',
    timeout: 0,
    prev: "#news-next",
    next: "#news-prev",
    rev: true
  });
  
  // Show Terms Fancybox
  var $showTerms = $("#show-terms");
  $showTerms.fancybox({
    width: 800,
    height: 500,
    autoDimensions: false,
    type: 'iframe'
  });
  
  // If terms and conditions page is open by itself, we'll be redirected to homepage with showTerms query string
  if(getParameterByName("showTerms") == 1) {
    $showTerms.click();
  }
  
  
  $("#help-intro").fancybox({
    width: 400,
    autoDimensions: false
  });
  
  // Show Freight Code Fancybox
  
  var $freightCode = $("#freight-code");
  $freightCode.fancybox ({
    width: 800,
    height: 500,
    autoDimensions: false,
    type: 'iframe'
  });
  
  //Text Slider 
  $("#slider2").slider({
    direction: 'ltr',
    speed: 15000
  });
  
  // Get started vars
  var $gs = $("#getstarted-cat #get-started");
  var $open = $("#gs-open");
  var $close = $("#gs-close");
  
  // Get started preview
  if($.cookie("gs") == null) {
    $gs.delay(500).slideDown(700, function() {
      $close.fadeToggle(200);
      $.cookie('gs', 'open', { expires: 365, path: '/' });
    });
  }
  
  // Go Back
  $("#go-back").click(function(e) {
    e.preventDefault();
    history.go(-1);
  });

  // Get started open/close functionality
  $open.click(function(e) {
    e.preventDefault();
    $gs.slideToggle(500, function() {
      if($gs.is(":visible"))
        $.cookie('gs', 'open', { expires: 365, path: '/' });
      else
        $.cookie('gs', 'closed', { expires: 365, path: '/' });
      $close.fadeToggle(200);
    });
  });
  $close.click(function(e) {
    $gs.slideUp(500, function() {
      $close.fadeOut(200);
      $.cookie('gs', 'closed', { expires: 365, path: '/' });
    });
  });
  
  // Booking Form
  var $bookForm = $("#book-form");
  if($bookForm.size() > 0) {
  
    // Populate fields from query string
    var origin = getParameterByName("origin");
    var destination = getParameterByName("destination");
    
    if(origin.length > 0) {
      $(".input-origin", $bookForm).val(origin);
    }
    if(destination.length > 0) {
      $(".input-destination", $bookForm).val(destination);
    }
    
    // Customize Validation
    $(".book-button", $bookForm).click(function() {
      Page_ClientValidate();
      if (Page_IsValid==true) {
        console.log("true");
      }
      else {
        var $validation = $(".validation", $bookForm);
        window.setTimeout(function() {
          $validation.prepend("<span>Error.</span>");
          $("<p />").addClass("generic-message").html("For assistance, please contact our Freight Service Centre on <b>0800 351 351</b> or email <a href=\"mailto:freight@kiwirail.co.nz\">freight@kiwirail.co.nz</a>").appendTo($validation);
          $("<a />").attr("href", "#").addClass("close").text("Close").click(function(e) {
            e.preventDefault();
            $validation.hide();
          }).appendTo($validation);
          $("<img />").attr("src", "/images/error_bottom.gif").appendTo($validation);
        }, 100);
      }
    });
  }
});

function validateEmailPhone(sender, args) {
  var phone = $.trim($(".form-phone").val());
  var email = $.trim($(".form-email").val());
  args.IsValid = !(phone.length == 0 && email.length == 0);
}

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, " "));
}
