﻿var _MINIMUM_FONT_SIZE = 10;
var _DEFAULT_FONT_SIZE = 12;
var _MAXIMUM_FONT_SIZE = 16;

jQuery(document).ready(function()
{
    var temp = jQuery;
    jQuery = jQuery;
    // Load the default font-size from the cookie
    var fontsize = jQuery.cookie('customfontsize');
    if (fontsize == null) {
        fontsize = _DEFAULT_FONT_SIZE;
    }
    jQuery('.resize').css('font-size', (fontsize + 'px'));

    // Increase Font Size
    jQuery(".increaseFont").click(function()
    {
        var currentFontSize = jQuery('.resize').css('font-size');
        var finalNum = parseFloat(currentFontSize, 10);
        var stringEnding = currentFontSize.slice(-2);
        var newFontSize = finalNum + 1;
        if (newFontSize > _MAXIMUM_FONT_SIZE) {
            newFontSize = _MAXIMUM_FONT_SIZE;
        }
        jQuery('.resize').css('font-size', (newFontSize + stringEnding));
        // set the new font size in the cookie
        jQuery.cookie('customfontsize', newFontSize, { expires: 365 });
        return false;
    });

    // Decrease Font Size
    jQuery(".decreaseFont").click(function()
    {
        var currentFontSize = jQuery('.resize').css('font-size');
        var finalNum = parseFloat(currentFontSize, 10);
        var stringEnding = currentFontSize.slice(-2);
        var newFontSize = finalNum - 1;
        if (newFontSize < _MINIMUM_FONT_SIZE) {
            newFontSize = _MINIMUM_FONT_SIZE;
        }
        jQuery('.resize').css('font-size', (newFontSize + stringEnding));
        // set the new font size in the cookie
        jQuery.cookie('customfontsize', newFontSize, { expires: 365 });
        return false;
    });

    // Mouse out of a location item
//    jQuery(".LocationItem").mouseover(function()
//    {
//        jQuery(this).addClass("Hover");
//    });

//    // Mouse out of a location item
//    jQuery(".LocationItem").mouseout(function()
//    {
//        jQuery(this).removeClass("Hover");
//    });

//    // Click on a location item
//    jQuery(".LocationItem").click(function()
//    {
//        jQuery(".LocationItem.Active").removeClass("Active");
//        jQuery(".LocationItem.Hover").removeClass("Hover");
//        jQuery(this).addClass("Active");
//    });
    jQuery = temp;
});

function searchFocus(box, text) {
  if (box.value == text) {
    box.value = '';
  }
}

function searchBlur(box, text) {
  if (box.value == '') {
    box.value = text;
  }
}

////////////////////////////////////////////////////////////////////
// GOOGLE MAPS
////////////////////////////////////////////////////////////////////

var map = null;
var bounds = null;
var gdir = null;
var gmarkers = [];
var htmls = [];

function isPrintView() {
  var div = document.getElementById("printwrapper");
  return div != null;
}

function initGoogleMap(map_div) {
  if (true) {
    var div = document.getElementById(map_div);
    if (div != null) {
      map = new GMap2(div);
      //map.setCenter(new GLatLng(38.5070010, -95.6379010), 4);
      map.enableScrollWheelZoom();

      if (!isPrintView()) {
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableInfoWindow();
      }
    }
  }
}

function getLocations(searchUrl) {
  if (map != null) {
    map.clearOverlays();
    GDownloadUrl(searchUrl, function(data, responseCode) { populateMap(data, responseCode); });
  }
}

