﻿/// Add ref to vsdoc for intellisense
/// <reference path="jquery-1.4.1-vsdoc.min.js" />
/* VTNZ JS */

// Replaces JQuery fadeIn, fadeOut & fadeTo methods as they fuck up the font rendering in IE
// Tip of the hat goes to http://jquery.malsup.com/
if (jQuery.browser.msie) {
  jQuery.fn.fadeIn = function (speed, callback) {
    return this.animate({ opacity: 'show' }, speed, function () {
      if (jQuery.browser.msie) {
        var curStyle = this.style;
        if (curStyle != null) {
          curStyle.removeAttribute('filter');
        }
      }
      if (jQuery.isFunction(callback))
        callback();
    });
  };

  jQuery.fn.fadeOut = function (speed, callback) {
    return this.animate({ opacity: 'hide' }, speed, function () {
      if (jQuery.browser.msie) {
        var curStyle = this.style;
        if (curStyle != null) {
          curStyle.removeAttribute('filter');
        }
      }
      if (jQuery.isFunction(callback))
        callback();
    });
  };

  jQuery.fn.fadeTo = function (speed, to, callback) {
    return this.animate({ opacity: to }, speed, function () {
      if (to == 1 && jQuery.browser.msie) {
        var curStyle = this.style;
        if (curStyle != null) {
          curStyle.removeAttribute('filter');
        }
      }
      if (jQuery.isFunction(callback))
        callback();
    });
  };
}

$(document).ready(function () {
  // PNGFix for IE6
  if (typeof correctPNG == "function") {
    correctPNG();
  }

  // Init flash banner
  var flashvars = {
    width: '770',
    height: '90',
    enablejs: 'true',
    quality: 'high'
  };
  var params = {
    allowfullscreen: 'false',
    wmode: 'transparent',
    allowscriptaccess: 'always'
  };
  var attributes = {
    id: 'flybuys-ad_1',
    name: 'flybuys-ad_1'
  };
  swfobject.embedSWF(siteroot + '/notion/site/vtnzinternet/flash/vtnz-flybuys.swf', 'flybuys-ad-inner', '770', '90', '9.0.0', 'expressInstall.swf', flashvars, params, attributes);

  // Handle open of services
  $("#main-menu ul li.services-item #services-dropdown a").click(function (e) {
    e.preventDefault();    
    $("#services-popup").fadeIn('fast');
    if ($.browser.msie && $.browser.version <= 6) {
      $("#rci-station-search #ss-town-city").css("visibility", "hidden");
      $("#rci-station-search #ss-suburb").css("visibility", "hidden");
    }    
  });

  // Handle close of services popup
  $("#main-menu #services-popup a#close-services").click(function (e) {
    e.preventDefault();
    $("#services-popup").fadeOut('fast');
    if ($.browser.msie && $.browser.version <= 6) {
      $("#rci-station-search #ss-town-city").css("visibility", "visible");
      $("#rci-station-search #ss-suburb").css("visibility", "visible");
    }    
  });

  // Hide any elements that require hiding (JS will replace their functionality)
  $(".to-hide").css("display", "none");

  // Handle onchange of station finder town field (if it exists)...
  $("#ss-town-city").change(function () {
    $.get(siteroot + "/ajax/suburbs?townid=" + $(this).val(), function (data) {
      $("#ss-suburb").html(data);
    });
  });

  // Handle onchange of vehicle make
  $('.vehicleMake').change(function () {
    $.get(siteroot + '/ajax/vehicle?make=' + $(this).val(), function (data) {
      $('.vehicleModel').html(data);
    });
  });

  // searchFor:deliveryAddressHasBeenRemoved
  $('.copyDetails').click(function () {
    var rel = $(this).attr('rel');

    if (rel != '') {
      $('input#policyHolder' + rel).val($('input#firstname').val() + ' ' + $('input#lastname').val());
      $('input#address1' + rel).val($('input#address1BA').val());
      $('input#address2' + rel).val($('input#address2BA').val());
      $('input#suburb' + rel).val($('input#suburbBA').val());
      $('input#city' + rel).val($('input#cityBA').val());
      $('input#postCode' + rel).val($('input#postCodeBA').val());
    }
  });

  $("input.datePicker").datepicker({
    dateFormat: 'dd/mm/yy',
    minDate: 0,
    firstDay: 1
  });

  // product-list select dropdown
  if ($('#product-list').length) { // implies *not* zero       
    $('#product-list').jqDropDown({
      //defaultOption: 'Please select a renewal policy',
      direction: 'down',
      effect: 'fade',
      effectSpeed: 300,
      modal: true,
      placeholder: '#hiddenProductValue', // holds the id of the product to add to the cart
      useValue: true,
      optionChanged: function () {
        var url = window.location.pathname;
        var value = $('#hiddenProductValue').text();
        $('a.#addToCartButton').replaceWith('<a id=\"addToCartButton\" href=\"' + url + '?add=true&product=' + value + '\"><span>Add to cart</span></a>');
        if (value > 0) {
          $('#button-add-to-cart').css('visibility', 'visible');
          $('#button-add-to-cart').fadeTo('fast', 1, function () { });
        } else {
          $('#button-add-to-cart').fadeTo('fast', 0, function () {
            $(this).css('visibility', 'hidden');
          });
        }
      }
    });
  }


  // PPI time slot table 
  if ($('#ppi-station-list').length) {  // implies *not* zero
    $('#ppi-station-list').change(function () {
      var dropdownVal = $(this).val();
      $('#ppi-ajax-container').empty().html('<div style="width:100%;margin-top:50px"><img style="margin:auto;display: block;" src="notion/site/VTNZInternet/images/VTNZInternet/ajax-loader.gif" /></div>').delay(200);

      $.get(siteroot + '/ajax/timeslots?stationid=' + dropdownVal, function (data) {
        $('#ppi-ajax-container').fadeOut('fast', function () {
          $('#ppi-ajax-container').html(data).fadeIn('slow', function () {
            $("#scrollContainer").mCustomScrollbar("horizontal", 400, "easeOutCirc", 1, "fixed", "yes", "yes", 20);
          });
        });
      });
    });
  }



  // PPI products and cart
  if ($('#ppi-product-select').length) { // if found then continue

    // Product has been selected or unselected
    $('#ppi-product-select').change(function () {

      var productId = $('#ppi-product-select option:selected').attr('id');
      var productName = $('#ppi-product-select option:selected').text();
      $('#productId').val(productId);
      var productPrice = parseFloat($(this).val()).toFixed(2);
      var productSavingAmount = parseFloat($('#' + productId + 'Saving').val()).toFixed(2);

      var products = [];
      products = productName.split(' + ');

      var cartItemsText = '<tr><td>' + products[0] + '</td><td class="col-price"><span class="mainPrice">$' + productPrice + '</span></td></tr> ';

      if (products.length > 1) {
        for (var i = 1; i < products.length; i++) {
          cartItemsText += '<tr><td>+ ' + products[i] + '</td></tr>';
        }
      }

      cartItemsText += '<tr class="totalLine"><td class="col-price" colspan="2">Total: <span class="mainPrice">$' + parseFloat(productPrice).toFixed(2) + '</span>';
      if (productSavingAmount > 0) {
        cartItemsText += '<br><span class="discount">Saving: $' + parseFloat(productSavingAmount).toFixed(2) + '</span>';
      }
      cartItemsText += '</tr>';

      if ($('#no-cart-items-notice').is(':visible')) {
        $('#no-cart-items-notice').fadeOut('fast', function () {
          $('table#cart-items').html(cartItemsText).fadeIn('fast');
          $('#cart-buttons').fadeIn('fast');
        });
      } else {
        $('table#cart-items').fadeOut('fast', function () {
          $('table#cart-items').html(cartItemsText).fadeIn('fast');
        });
      }

      checkDisplayNextStepLink(siteroot);

      // A timeslot has been selected so check if we should display the next step link
      // Use .live('change') instead of .change() as timeslot table is loaded dynamically using ajax so it is not part of DOM when the page finishes loading
      $('.radioTimeslot:input:radio').live('change', function () {
        checkDisplayNextStepLink(siteroot);
      });

      // Hide the "next step" button if a new station has been selected from the drop down
      $('#ppi-station-list').change(function () {
        $('a#next-step-button').fadeOut('fast');
      });

    });

  } //close if

  if ($('#finalNoticeMessage').length) {
      $.colorbox({ width: "630px", open: true, inline: true, href: "#finalNoticeMessage" }, reloadSifr('div#finalNoticeMessage h2'));
  }    

});    //close $(document).ready();




