var dax = {
  src: '/notion/site/MTA/flash/mta/dax.swf'
};

var map = null;
var geocoder = null;
var markerUrl = "http://mta.org.nz/notion/site/mta/images/mta/map-marker.gif";

sIFR.bUseInnerHTMLHack = true;
sIFR.preserveSingleWhitespace = false;
sIFR.activate(dax);

sIFR.replace(dax, {
  selector: 'h1.sifr',
  ratios: [8, 0.93, 11, 0.97, 14, 1.09, 19, 1.11, 25, 1.13, 28, 1.15, 32, 1.16, 36, 1.13, 42, 1.15, 45, 1.16, 52, 1.17, 60, 1.18, 67, 1.19, 68, 1.2, 69, 1.19, 70, 1.2, 72, 1.19, 83, 1.2, 84, 1.21, 85, 1.2, 86, 1.21, 88, 1.2, 107, 1.21, 108, 1.22, 109, 1.21, 110, 1.22, 111, 1.21, 1.22],
  css: ['.sIFR-root { color: #00aeef; font-size: 27px; leading: -5;}'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h2.green',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #00a890; font-size: 21px; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h2.sifr-blue',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #00aeef; font-size: 17px; background-color: #ff0000; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h2.sifr-grey',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #666666; font-size: 17px; background-color: #ff0000; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h2.sifr-blue-narrow',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #00aeef; font-size: 17px; background-color: #ff0000; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h2.sifr',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #00aeef; font-size: 17px; } ','a { text-decoration: none; }' ,'a:link { color: #00AEEF; }' ,'a:hover { color: #00AEEF; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h3.sifr-white',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #ffffff; font-size: 15px; } ','a { text-decoration: none; }' ,'a:link { color: #ffffff; }' ,'a:hover { color: #999999; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h3.sifr-grey',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #666666; font-size: 15px; } ','a { text-decoration: none; }' ,'a:link { color: #666666; }' ,'a:hover { color: #00AEEF; }'], 
  wmode: 'transparent'
});

sIFR.replace(dax, {
  selector: 'h3.sifr',
  ratios: [10, 1.43, 12, 1.35, 16, 1.34, 23, 1.32, 24, 1.29, 28, 1.3, 36, 1.29, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26],
  css: ['.sIFR-root { color: #00aeef; font-size: 15px; } ','a { text-decoration: none; }' ,'a:link { color: #00AEEF; }' ,'a:hover { color: #00AEEF; }'], 
  wmode: 'transparent'
});

$(document).ready(function() {
  InitBannerRotation();
  InitFindMember();
  InitLogin();
  InitSearch();
  InitStore();
  InitGallery();
  InitFloatInfo();
  InitCalendarHighlight();
  InitTopicSearchCategory();
  InitDescriptionCounter();
});

function InitDescriptionCounter(){
  $('#txtBusinessDescription').each(function(){
    $(this).after('<div id="businessDescriptionLabel">Your description can contain another ' + (255 - $(this).html().length) + ' characters.</div>');
    
    $(this).keyup(function(){
      var length = 255 - $(this).html().length;
      if(length > 0){
        $('#businessDescriptionLabel').html('Your description can contain another ' + length + ' characters.');
      } else if(length == 0){
        $('#businessDescriptionLabel').html('Your description contains exactly 255 characters.');
      } else {
        $('#businessDescriptionLabel').html('Your description can only contain 255 characters, please remove ' + (-length) + ' characters.');
      }
    });
  });
}

function InitFloatInfo(){
  var zIndex = 2000;
  
  $('div.float-image-wrapper').each(function(){
    $(this).css('z-index', zIndex--);
  });
  
  $('div.float-image-wrapper').hover(
    function(){
      $(this).find('div.float-image-popup-wrapper').show();
    },
    function(){
      $(this).find('div.float-image-popup-wrapper').hide();
    }
  );
}

function ShowOnMap(tradingName, address, retryAddress){
  var mapNode = document.getElementById('map');

  if(mapNode){
    var map = new GMap2(mapNode);    
    var geocoder = new GClientGeocoder();
    

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = null;
    baseIcon.iconSize = new GSize(39, 28);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(39, 28);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    // Creates a marker whose info window displays the letter corresponding
    // to the given index.
    function CreateMarker(popupDisplayText, point) {
      var letteredIcon = new GIcon(baseIcon);
      letteredIcon.image = markerUrl;

      // Set up our GMarkerOptions object
      markerOptions = { icon:letteredIcon };
      var marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(popupDisplayText);
      });
      
      return marker;
    }

    if(map && geocoder){
      map.addControl(new GLargeMapControl());

      geocoder.getLatLng(
        address,
        function(point) {
          if (!point) {
            if(retryAddress){
              ShowOnMap(tradingName, retryAddress, null);
            } else {
              $('map-description').html('The location specified could not be found');
            }
          } else {
            var popupDisplayText = "<b>" + tradingName + "</b><br />" + address;
            
            map.setCenter(point, 15);
            var marker = CreateMarker(popupDisplayText, point);
            map.addOverlay(marker);
            marker.openInfoWindowHtml(popupDisplayText);
          }
        }
      );
    }
  }
}