function populateMap(data, responseCode) {
  if (responseCode == 200) {
    var locations = getLocationsFromXML(data);
    var entries = getEntriesFromLocations(locations);

    if (entries.length > 0) {   // Results were found            
      bounds = new GLatLngBounds();

      for (var i in entries) {
        var entry = entries[i];
        var marker = entry.marker;

        // Update bounds
        bounds.extend(marker.getLatLng());
        // Add marker to map
        map.addOverlay(marker);
      }
      map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }

    if (typeof onMapLoadComplete == 'function') {
      onMapLoadComplete();
    }

    // create a GDirections Object ===
    gdir = new GDirections(map, document.getElementById("directions"));

    // === Array for decoding the failure codes ===
    var reasons = [];
    reasons[G_GEO_SUCCESS] = "Success";
    reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST] = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY] = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

    // === catch Directions errors ===
    GEvent.addListener(gdir, "error", function() {
      var code = gdir.getStatus().code;
      var reason = "Code " + code;
      if (reasons[code]) {
        reason = reasons[code]
      }

      alert("Failed to obtain directions, " + reason);
    });
  }
}

function getEntriesFromLocations(locations) {
  var entries = new Array();

  for (var i = 0; i < locations.length; i++) {
    var id = locations[i].getAttribute('id');
    var name = locations[i].getAttribute('name');
    var address2 = locations[i].getAttribute('address2');
    var address3 = locations[i].getAttribute('address3');
    var address4 = locations[i].getAttribute('address4');
    var city = locations[i].getAttribute('city');
    var state = locations[i].getAttribute('state');
    var zip = locations[i].getAttribute('zip');
    var phone = locations[i].getAttribute('phone');
    var distance = parseFloat(locations[i].getAttribute('distance'));
    var icon = locations[i].getAttribute('icon');
    var latitude = parseFloat(locations[i].getAttribute('latitude'));
    var longitude = parseFloat(locations[i].getAttribute('longitude'));

    var point = new GLatLng(latitude, longitude);
    var marker = createMarker(point, id, name, icon, address2, address3, address4, city, state, zip, phone);


    var entry = new Object();
    entry.marker = marker;

    entries.push(entry);
  }

  return entries;
}

function getLocationsFromXML(data) {
  var xml = GXml.parse(data);
  return xml.documentElement.getElementsByTagName('location');
}

function createMarker(point, id, name, icon, address2, address3, address4, city, state, zip, phone) {   // Create our custom marker
  var markerIcon = new GIcon();
  if (icon != null) {
    markerIcon.image = icon;
    markerIcon.printImage = icon;
    markerIcon.mozPrintImage = icon;
  }

  markerIcon.iconSize = new GSize(15, 23);
  markerIcon.iconAnchor = new GPoint(8, 23);
  markerIcon.infoWindowAnchor = new GPoint(8, 23);
  markerIcon.shadow = WEB_ROOT + '/Images/map/shadow.gif';
  markerIcon.shadowSize = new GSize(27, 23);
  markerIcon.shadowAnchor = new GPoint(10, 23);

  var markerOptions = { icon: markerIcon, title: name };
  var marker = new GMarker(point, markerOptions);

  if (!isPrintView()) {
    // create balloon info
    var balloonInfo = createMarkerBalloonInfo(point, id, name, icon, address2, address3, address4, city, state, zip, phone);

    // List marker
    var img = document.getElementById("sidebar_img." + id);
    if (img != null) {
      // Link image click event to marker
      GEvent.addDomListener(img, 'click', function() {
        GEvent.trigger(marker, 'click');
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        map.setMapType(G_NORMAL_MAP);
        gdir.clear();
      });

      // Add balloon info to marker
      //jQuery(".LocationItem.Active").removeClass("Active"); jQuery(".LocationItem.Hover").removeClass("Hover"); jQuery(("#" + id)).addClass("Active");
      GEvent.addListener(marker, 'click', function() { marker.openInfoWindow(balloonInfo); img.scrollIntoView(true); });
    }
    else {
      GEvent.addListener(marker, 'click', function() { marker.openInfoWindow(balloonInfo); });
    }

    // List address
    var div = document.getElementById("sidebar." + id);
    if (div != null) {
      // Link div click event to marker
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        map.setMapType(G_NORMAL_MAP);
        gdir.clear();
      });
    }

    // List select link
    var link = document.getElementById("sidelink." + id);
    if (link != null) {
        // Link anchor click event to zoom into the location
        GEvent.addDomListener(link, 'click', function() { map.setCenter(point, 17, G_HYBRID_MAP); img.scrollIntoView(true) });
    }
    else {
        GEvent.addListener(marker, 'click', function() { marker.openInfoWindow(balloonInfo); });
    }
  }

  gmarkers.push(marker)
  return marker;
}

