var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
  version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
  chrome: /chrome/.test( userAgent ),
  safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
  opera: /opera/.test( userAgent ),
  msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
  mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

// For use within normal web clients 
var isiPad = navigator.userAgent.match(/iPad/i) != null;

// For use within iPad developer UIWebView
// Thanks to Andrew Hedges!
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);

$(function(){
  if($.browser.mobile) {
    $('#block-userfeedback-link').hide();
  }
  if(isiPad){
     $('#block-userfeedback-link').hide();
  }
  // main menu
// initialise Superfish 
 
     $("#header ul.menu:first").removeClass('menu').addClass('sf-menu sf-navbar');
     $("#header ul.sf-menu").attr('id', 'main-nav');
     
     $("#header ul.sf-menu li").removeClass('leaf');
     $("#header ul#main-nav li.first:first").attr('id','home-icon');
     
     $("#header ul.sf-menu ul.menu").removeClass('menu');
     $("#header ul.sf-menu ul").addClass('sub-nav');
     $("#header ul.sf-menu ul.sub-nav li").removeClass('active-trail');
     $("#header ul.sf-menu ul.sub-nav ul").remove();
     
     $("#header ul.sub-nav li").removeClass('collapsed');
     
     $("#header ul.sf-menu").superfish({ 
            pathClass:  'active-trail' ,
            delay		: 800,
            speed   : 'fast'
     });
        
        
     
 
  
 // if ($('.lavaLamp li.active-trail').length>0 && $('.lavaLamp li.active').length==0){
 //   $('.lavaLamp li.active-trail').addClass('active');
 // }
 // $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700 });
  
  // default text in text fields
  $("#edit-search-block-form-1").DefaultValue("");
  if ($('#edit-search-block-form-1').length > 0) {
      $('#block-search-0 input[type="text"]').click(function () {
          //if (jQuery('#block-search-0 input[type="text"]').css() == 'Search MHB') {
              $('#block-search-0 input[type="text"]').css('background','white');
          //}
      });
      $('#edit-search-block-form-1').blur(function () {
          if ($('#block-search-0 input[type="text"]').val() == '') {
              $('#block-search-0 input[type="text"]').css('background','url("/themes/fairmont/images/icon-search.png") no-repeat white');
          }
      });          
  }  
  
  $("#arrivalDate").DefaultValue("Start date");
  $("#departureDate").DefaultValue("End date");
  $("#arrivalDateDirectBooking").DefaultValue("Arrival date");
  
  // cross browser issues
  if ($.browser.chrome){
    $('#home_wrapper .panel-panel .pane-block-6, #home_wrapper .panel-panel .pane-block-10').css('width', '200px').css('height', '228px');
  }
  else if ($.browser.safari){
    $('#home_wrapper .pane-block-8 .pane-content p').css('margin', '0.4em 0');
  }else if ($.browser.mozilla){
    $('.upload-image-images .item-list ul li a img').css('border', '2px solid #B9CEDA');
  }
  
  // date picker
  if ($('#teedate').length>0){
    $("#teedate").datepicker({
      dateFormat: "yy-mm-dd",
      minDate: +1,
      maxDate: "+12M",
      showOtherMonths: true,
      selectOtherMonths: true,
      showOn: "both",
      buttonImage: "/themes/fairmont/images/btn-calendar.png",
      buttonImageOnly: false
    });
  }
  if ($('#arrivalDate, #departureDate').length>0){
    var dates = $("#arrivalDate, #departureDate").datepicker({
      defaultDate: "+1d",
      dateFormat: "yy-mm-dd",
      minDate: +1,
      maxDate: "+12M",
      changeMonth: true,
      changeYear: true,
      showOn: "both",
      buttonImage: "/themes/fairmont/images/btn-calendar.png",
      buttonImageOnly: false,
      onSelect: function( selectedDate ) {
        var option = this.id == "arrivalDate" ? "minDate" : "maxDate",
        instance = $( this ).data( "datepicker" );
        date = $.datepicker.parseDate(
          instance.settings.dateFormat ||
          $.datepicker._defaults.dateFormat,
          selectedDate, instance.settings );
        if (this.id == "arrivalDate"){
          $("#arrivalYear").val(date.getFullYear().toString());
          $("#arrivalMonth").val((date.getMonth()).toString());
          $("#arrivalDay").val(date.getDate().toString());
          date.setDate(date.getDate()+1);
          dates.not( this ).datepicker( "option", option, date );
          if ($("#departureDate").val()>''){
            var dstr = $("#departureDate").val().replace('-', '/');
            var dateTo = new Date(dstr.replace('-', '/'));
            $("#nightsStay").val(Math.ceil((dateTo.getTime()-date.getTime())/86400000)+1);
          }
        }
        else{
          date.setDate(date.getDate()-1);
          dates.not( this ).datepicker( "option", option, date );
          if ($("#arrivalDate").val()>''){
            var dstr = $("#arrivalDate").val().replace('-', '/');
            var dateFrom = new Date(dstr.replace('-', '/'));
            $("#nightsStay").val(Math.ceil((date.getTime()-dateFrom.getTime())/86400000)+1);
          }
        }
      }
    });
  }
  
  if ($('#arrivalDateDirectBooking').length>0){
    var dates = $("#arrivalDateDirectBooking").datepicker({
      defaultDate: "+1d",
      dateFormat: "yy-mm-dd",
      minDate: +1,
      maxDate: "+12M",
      changeMonth: true,
      changeYear: true,
      showOn: "both",
      buttonImage: "/themes/fairmont/images/btn-calendar.png",
      buttonImageOnly: false,
      onSelect: function( selectedDate ) {
        var option = this.id == "arrivalDateDirectBooking" ? "minDate" : "maxDate",
        instance = $( this ).data( "datepicker" );
        date = $.datepicker.parseDate(
          instance.settings.dateFormat ||
          $.datepicker._defaults.dateFormat,
          selectedDate, instance.settings );
        if (this.id == "arrivalDateDirectBooking"){
          $("#arrivalYear").val(date.getFullYear().toString());
          $("#arrivalMonth").val((date.getMonth()).toString());
          $("#arrivalDay").val(date.getDate().toString());
        }

      }
    });
  }
  
  $('.upload-image-images .item-list ul li').append('<div class="magnifyIcon"></div>');
  
  //$('.upload-image-images .item-list ul li a').prepend('<div class="imgBox"></div>');
    
  $('.upload-image-images .item-list ul li').hover( 
    function () { $(this).children('.magnifyIcon').css('background-position','0 -15px');},
    function () { $(this).children('.magnifyIcon').css('background-position','0 0');}
  );
  
  if ($('#block-block-3 .content ul li').length>0){
    $('#block-block-3 .content ul li').append('&nbsp;<img alt="plus-icon" style="vertical-align:-9%;" src="/themes/fairmont/images/link-list.png" border=0 width="12" height="12" />');
  }
  if ($('.menu-block-1 ul.menu li').length>0){
    $('div.menu-block-1 ul.menu li.leaf a').append('&nbsp;<img alt="plus-icon"style="vertical-align:-9%;" src="/themes/fairmont/images/link-list.png" border=0 width="12" height="12" />');
  }
  if ($('.view-Blog-archive-2 ul.views-summary li').length>0){
    $('.view-Blog-archive-2 ul.views-summary li').append('&nbsp;<img alt="plus-icon" style="vertical-align:-9%;" src="/themes/fairmont/images/link-list.png" border=0 width="12" height="12" />');
  }  
  
  //console.log($('.menu-block-1').children());
  if ($('.pane-block-12 > h2').length>0 && $('.pane-block-12 > h2 > img').length==0){
    if ($('.pane-block-12 a:eq(0) img').length>0) {
      $('.pane-block-12 a:eq(0)').remove().prependTo('.pane-block-12 > h2');
    } else {
      $('.pane-block-12 img:eq(0)').remove().prependTo('.pane-block-12 > h2');
    }
  }
  if ($('a.link_button').length>0){
    $('a.link_button').removeClass('link_button').wrap('<span class="link_button"></span>');
  }

  if ($('#mediaPageCarouselSlideshow').length>0)  
    var cat = self.document.location.hash.substring(1);
    if (cat > '') {
      var startIdx = 0; 
      $('#mediaPageCarouselSlideshow img').each(function(){
        if (startIdx == 0 && $(this).hasClass(cat)) {
          //alert(cat + ' -> ' + $("#mediaPageCarouselSlideshow").index(this));
          var newIdx = $("#mediaPageCarouselSlideshow img").index(this);
          if (newIdx > 0) {
            startIdx = newIdx;
          }
        }
      });
    }
    $('#mediaPageCarouselSlideshow').cycle({
      fx:      'fade',
      startingSlide: startIdx,
      timeout:  10000,
      before: onBefore,
      pager:   '#navMediaPageCarousel',
      pagerAnchorBuilder: function (idx, slide) {
        return '<li><a href="#" class="indicator"></a></li>';
      }
  });
   
  function onBefore(curr, next, opts) {
    $('#navMediaPageCarouselCategory a').removeClass('active');
    $('#navMediaPageCarouselCategory a#' + $(next).attr('class') + 'CategoryContainer').addClass('active');
  };
  
  if ($('#springboard_info').length>0 && $('#springboard_dialog').length>0){
    $( "#springboard_dialog" ).dialog({ autoOpen: false });
    $('#springboard_info').click(function(){
      $( "#springboard_dialog" ).dialog('open');
    });
  }
  
  // fix some weird IE issues
  if ($.browser.msie){
    $('block-block-1').css('height', '220px');
    $('#home_wrapper .panel-panel .pane-block-6, #home_wrapper .panel-panel .pane-block-10').css('width', '200px').css('height', '230px');
    $(".pane-block-6 .pane-content p").each(function(){
      if ($(this).html()=='&nbsp;'){
        $(this).css('height', '6px');
      }
    });
    if ($.browser.version=='8.0'){
      //$('#block-block-2').css('position', 'relative').css('top', '-78px').css('right', '0');
    }
    else if ($.browser.version=='7.0'){
      $('#home_wrapper .pane-block-8').css('height', '71px');
      $('#home_wrapper .pane-block-8 .pane-content').css('height', '68px');
      $('#home_wrapper .pane-block-8 .pane-content table').css('height', '60px');
      $('#footer-wrapper').css('height', '375px');
      $('#footer').css('height', '280px');
      $('#block-block-1').css('height', '260px');
    }
  }
  
  // add google tracking code
  $('#simplenews-exclusives-subscribe-form input.form-submit').click(function(){
    var selectedCountry = $( 'select#edit-country option:selected' ).text();
    var selectedPostal = $('input#edit-postal-code').val();   
    var userDetails = 'Postal Code:' + selectedPostal + '; Country:' + selectedCountry;
    _gaq.push(['_setCustomVar', 2, 'Email Subscriber', userDetails, 1]); 
    _gaq.push(['_trackPageview', '/email-exclusives-complete']);
  });
  $('#simplenews-legend-subscribe-form input.form-submit').click(function(){
    _gaq.push(['_trackPageview', '/legend/register-complete']);
  });
  $('#simplenews-loyalty-subscribe-form input.form-submit').click(function(){
    _gaq.push(['_trackPageview', '/family-first-loyalty-program/register-complete']);
  });
  $('#simplenews-realty-subscribe-form input.form-submit').click(function(){
    _gaq.push(['_trackPageview', '/real-estate/register-complete']);
    //var $conversionId = '975294310'; //not used
    //var $label = 'J14VCLql0wIQ5p6H0QM'; //not used
    //var $url = 'http://www.googleadservices.com/pagead/conversion/975294310/?label=J14VCLql0wIQ5p6H0QM&amp;guid=ON&amp;script=0';
    //LoadImageForTracking($url);
  });
  $('#user-login-form input.form-submit').click(function(){
    _gaq.push(['_trackPageview', '/sign-in-complete']);
  });
  $('#user-register input.form-submit').click(function(){
    var iSelectedGender = $('input[name="gender"]:checked').val();
    if (iSelectedGender == '1'){
      var selectedGender = 'Male';
    }else{
      var selectedGender = 'Female';
    }
    var selectedDOB = $('input#edit-birth-date').val();   
    var userDetails = 'Gender:' + selectedGender + '; Date of Birth:' + selectedDOB;
    _gaq.push(['_setCustomVar', 1, 'Registered User', userDetails, 1]); 
    _gaq.push(['_trackPageview', '/sign-up-complete']);
  });
  $('#print-mail-form input#edit-btn-submit').click(function(){
    _gaq.push(['_trackPageview', '/emailpage-complete']);
  });
  $('#book-tee-time input[type="submit"]').click(function(){
    _gaq.push(['_trackPageview', '/golfteetime-search']);
  });
  $('a[href*="reseze.net"]').click(function(){
    _gaq.push(['_link', $(this).attr('href')]);
    return false;
  });
  $('a[href^="/print/"]').click(function(){
    _gaq.push(['_trackEvent', 'printpage', 'linkclick', $('h2').text()]);
    window.open(this.href);
    return false;
  });
  
  $("img[src*='2011-tourArts-Promo']").parent("a[href='/node/']").attr('href', 'http://www.facebook.com/pages/Tour-of-the-Arts-2011/141312129259540').attr('target', '_blank');
  
  if ($('#photogallery').length>0){
    // $('#photogallery a').lightBox();
    // pagination
    var prev = {start: 0, stop: 0},
    perPage = 20;
    cont = $('#photogallery ul li');
    if (cont.length > perPage) {
      var Paging = $(".pagination").paging(cont.length, {
        format: '[< ncnnnnnnnn >]',
        perpage: perPage,
        lapping: 0,
        page: 1,
        onSelect: function (page) {
          var data = this.slice;
          cont.slice(prev[0], prev[1]).css('display', 'none');
          cont.slice(data[0], data[1]).fadeIn( 1500 );
          prev = data;
          return false;
        },
        onFormat: function (type) {
          switch (type) {
          case 'block': // n and c
            if (!this.active)
              return '<span class="disabled">' + this.value + '</span>';
            else if (this.value != this.page)
              return '<a href="#' + this.value + '">' + this.value + '</a>';
            return '<span class="current">' + this.value + '</span>';
            //return '<a>' + this.value + '</a>';
          case 'next': // >
            return '<a>next &#8594;</a>';
          case 'prev': // <
            return '<a>&#8592; prev</a>';
          case 'first': // [
            return '';
          case 'last': // ]
            return '';
          }
        }
      });
    }
    else {
      $('#photogallery ul li').css('display', 'inline-block');
    }
  }
  
  if ($('#weatherTabsWrapper').length>0) {
    try {
      $('#weatherTabs').load("/weather-widget.php", {}, function(data) {
        //alert("Data Loaded: " + data);
        if (data.length<100 || data.indexOf("page not found")>0) {
         $('#weatherTabs').html("<p style='margin:10px'>Feed is currently unavailable.</p>");
        }
      });
    }
    catch(e) {
      // alert(e.message);
      // displays a message 
      $('#weatherTabs').html("<p style='margin:10px'>Feed is currently unavailable.</p>");
    }
  }    
  
});

