// Dealer Locator Mapping
// Teneleven Interactive

//window.onload = init;
window.onresize = handleResize;
try{}catch(e){googleError();}

var geocoder, objMap, map, manager, bounds;
var centerLatitude = 32.7, centerLongitude = -117.16, startZoom = 11;

$(document).ready(function(){
  $("input").bind("keypress", function(e) {
    var code=e.charCode || e.keyCode;
    if(code==13){
      searchLocations($('#addressInput').val(),$('#radiusSelect').val(),$('#phone').val());
    }
  });

});

function init() {
  handleResize();
  try{
    geocoder = new GClientGeocoder();
    objMap = document.getElementById("map"); // Google Maps does not like jQuery objects as targets
    map = new GMap2(objMap);
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
    var controlLocation = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(6,10));
    var labelLocation = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(50,5));
    var zoomLocation = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(6,20));
    map.addControl(new GMapTypeControl(), controlLocation);
    map.addControl(new GSmallZoomControl3D(),zoomLocation);
    map.addControl(new GNavLabelControl(),labelLocation);
    
    dealerTip = document.createElement("div");
    map.getPane(G_MAP_FLOAT_PANE).appendChild(dealerTip);
    bounds = new GLatLngBounds();
    manager = new GMarkerManager(map);
    window.onunload = GUnload;
  }catch(e){googleError();}
}

function handleResize() {
  var height = $(window).height()-117;
  $('#mapWrapper').css('height',height);
  $('#fadeOverlay').css('height',height+3);
  $('#map').css('height',height);
  $('#sidebar').css('height',height-136);
}

function searchLocations(address,radius,phone){
	$('#phone').val("");
  showLocalRetailers();
  init();
  geocoder.getLatLng(address,function(latlng){
    if (!latlng) {
      googleError();
    } else {
      $('#sidebar-list').empty();
      var listItem = document.createElement('li');
      var html = '<h3><strong>Searching for retailers.</strong></h3>';
      listItem.innerHTML = html;
      $('#sidebar-list').append(listItem);
      getMarkers('dealerXML.php?lat=' + latlng.lat() + '&lng=' + latlng.lng() + '&radius=' + radius + '&p=' + phone);
    }
  });
}

function getMarkers(searchUrl){
  $.ajax({
    url: searchUrl,
    dataType: 'xml',
    success: processMarkers
  });
}

function processMarkers(responseXML){
  $('#sidebar-list').empty();
  batch = [];
  $(responseXML).find("marker").each(function() {
    batch.push(createMarker($(this)));
  });

  if (batch.length>0){
	if (batch.length>1){
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}else{
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-3);	
	}
    manager.addMarkers(batch, 1);
    manager.refresh();

  }else{
	//showDefaultRetailers();
    var listItem = document.createElement('li');
    var html = '<h3><strong>No retailers found within ' + $('#radiusSelect').val() + ' miles of ' + $('#addressInput').val() + '.</strong></h3><br>';
    html += 'Please expand your range, or enter a new address or zip code.';
    listItem.innerHTML = html;
    $('#sidebar-list').append(listItem);
  }
}

function showLocalRetailers(){
  	$('#onlineDealers').css('display','none');
  	$('#localDealers').css('display','none');
  	$('#internationalDealers').css('display','none');
  	$('#otherDealers').css('display','block');
	$('#fadeOverlay').css('display','block');
	$('#sidebar').css('display','block');
	$('#mapWrapper').css('display','block');
}

function showDefaultRetailers(){
  	$('#onlineDealers').css('display','block');
  	$('#localDealers').css('display','block');
  	$('#internationalDealers').css('display','block');
  	$('#otherDealers').css('display','none');
	$('#fadeOverlay').css('display','none');
	$('#sidebar').css('display','none');
	$('#mapWrapper').css('display','none');
}