function InitBannerRotation(){
  $('#banner-images').cycle();
  $('#additional-column-links').cycle({delay: 8000, timeout: 8000});
  $('#additional-column-partners-logos').cycle({delay: 2000, timeout: 5000});
}

function InitSearch(){
  $("#keywords").blur(function () {
    if($(this).val() == ''){
      $(this).val('Search');
    }
  });
  
  $("#keywords").focus(function () {
    if($(this).val() == 'Search'){
      $(this).val('');
    }
  });  
}

function InitFindMember(){
  $('#find-member-link').click(function () {
    $(this).blur();
    var wNode = $('#find-member-form');
  
    if(wNode){   
      if(wNode.height() != 15){
        wNode.animate({'height': '15px'}, 'slow');
      } else {
        wNode.animate({'height': '122px'}, 'slow');
      }
    }
    
    return false;
   });
}

function InitLogin(){
  $('#login-button').click(function () {
    $(this).blur();
    var node = $('#login-box');
  
    if(node){
      if(node.css('display') != 'block'){
        node.css({'display' : 'block'});
        node.css({'height': '0px', 'width': '0px', 'visibility' : 'visible'});
      }
    
      if(node.height() != 175){
        node.animate({'height': '175px', 'width': '280px'}, 'slow');
      } else {
        node.animate({'height': '0px', 'width': '0px'}, 'slow');
      }
    }
    
    return false;
   });
}

function InitStore(){
  $('#Delivery_Details_Business_Name').each(function(){
    $(this).after('<div class="descriptionLabel"><input class=\"checkbox\" type="checkbox" onclick=\"ToggleResidentialDetail();\" id="Delivery_Details_Business_Name_Check" value="residential" /> <label for="Delivery_Details_Business_Name_Check">Residential</label></div>');
    $('#Delivery_Details_Business_Name_Check').click(function(){
      if($(this).attr('checked')){
        $('#Delivery_Details_Business_Name').each(function(){
            $(this).val('Residential');
            $(this).attr('disabled', 'disabled');
        });
      } else {
        $('#Delivery_Details_Business_Name').each(function(){
            $(this).val('');
            $(this).removeAttr('disabled');
            $(this).focus();
        });
      }
    });
  });
  
  $('#Delivery_Details_Telephone_Number').each(function(){
    $(this).after('<div class="error"></div>');
    
    $(this).keyup(function(){
      var length = this.value.length;
      if(length > 0){
        if(this.value[0] != '0' || !this.value.toString().match(/^\d*$/)){
         // $(this).parent().find('div.error').html('Please provide a phone number, including the area code, without any spaces.');
        } else {
          $(this).parent().find('div.error').html('');
        }
      }
    });
  });

  $('input.product-quantity').blur(function(){
    UpdateItemPrice(this);
    UpdateTotal();
  });
   
  $('#Ecom_Payment_Card_Type').change(function(){
    InitCreditCard(this);
    UpdateTotal();
  });
    
  if($('#button-purchase').length > 0){
    $('#confirm').click(function(){
      var status = !($(this)[0].checked);
      $('#button-purchase')[0].disabled = status;
      
      if(status){
        $('#button-purchase').css('background-image', 'url(notion/site/mta/images/mta/button-purchase-disabled.gif)');
      } else {
        $('#button-purchase').css('background-image', 'url(notion/site/mta/images/mta/button-purchase.gif)');
      }
    });
  
    $('#button-purchase')[0].disabled = true;
    $('#button-purchase').css('background-image', 'url(notion/site/mta/images/mta/button-purchase-disabled.gif)');
  }
  
  if($('#Ecom_Payment_Card_Type').length > 0){
    InitCreditCard($('#Ecom_Payment_Card_Type'));
  }
  
  function InitCreditCard(node){
    if($(node).val() == "Cardlink"){
      $('#store-input-card').hide();
    } else {
      $('#store-input-card').show();
    }
  }

  function UpdateItemPrice(node){
    var quantity = parseInt(node.value, 10);
    var price = parseFloat($('#' + node.name.replace(/Ouantity/, "Price")).val());
    
    if(isNaN(quantity) || isNaN(price)){
      quantity = 0;
      price = 0;
    }

    $('#' + node.name.replace(/Ouantity/, "Total")).html((quantity * price) + '');  
  }
  
  function UpdateTotal(){
   
    var total = 0;
    var shipping = 0;
    
    $('span.product-sum').each(function(){
      var val = parseFloat($(this).html())
    
      if(!isNaN(val)){
        total += val;
      }
    });
    
    if($('#Ecom_Payment_Card_Type').val() == "Cardlink"){
      shipping = 5;
    } else {
      $(sah.items).each(function(){
        if(this.min <= total && this.max >= total){
          shipping = this.cost;
        }
      });
    }
    
    var allTotal = total + shipping;
    
    if(total > sah.max){
      $('#shipping-total').html('');
      $('#shipping-cost').html('');
      $('#order-total').addClass('error');
      $('#order-total').html('Your order has exceeded the maximum amount ($' + sah.max + ').');
    } else {
      $('#shipping-total').html('$' + shipping);
      $('#shipping-cost').html('$' + shipping);
      $('#order-total').removeClass('error');
      $('#order-total').html('$' + allTotal);
    }
  }
}

