$(function () {
  // Make external links open in new window
  $('a[href^=http]').click(function () {
    window.open(this.href);
    return false;
  });
});

$(document).ready(function () {

  // Set preferred stylesheet
  var cookie = readCookie('style');
  if (cookie != '') {
    var title = cookie ? cookie : getPreferredStyleSheet();
    setActiveStyleSheet(title);
  };

  // Sub-menu
  $("#nav > li").hover(function () {
    $(this).find("ul").stop(true, true).fadeIn(300);
  }, function () {
    $(this).find("ul").stop(true, true).fadeOut(300);
  });

  // Highlight active menu section
  var filePath = window.location.pathname;
  var fileName = filePath.substr(filePath.lastIndexOf("/") + 1);
  $("#nav > li > a").each(function () {
    var child = $(this);
    if (child.attr("href") == fileName) { child.attr('class', 'selected') } else {
      child.next().find("a").each(function () {
        if ($(this).attr("href") == fileName) { child.attr('class', 'selected'); };
      })
    }
  });

  // Start vertical news ticker
  var pathname = window.location.pathname;
  if (pathname.indexOf("admin") <= 0) {
    $('.ticker').vTicker({
      speed: 500,
      pause: 4000,
      animation: 'fade',
      mousePause: true
    });
    $('#s').watermark('search');
  };

  // Google Site Search
  var config = {
    siteURL: 'nestor-healthcare.co.uk', // Change this to your site
    searchSite: true,
    type: 'web',
    append: false,
    perPage: 8, 		// A maximum of 8 is allowed by Google
    page: 0				// The start page
  }

  $('#submitButton').click(function () {
    googleSearch();
    return false;
  });

  function googleSearch(settings) {
    settings = $.extend({}, config, settings);
    settings.term = settings.term || $('#s').val();
    settings.term = 'site:' + settings.siteURL + ' ' + settings.term;
    var apiURL = 'http://ajax.googleapis.com/ajax/services/search/' + settings.type + '?v=1.0&callback=?';
    var resultsDiv = $('#resultsDiv');
    var sTerm = $('#s').val();

    $.getJSON(apiURL, { q: settings.term, rsz: settings.perPage, start: settings.page * settings.perPage }, function (r) {
      var results = r.responseData.results;
      $('#more').remove();
      if (results.length) {
        // If results were returned, add them to a pageContainer div, after which append them to the #resultsDiv:
        var pageContainer = $('<div class="pageContainer">');
        pageContainer.append('<h1>Your search results for the term "' + sTerm + '"...</h1>')

        for (var i = 0; i < results.length; i++) {
          // Creating a new result object and firing its toString method:
          pageContainer.append(new result(results[i]) + '');
        }

        if (!settings.append) {
          // This is executed when running a new search instead of clicking on the More button:
          resultsDiv.empty();
        }
        pageContainer.append('<div class="clear"></div>')
							 .hide().appendTo(resultsDiv)
							 .fadeIn('slow')
                .click(function () {
                  $(this).fadeOut();
                })

        var cursor = r.responseData.cursor;

        // Checking if there are more pages with results and deciding whether to show the More button:
        if (+cursor.estimatedResultCount > (settings.page + 1) * settings.perPage) {
          $('<div>', { id: 'more' }).appendTo(resultsDiv).click(function () {
            googleSearch({ append: true, page: settings.page + 1 });
            $(this).fadeOut();
          });
        }
      }
      else {
        // No results were found for this search.
        resultsDiv.empty();
        $('<h1>', { className: 'notFound', html: 'Sorry, no results found!<div class="clear"></div>' }).hide().appendTo(resultsDiv).fadeIn().click(function () {
          $(this).fadeOut();
        });
      }
    });
  }

  function result(r) {
    var arr = [];
    arr = [
					'<div class="webResult">',
					'<h3><a href="', r.unescapedUrl, '" target="_blank">', r.title, '</a></h3>',
					'<p>', r.content, '</p>',
					'<a href="', r.unescapedUrl, '" target="_blank">', r.visibleUrl, '</a>',
					'</div>'
				];
    this.toString = function () {
      return arr.join('');
    }
  }
});


// Google mapping
google.load('search', '1');

function loadGoogleMap(postcode) {
  var localSearch = new google.search.LocalSearch();
  if (GBrowserIsCompatible()) {
    // LEAVE 3 SECONDS TO ENSURE PAGE FULLY LOADED
    setTimeout(function () { usePointFromPostcode(postcode, setCenterToPoint, localSearch) }, 3000);
  }
}

function usePointFromPostcode(postcode, callbackFunction, localSearch) {
  localSearch.setSearchCompleteCallback(null, function () {
    if (localSearch.results[0]) {
      var resultLat = localSearch.results[0].lat;
      var resultLng = localSearch.results[0].lng;
      var point = new GLatLng(resultLat, resultLng);
      callbackFunction(point);
    } else {
      alert("Postcode not found!");
    }
  });
  localSearch.execute(postcode + ", UK");
}

function setCenterToPoint(point) {
  var map = new GMap2(document.getElementById("map"));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(point, 12, G_NORMAL_MAP);
  var marker = new GMarker(point);
  map.addOverlay(marker);
}

// Resize text
function setActiveStyleSheet(title) {
  var i, a, main;
  for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel").indexOf("style") != -1
      && a.getAttribute("title")) {
      a.disabled = true;
      if (a.getAttribute("title") == title) a.disabled = false;
    }
  }
}
function getActiveStyleSheet() {
  var i, a;
  for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel").indexOf("style") != -1
  && a.getAttribute("title")
  && !a.disabled) return a.getAttribute("title");
  }
  return null;
}
function getPreferredStyleSheet() {
  var i, a;
  for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

// Cookies
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}
function eraseCookie(name) {
  createCookie(name, "", -1);
}

// Save preferred stylesheet on exit
window.onunload = function (e) {
  var title = getActiveStyleSheet();
  createCookie('style', title, 365);
}

// Get querystring parameter
function getParameterByName(name) {
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}