function createMarker(pointData) {
  var latlng = new GLatLng(pointData.attr('lat'), pointData.attr('lng'));
  var icon = new GIcon();
  icon.image = '/images/map/1pxt.png';
  icon.iconSize = new GSize(20, 20);
  icon.iconAnchor = new GPoint(10, 10);
  opts = {
    "icon": icon,
    "labelText": pointData.attr('index'),
    "labelOffset": new GSize(-10,-10)
  };
  
  // Map Marker
  var marker = new LabeledMarker(latlng, opts);
  marker.dealerTip = '<div class="dealerTip"><div class="window"><table><tr><td class="left">&nbsp;</td><td class="mid">'+pointData.attr('name')+'</td><td class="right">&nbsp;</td></tr></table></div></div>';
  
  // Sidebar List Item
  var listItem = document.createElement('li');
  listItem.id = 'entry' + pointData.attr('index');
  
  var html = '<div style="float:right"><strong>' + parseFloat(pointData.attr('distance')).toFixed(1) + 'miles</strong><br><a onclick="getDirections(\'' + pointData.attr('address') +'\', \'' + listItem.id +'\');$(this).remove();">Get Directions</a></div>';
  html += '<h3><div class="labeledMarker">' + pointData.attr('index') + '</div><strong>' + pointData.attr('name') + '</strong></h3><br>' + pointData.attr('address') + '<br>';
  if(pointData.attr('phone')!=''){html += 'Phone: ' + pointData.attr('phone');}
  html +="<span class='clear'>&nbsp;</span>";
  
  listItem.innerHTML = html;
  $('#sidebar-list').append(listItem);

  GEvent.addListener(marker, "mouseover", function() {
    showDealerTip(marker);
    rowHover(listItem);
  });
  GEvent.addListener(marker, "mouseout", function() {
    rowOut(listItem);
    dealerTip.style.visibility="hidden"
  });
  GEvent.addListener(marker, "click", function() {
    centerZoom(latlng);
  });
  
  
  GEvent.addDomListener(listItem, "mouseover", function() {
    showDealerTip(marker);
    rowHover(listItem);
  });
  GEvent.addDomListener(listItem, "mouseout", function() {
    rowOut(listItem);
    dealerTip.style.visibility="hidden"
  });
  GEvent.addDomListener(listItem, "click", function() {
    centerZoom(latlng);
  });
  
  bounds.extend(latlng);
  return marker;
}

function showDealerTip(marker) {
	dealerTip.innerHTML = marker.dealerTip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(13,-4),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=dealerTip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 

	pos.apply(dealerTip);
	dealerTip.style.visibility="visible";
}

function rowHover(target) {
	$(target).addClass("hovered");
}
function rowOut(target) {
	$(target).removeClass("hovered");
}

function centerZoom(latlng){
  map.panTo(latlng);
}

function getDirections(address,element){
  directionsPanel = document.getElementById(element);
  directions = new GDirections(map, directionsPanel);
  directions.clear();
  directions.load("from: " + $('#addressInput').val() + "  to: " + address)
  
}

function googleError(){
  var listItem = document.createElement('li');
  var html;
  if($('#addressInput').val()=="Address or ZIP Code"){
    html = '<h3><strong>No Address or ZIP Code entered.</strong></h3><br>';
    html += 'Please enter an Address or ZIP Code above and try again.';   
  }else{
    html = '<h3><strong>There may be a problem with Google Maps or your address could not be found.</strong></h3><br>';
    html += 'If this is the correct address, please try your search again in 30 seconds.';
  }
  listItem.innerHTML = html;
  $('#sidebar-list').append(listItem);
}

/*
* LabeledMarker Class
*
* Copyright 2007 Mike Purvis (http://uwmike.com)
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class extends the Maps API's standard GMarker class with the ability
* to support markers with textual labels. Please see articles here:
*
*       http://googlemapsbook.com/2007/01/22/extending-gmarker/
*       http://googlemapsbook.com/2007/03/06/clickable-labeledmarker/
*/
try{
function LabeledMarker(latlng, options){
    this.latlng = latlng;
    this.labelText = options.labelText || "";
    this.labelClass = options.labelClass || "markerLabel";
    this.labelOffset = options.labelOffset || new GSize(0, 0);    
    this.clickable = options.clickable || true;
    if (options.draggable) {options.draggable = false;}
    GMarker.apply(this, arguments);
}

LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

LabeledMarker.prototype.initialize = function(map) {
	GMarker.prototype.initialize.apply(this, arguments);
	
	var div = document.createElement("div");
	div.className = this.labelClass;
	div.innerHTML = this.labelText;
	div.style.position = "absolute";
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);

	if (this.clickable) {
		// Pass through events fired on the text div to the marker.
		var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
		for(var i = 0; i < eventPassthrus.length; i++) {
			var name = eventPassthrus[i];
			GEvent.addDomListener(div, name, newEventPassthru(this, name));
		}
		div.style.cursor = "pointer";
	}
	this.map = map;
	this.div = div;
}

function newEventPassthru(obj, event) {
	return function() { 
		GEvent.trigger(obj, event);
	};
}

LabeledMarker.prototype.redraw = function(force) {
	GMarker.prototype.redraw.apply(this, arguments);
	if (!force) return;

	var p = this.map.fromLatLngToDivPixel(this.latlng);
	var z = GOverlay.getZIndex(this.latlng.lat());

	this.div.style.left = (p.x + this.labelOffset.width) + "px";
	this.div.style.top = (p.y + this.labelOffset.height) + "px";
	this.div.style.zIndex = z + 1; // in front of the marker
}

LabeledMarker.prototype.remove = function() {
	GEvent.clearInstanceListeners(this.div);
	this.div.parentNode.removeChild(this.div);
	this.div = null;
	GMarker.prototype.remove.apply(this, arguments);
}
}catch(e){}