/*** News and events Image Gallery ****/

var gallery_position = 0;
var gallery_imageWidth = 58;
var gallery_currentImage = 0;

function InitGallery(){
  
  var galleryNavigation = $('div.gallery-navigation-wrapper');
  
  if(galleryNavigation.length > 0){
    
    $('a.image-thumb-anchor').click(function(){
      $('div.gallery-main-image-wrapper img')[0].src = $(this).parent().find('img')[0].src.replace("_thumbnail", "");
      return false;
    });
    
    var imageThumbHolder = $('div.gallery-image-thumbs');
    imageThumbHolderWidth = $('div.gallery-image-thumbs img').length * gallery_imageWidth;
    imageThumbHolder.css({width: imageThumbHolderWidth + "px"})
        
    $('div.gallery-btn-previous').click(function(){MoveSlide('left');});
    $('div.gallery-btn-next').click(function(){MoveSlide('right');});
    
    galleryNavigation.show();
  }
  
  return false;
}
        
function MoveSlide(direction){
  var imageThumbHolder = $('div.gallery-image-thumbs');
  var imageThumbs = $('div.gallery-image-thumbs img');
  var imageCount = imageThumbs.length;
  var toggleSlide = false;

  if(direction == "left"){
    if(gallery_currentImage > 0){
      gallery_position = gallery_position + gallery_imageWidth;
      gallery_currentImage--;
      toggleSlide = true;
    }
  } else {
    if(gallery_currentImage < (imageCount - 4)){ 
      gallery_position = gallery_position - gallery_imageWidth;
      gallery_currentImage++;
      toggleSlide = true;
    }
  }

  if(toggleSlide){
    ToogleThumbs(imageThumbHolder);
  }
  return false;
}

function ToogleThumbs(imageThumbHolder){
  imageThumbHolder.animate({left: gallery_position + "px"}, 600);
  return false;
}

/**** Training Calendar ****/

function InitCalendarHighlight(){
  $('tr.calenderItem').each(function () {
    var link = $(this).find('a')[0];
    
    if(link){
      $(this).click(function(){window.location.href = link.href});
    }
  
    $(this).hover(
      function () {
        $(this).css('background-color', '#C7C7C7');
      }, 
      function () {
        $(this).css('background-color', '');
      }
    )
  });
}

function ToggleCalendar(direction){
  return false;
}

/** Bulletin Board Index **/

function InitTopicSearchCategory(element){
  if($('#topic-search-category').val() != "technical"){
    $('tr.topic-search-category-select-technical').hide();
  }

  $('#topic-search-category').change(function(){
    if(this.value == "technical"){
      $('tr.topic-search-category-select-technical').show();
    } else {
      $('tr.topic-search-category-select-technical').hide();
    }
  });
  
  $('#vehicletype').change(function(){
    var type = this.value;
    
    var options = '<option value=""></option>';
    
    $(makemodel.Vehicles).each(function(){
      if(this.Type.toLowerCase() == type){
        options += '<option value="' + this.Make + '">' + this.Make + '</option>';
      }
    });
    
    $("#make").html(options);
    $("#model").html('');
  
  });
  
  $('#make').change(function(){
    var make = this.value.toLowerCase();
    var options = '';
    
    $(makemodel.Vehicles).each(function(){
      if(this.Make.toLowerCase() == make){
        for (var i = 0; i < this.Models.length; i++) {
          options += '<option value="' + this.Models[i] + '">' + this.Models[i] + '</option>';
        }
      }
    });
    
    $("#model").html(options);
  });
}