function addActivity(aid){
  $.get("/my-springboard/add/" + aid);
  alert('Activity has been added to your springboard.');
  return false;
}

function gotoSlide(idx) {
  if (idx >= 0) {
    $('#mediaPageCarouselSlideshow').cycle(idx);
  }
  return false;
};

$(document).ready(function() {
  $('.vacationBookingRequest').click(function() {
    var $conversionId = '975294310'; //not used
    var $label = 'BQcSCLq55wIQ5p6H0QM'; //not used
    var $url = 'http://www.googleadservices.com/pagead/conversion/975294310/?label=BQcSCLq55wIQ5p6H0QM&amp;guid=ON&amp;script=0';
    LoadImageForTracking($url);
    return true;
  });

  $('.campingBookingRequest').click(function() {
    var $conversionId = '975294310'; //not used
    var $label = 'JASKCKK85wIQ5p6H0QM'; //not used
    var $url = 'http://www.googleadservices.com/pagead/conversion/975294310/?label=JASKCKK85wIQ5p6H0QM&amp;guid=ON&amp;script=0';
    LoadImageForTracking($url);
    return true;
  });

  $('.golfBookingRequest').click(function() {
    var $conversionId = '975294310'; //not used
    var $label = 'C6NaCKq75wIQ5p6H0QM'; //not used
    var $url = 'http://www.googleadservices.com/pagead/conversion/975294310/?label=C6NaCKq75wIQ5p6H0QM&amp;guid=ON&amp;script=0';
    LoadImageForTracking($url);
    return true;
  });


  $('.spaBookingRequest').click(function() {
    var $conversionId = '975294310'; //not used
    var $label = 's01ICNKViwMQ5p6H0QM'; //not used
    var $url = 'http://www.googleadservices.com/pagead/conversion/975294310/?label=s01ICNKViwMQ5p6H0QM&amp;guid=ON&amp;script=0';
    LoadImageForTracking($url);
    return true;
  });

});

function LoadImageForTracking($url)
{
  var image = new Image(1,1);
  image.src = $url
  return true;
}

