$(document).ready(function () {
  InitializeNavigation();
  InitFooterAndFormLinks();

  // If page has Google Map then run the map script
  if ($('#googleMapPlaceHolder').length) {
    InitializeGoogleMap();
  }

  $('div#contactContainer div.wrapper div').hover(
        function () {
          $(this).addClass('highlighted').find('h3, a').addClass('highlighted');
        },
        function () {
          $(this).removeClass('highlighted').find('h3, a').removeClass('highlighted');
        }
    );

  // Adds highlighted class to every element that has the hover class
  $('.hover').hover(
        function () {
          $(this).addClass('highlighted');
        },
        function () {
          $(this).removeClass('highlighted');
        }
    );

  // Add class "last" to all macthing this last selector
  $('div#articleArea div#latestNews div.newsItem').last().addClass('last');

  if ($('.datepicker').length) {
    $('.datepicker').datepicker({
      showAnim: 'slideDown',
      showOn: 'button',
      buttonImage: '/shared/css/datepicker/images/calendar.gif',
      buttonImageOnly: true,
      buttonText: 'Click to display date picker',
      dateFormat: 'dd/M/yy'
    });
  }

  $('#txtNameOrTrust, #txtProperty').click(function () {
    $(this).addClass('active');
  });

  $('div#unclaimedMoneySearchResults span.radio').live('click', function () {
    $('#unclaimedMoneySearchForm').submit();
  });

  $('#firstNameFilter, #lastNameFilter').click(function () {
    $('#unclaimedMoneySearchForm').submit();
  });

  $('#txtNameOrTrust, #txtProperty').blur(function () {
    var value = jQuery.trim($(this).val());
    if (value == 'Name or trust' || value == 'Property' || value == '') {
      $(this).removeClass('active');
    }
  });

  if ($('#unclaimedMoneySearchResults').length && $('.paginationIndex').length && typeof _gaq != 'undefined') {
    var resultCountRegEx = new RegExp(/\d+(?!.*\d)/);
    var resultCountStr = $('.paginationIndex').html().match(resultCountRegEx);
    var resultCountInt = -1;
    if (resultCountStr != null && !isNaN(resultCountStr)) {
      resultCountInt = parseInt(resultCountStr);
    }
    _gaq.push(['_trackEvent', 'Unclaimed Money', 'Search', 'Results', resultCountInt]);
  }

});   // close doc ready

// Functions

function GetQuerystringParams() {
  var urlParams = {};
  var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
    q = window.location.search.substring(1);

  while (e = r.exec(q)) {
    urlParams[d(e[1])] = d(e[2]);
    }
  return urlParams;
}

function InitFooterAndFormLinks() {
  $('#footerControl2').click(function (e) {
    e.preventDefault();
    if (typeof _gaq != 'undefined') {
      _gaq.push(['_trackEvent', 'Popup Form', 'Open', 'Update Your Contact Details']);
    }
    LoadAjaxForm('/ajax/' + $(this).attr('rel') + '/UpdateYourDetailsForm', 740);
  });

  $('#someoneYouKnow').click(function (e) {
    e.preventDefault();
    if (typeof _gaq != 'undefined') {
      _gaq.push(['_trackEvent', 'Popup Form', 'Open', 'Is This Someone You Know?']);
    }
    var params = GetQuerystringParams();
    LoadAjaxForm('/ajax/' + $(this).attr('rel') + '/IsThisSomeoneYouKnowForm?clientCode=' + params["clientCode"], 740);
  });

  $('#tellAFriend, #tellsOthers, #footerControl3').click(function (event) {
    event.preventDefault();
    if (typeof _gaq != 'undefined') {
      _gaq.push(['_trackEvent', 'Popup Form', 'Open', 'Tell Others About This Page']);
    }
    LoadAjaxForm('/ajax/' + $(this).attr('rel') + '/TellOthersAboutThisPage', 375);
  });

  $('#footerControl4').click(function (event) {
    event.preventDefault();
    window.print();
  });

  $('#isThisYou').click(function (event) {
    event.preventDefault();
    if (typeof _gaq != 'undefined') {
      _gaq.push(['_trackEvent', 'Popup Form', 'Open', 'Is This You?']);
    }
    var params = GetQuerystringParams();
    LoadAjaxForm('/ajax/' + $(this).attr('rel') + '/IsThisYouForm?clientCode=' + params["clientCode"], 740);
  });
}

function LoadAjaxForm(url, width) {
  $.fancybox({
    'href': url,
    'titleShow': false,
    'transitionIn': 'fade',
    'transitionOut': 'fade',
    'overlayColor': '#000',
    'overlayOpacity': 0.7,
    'width': width,
    'height': 'auto',
    'showCloseButton': false,
    'autoDimensions': false,
    'margin': 0,
    'padding': 0,
    'overflow': 'no'
  });
}

function ClearFormElement(element, label) {
  if ($(element).val() == label || $(element).val().indexOf(label) != -1) {
    $(element).val("");
  }
}

function RestFormElement(element, label) {
  if ($(element).val() == "") {
    $(element).val(label);
  }
}

function OpenGallery(galleryGroupName) {
  var galleryThumb = $('a.colorboxLink[rel="' + galleryGroupName + '"]:first');

  if (galleryThumb.length == 1) {
    galleryThumb.trigger("click");
  }
  return false;
}

function InitAjaxForm(nodeId) {
  $('#' + nodeId).find('form').ajaxForm({
    success:
        function (responseText, statusText) {
          $('#' + nodeId).html(responseText);
          $('.requiredFieldsNotice').hide();
        }
  });

  return false;
}