function UpdateMemberSearchBox(){
   var updateNode = jQuery('#find-member-form');

  var url = 'default.csf?pageid=' + pageId + '&indexer=' + indexerId + '&ipage=' + indexPageNumber + '&cpage=' + contentPageNumber;
  	   
  jQuery.ajax({
    type: 'GET',
    url: url,
    success: function(html){
      updateNode.html(html);
    }
  });
}



function ToggleBillingDetails(checkboxElement, firstNameFieldId, lastNameFieldId, businessNameFieldId, addressFieldId, postCodeFieldId,
                              deliveryFirstNameFieldId, deliveryLastNameFieldId, deliveryBusinessNameFieldId, deliveryAddressFieldId, 
                              deliveryPostCodeFieldId){
  
  
  var disableField = false;
 
  if($(checkboxElement).attr("checked")){
    disableField = true;
  }
  
   CopyOrderDetails(firstNameFieldId, lastNameFieldId, businessNameFieldId, addressFieldId, postCodeFieldId,
                     deliveryFirstNameFieldId, deliveryLastNameFieldId, deliveryBusinessNameFieldId, deliveryAddressFieldId, 
                     deliveryPostCodeFieldId);
  
  ToggleFieldAccessibility(deliveryFirstNameFieldId, disableField);
  ToggleFieldAccessibility(deliveryLastNameFieldId, disableField);
  ToggleFieldAccessibility(deliveryBusinessNameFieldId, disableField);
  ToggleFieldAccessibility(deliveryAddressFieldId, disableField);
  ToggleFieldAccessibility(deliveryPostCodeFieldId, disableField);
  
  return false;
}

function CopyOrderDetails(firstNameFieldId, lastNameFieldId, businessNameFieldId, addressFieldId, postCodeFieldId,
                          deliveryFirstNameFieldId, deliveryLastNameFieldId, deliveryBusinessNameFieldId, deliveryAddressFieldId, 
                          deliveryPostCodeFieldId){
    
    if($("#" + "billingDetailsCheckbox").attr("checked")){
      CopyOrderDetailValue(firstNameFieldId, deliveryFirstNameFieldId);
      CopyOrderDetailValue(lastNameFieldId, deliveryLastNameFieldId);
      CopyOrderDetailValue(businessNameFieldId, deliveryBusinessNameFieldId);
      CopyOrderDetailValue(addressFieldId, deliveryAddressFieldId);
      CopyOrderDetailValue(postCodeFieldId, deliveryPostCodeFieldId); 
    }
  return false;
}
                          
function ToggleResidentialDetail(){
  var checkbox = $('#Delivery_Details_Business_Name_Check');
    
  if(checkbox.attr("checked") == true){
     $("#Delivery_Details2_Business_Name").attr("value", "Residential");
  } else {
     $("#Delivery_Details2_Business_Name").attr("value", "");
  }
}                          

function CopyOrderDetailValue(sourceFieldId, targetFieldId, isTextArea){
  var sourceFieldObj = $("#" + sourceFieldId);
  var targetFieldObj = $("#" + targetFieldId);
  
  if(sourceFieldObj.val() != ""){
    targetFieldObj.val(sourceFieldObj.val());
  }
  return false;
}

function ToggleFieldAccessibility(elementId, disable){
  var elementObj = $("#" + elementId);
  if(disable){
    elementObj.attr("disabled",true);
  } else {
    elementObj.attr("disabled",false);
  }
  return false;
}

function OnclickRemoveAutoLogin(checkboxElement){
  var checkBox = $(checkboxElement);
  var logoutButton = $('#logout-button');
  var logoutHref = logoutButton.attr("href");
  
  if(checkBox.attr("checked") == true){
    if(logoutHref.indexOf("removeAutoLogin") == -1){
      logoutHref += "&removeAutoLogin=true";
    } 
  } else {
    logoutHref = logoutHref.replace("&removeAutoLogin=true", "");
  }
   logoutButton.attr("href", logoutHref);
}