/***************************/
/******** FUNCTIONS ********/
/***************************/

function reloadSifr(cssSelector) {
    setTimeout(function () {        
        sIFR.replace(daxregularnormalbold, {
            selector: cssSelector, wmode: 'transparent', css: ['.sIFR-root { text-align: left; font-style:italic;color:#333333;}']
        });
    }, 500);
}

function displayShopProducts(item) {
  var $item = $(item);
  var $parentPanel = $item.parent($('.panel'));

  if ($parentPanel.hasClass('expanded')) {
    $parentPanel.removeClass('expanded').addClass('collapsed');
    $item.siblings('.productDetails').slideUp('fast');
  } else {
    $parentPanel.removeClass('collapsed').addClass('expanded');
    $item.siblings('.productDetails').slideDown('fast');
  }
}

// Check to see that a product and a time slot has been selected before displaying next step link
function checkDisplayNextStepLink(siteroot, productId) {
  if ($('#productId').length && $('.radioTimeslot:input:radio:checked').length) {
    $('a#next-step-button').fadeIn('fast', function () {
      var productId = $('#productId').val();
      var rawTimeslotInfo = $('.radioTimeslot:input:radio:checked').val().split('|');
      var timeslotId = rawTimeslotInfo[0];
      var inspectionTime = rawTimeslotInfo[1];
      var stationName = $('#ppi-station-list option:selected').text();
      var link = siteroot + '/prepurchaseinspection?add=true&';
      $('a#next-step-button').attr("href", link + "productId=" + productId + "&timeslotId=" + timeslotId + "&inspectionTime=" + inspectionTime + "&stationName=" + stationName);
    });
  }
}

function initStationSelectForm(parentNode, clear) {
  $(parentNode).find('.station-select-station select option').each(function () {
    $(parentNode).find('.station-select-station select').data('' + $(this).val(), '' + $(this).attr('rel'));
  });

  $(parentNode).find('.station-select-region select').change(function () {
    var selectedValue = $(this).val();
    $(parentNode).find('.station-select-station select option').remove();
    $(parentNode).find('.station-select-station select').append('<option value="">Select station...</option>');

    $.each($(parentNode).find('.station-select-station select').data(), function (i, e) {
      if (selectedValue == e) {
        $(parentNode).find('.station-select-station select').append('<option value="' + i + '">' + i + '</option>');
      }
    });
  });

  if (clear) {
    $(parentNode).find('.station-select-station select option').remove();
  }

  $(parentNode).find('.station-select-region').show();
}