function createMarkerBalloonInfo(point, id, name, icon, address2, address3, address4, city, state, zip, phone) {   // Create marker balloon info
  var i = gmarkers.length;
  
  // retrieve the div containing item template
  var templateDiv = document.getElementById("balloonInfoTemplate");
  var template = templateDiv.innerHTML;
  var templateWdirections = '';

  // perform replacements on template
  template = template.replace("{id}", id);
  template = template.replace("{name}", name);
  template = template.replace("{address2}", address2);
  template = template.replace("{address3}", address3);
  template = template.replace("{address4}", address4);
  template = template.replace("{city}", city);
  template = template.replace("{state}", state);
  template = template.replace("{zip}", zip);
  template = template.replace("{phone}", !phone ? '' : phone);

  templateWdirections = template;
  
  // link to open the directions form
  template = template.replace("{directions}", '<a href="javascript:showDirectionsForm(' + i + ')">Get Directions To here</a>');

  var div = document.createElement("div");
  div.innerHTML = template;

  // directions form
  var directionTemplate =
           '<form action="javascript:getDirections(' + id + ')">' +
           'Start address:<br />' +
           '<input type="text" maxlength="40" name="saddr" id="saddr' + id + '" value="" style="width:210px;" /><br />' +
           '<input value="Get Directions" type="submit"><br />' +
           '<input type="hidden" id="daddr' + id + '" value="' + name + "@" + point.lat() + ',' + point.lng() +
           '"/>';

  templateWdirections = templateWdirections.replace("{directions}", directionTemplate);

  // add the directions html to the array so we can get it later
  htmls[i] = templateWdirections;

  return div;
}

// request the directions
function getDirections(id) {
  var opts = {};

  // ==== set the start and end locations ====
  var saddr_id = 'saddr' + id;
  var daddr_id = 'daddr' + id;
  var saddr = document.getElementById(saddr_id).value
  var daddr = document.getElementById(daddr_id).value
  gdir.load("from: " + saddr + " to: " + daddr, opts);
}

function showDirectionsForm(i) {
  gmarkers[i].openInfoWindowHtml(htmls[i]);
}

jQuery(function()
{
    jQuery('#understanding').hover(function()
    {
        jQuery(this).addClass('understandingImage');
    }, function()
    {
        jQuery(this).removeClass('understandingImage');
    });
});

jQuery(function()
{
    jQuery('#innerunderstanding').hover(function()
    {
        jQuery(this).addClass('innerunderstandingImage');
    }, function()
    {
        jQuery(this).removeClass('innerunderstandingImage');
    });
});

jQuery(function()
{
    jQuery('.navItemRollover').hover(function()
    {
        jQuery(this).addClass('over');
    }, function()
    {
        jQuery(this).removeClass('over');
    });
});

jQuery(function()
{
    jQuery('.navItemRolloverImage').hover(function()
    {
        jQuery(this).addClass('overImage');
    }, function()
    {
        jQuery(this).removeClass('overImage');
    });
});

jQuery(function()
{
    jQuery('#pros').hover(function()
    {
        jQuery(this).addClass('prosImage');
    }, function()
    {
        jQuery(this).removeClass('prosImage');
    });
});

jQuery(function()
{
    jQuery('#innerpros').hover(function()
    {
        jQuery(this).addClass('prosImage');
    }, function()
    {
        jQuery(this).removeClass('prosImage');
    });
});