<!-- main.js  -->

function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
                window.onload = func;
        }
        else {
                window.onload = function() {
                        oldonload();
                        func();
                }
        }
}

// A simple AJAX handler courtesy of Rasmus Lerdorf 2005-07-21
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sndReq(request) {
	http.open('get', request);
	http.onreadystatechange = handleResponse;
	http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();
		if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}

function changeDropoffDate(DateForm) {
	var pickup_day = document.getElementById("pickup_day").value;
	var pickup_month = document.getElementById("pickup_month").selectedIndex;
	var pickup_year;

	if (document.getElementById("pickup_year")) {
		pickup_year = document.getElementById("pickup_year").value;
	}
	else {
		var myDate=new Date();
		pickup_year = myDate.getFullYear();
	}

	var pickup_margin_el = document.getElementById("pickup_margin");
	var pickup_margin = 0;

	if (!pickup_margin_el) {
		pickup_margin = 86400000;
	}	
	else {
		pickup_margin = pickup_margin_el.value * 1000;
	}

	var pickupObj = new Date(pickup_year, pickup_month, pickup_day, 0, 0, 0);
	var pickup_ts = pickupObj.getTime();
	/* add in an aditional 61 minutes to the pickup margin to account for the daylights saving time switch */
	var dropoff_ts = pickup_ts + pickup_margin + 3660000;

	var myDateDropoff = new Date(dropoff_ts);

	var names = new Array();
	var values = new Array();

	// Set the element names and values.
	names['day'] = "dropoff_date[day]";
	names['month'] = "dropoff_date[month]";
	names['year'] = "dropoff_date[year]";
	values['day'] = myDateDropoff.getDate();
	values['month'] = myDateDropoff.getMonth() + 1;
	values['year'] = myDateDropoff.getFullYear();

	changeDate(DateForm, names, values);
}

function xxxxchangeDropoffDate(DateForm){
	var values = new Array();
	var names = new Array();
	var dropoff_day, dropoff_month, dropoff_year;
	pDay = DateForm.elements['pickup_date[day]'];
	pMonth = DateForm.elements['pickup_date[month]'];
	pYear = DateForm.elements['pickup_date[year]'];

	alert(pYear);

	// Calculate the dropoff values.
	day_sel = document.getElementById('pickup_day');
	month_sel = document.getElementById('pickup_month');
	dropoff_day = day_sel.selectedIndex + 2;
	dropoff_month = month_sel.options[month_sel.selectedIndex].value;
	
	if (pYear)
		dropoff_year = pYear.options[pYear.selectedIndex].value;

	// Adjust for overflow.
	if (dropoff_day > 31) {
		dropoff_day -= 31;
		dropoff_month++;
	}
	if (dropoff_month > 12) {
		dropoff_month -= 12;
		if (dropoff_year)
			dropoff_year++;
	}

	// Set the element names and values.
	names['day'] = "dropoff_date[day]";
	names['month'] = "dropoff_date[month]";
	names['year'] = "dropoff_date[year]";
	values['day'] = dropoff_day;
	values['month'] = dropoff_month;
	if (pYear)
		values['year'] = dropoff_year;

	changeDate(DateForm, names, values);
}

// Change the date elements to new values.
function changeDate(DateForm, names, values){
	var right_now=new Date();
	var sub_year = right_now.getYear() + 1900;
	if (DateForm.elements[names['year']]) {
		tempYear = values['year'];
		//DateForm.elements[names['year']].selectedIndex = values['year'] - sub_year;
		
		x = DateForm.elements[names['year']];
		for(i=0;i<x.length;i++) {
			if(x.options[i].value == values['year']) {
				//alert(x.options[i].value);
				x.options[i].selected = true;
				break;
			}
		}

	}

	DateForm.elements[names['month']].selectedIndex = values['month'] - 1;
	DateForm.elements[names['day']].selectedIndex = values['day'] - 1;
	// If we are changing the pickup, then update the dropoff.
	if (window.changeDropoffDate && (names['day'].indexOf('pickup') >= 0))
		changeDropoffDate(DateForm);
}

// Javascript for creating div popups

var divwidth='150px';
var divid = 'help';
var divbgcolor='lightyellow';
var disappeardelay=250;
var vertical_offset="-100px";
var horizontal_offset="-290px";

var ie4=document.all;
var ns6=document.getElementById&&!document.all;

function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}


function showhide(obj, e, visible, hidden, divwidth){
	if (ie4||ns6) dropmenuobj.style.left=dropmenuobj.style.top=-500
	if (divwidth!="")	{
		dropmenuobj.widthobj=dropmenuobj.style
		dropmenuobj.widthobj.width=divwidth
	}
	if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover") {
		obj.visibility=visible;
	} else if (e.type=="click") {
		obj.visibility=hidden;
	}
}

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
	var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
	if (whichedge=="rightedge"){
		var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
		dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
		if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)	{
			edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth;
		}
	}
	else{
		var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
		dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
		if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)	{
			edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight;
		}
	}
	return edgeoffset
}

function fixeddiv(menucontents, obj, e, divwidth, x_offset, y_offset, divid){
	
	if(y_offset != '') {
		vertical_offset = y_offset;
	}
	if(x_offset != '') {
		horizontal_offset = x_offset;
	}

	if (window.event) event.cancelBubble=true
	else if (e.stopPropagation) e.stopPropagation()
	clearhidediv()
	dropmenuobj=document.getElementById ? document.getElementById(divid) : divid
	dropmenuobj.innerHTML=menucontents

	if (ie4||ns6){
		showhide(dropmenuobj.style, e, "visible", "hidden", divwidth)

		dropmenuobj.style.top = '0px';
		dropmenuobj.style.top = (getposOffset(obj, "top") - getposOffset(dropmenuobj, "top") - 1) + 'px';
		
		dropmenuobj.style.left = '0px';
		dropmenuobj.style.left = (getposOffset(obj, "left") - getposOffset(dropmenuobj, "left") + 14) + 'px';
	}

}

function hidediv(e){
	if (typeof dropmenuobj!="undefined"){
		if (ie4||ns6){
			dropmenuobj.style.visibility="hidden";
		}
	}
}

function delayhidediv(){
	if (ie4||ns6) delayhide=setTimeout("hidediv()",disappeardelay)
}

function clearhidediv(){
	if (typeof delayhide!="undefined")
	clearTimeout(delayhide)
}

function couponWindow(info) {
	win = window.open(info, "couponWindow", "toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=no,resizable=yes,width=250,height=300,left=100,top=100");
	win.focus();
}


/** locations js */
var map;
var icon0;
var markers = new Array();
var infoContent = new Array();
var locations = new Array();
var gdir;
var address;
var geocoder = null;
var iconPath = '../images/';

var isGLoaded;

var maxLat = 0, maxLong = 0, minLat = 0, minLong = 0;
 
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

function loadMap(loc_array) {	
//	if ( typeof GMap2 !== 'object' )
//		return;
	isGLoaded = ( typeof GMap2 == 'undefined' ) ? false : true;
	if ( !isGLoaded )
		return;

	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(40.672306,-73.926315), 11);
//	map.setMapType(G_MAP_TYPE);
	
	if ( document.getElementById("directions") != null ) {
		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
	}
	
	geocoder = new GClientGeocoder();
 
	icon0 = new GIcon();
	icon0.image = iconPath + "gmarker.png";
	icon0.shadow = "http://www.google.com/mapfiles/shadow50.png";
	icon0.iconSize = new GSize(22, 36);
	icon0.shadowSize = new GSize(37, 34);
	icon0.iconAnchor = new GPoint(9, 36);
	icon0.infoWindowAnchor = new GPoint(9, 2);
	icon0.infoShadowAnchor = new GPoint(18, 25);
	
	addPoints();
}

function addPoints() {
	if ( !isGLoaded )
		return;
		
	for( var i = 0; i < locations.length; i++ ) {
		
		var point = new GPoint(locations[i][2],locations[i][1]);
		infoContent[i] = "<div id=\"popup\">" + locations[i][0] + '<br />';		
		if ( address != null && address.length > 5 ) {
			infoContent[i] += '<a href="' + locations[i][3] + '?address=' + address + '" style="font-weight:bold;">Get Directions</a><br />';
		}
		infoContent[i] += '<a href="#" onclick="openMarker(' + i + '); return false;" style="font-weight:bold;">Zoom In</a> | <a href="#" onclick="openMarker(' + i + ', 11);return false;" style="font-weight:bold;">Zoom Out</a>';
		if ( locations[i][3].length > 1 ) {
			infoContent[i] += ' | <a href="' + locations[i][3] + '" style="font-weight:bold;">More Information &raquo;</a></div>';
		}
		
		markers[i] = createMarker(point, icon0, infoContent[i]);
		map.addOverlay(markers[i]);
		
		// set min / max points
		if ( maxLat == 0 ) maxLat = locations[i][1];
		else if ( maxLat < locations[i][1] ) maxLat = locations[i][1];
		
		if ( minLat == 0 ) minLat = locations[i][1];
		else if ( minLat > locations[i][1] ) minLat = locations[i][1];

		if ( maxLong == 0 ) maxLong = locations[i][2];
		else if ( maxLong < locations[i][2] ) maxLong = locations[i][2];
		
		if ( minLong == 0 ) minLong = locations[i][2];
		else if ( minLong > locations[i][2] ) minLong = locations[i][2];
	}	
}
 
function createMarker(point, icon, popuphtml) {
	if ( !isGLoaded )
		return;
		
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(popuphtml);
	});
	return marker;
}

function centerAll() {
	if ( !isGLoaded )
		return;
		
	var bounds = extendByRatio(new GLatLngBounds(new GLatLng(minLat, minLong), new GLatLng(maxLat, maxLong)), 0.05);
	var zoom = map.getBoundsZoomLevel(bounds);

	var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0; 
	var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0; 

	map.setCenter(new GLatLng(center_lat, center_lng), zoom);
}

function setCenter(lat, long, zoom) {
	if ( !isGLoaded )
		return;
		
	map.setCenter(new GLatLng(lat,long), zoom);
}

function openMarker(i, zoom) {
	if ( !isGLoaded )
		return;
		
	if ( !zoom) zoom = 15;
	
	setCenter(locations[i][1], locations[i][2], zoom);
	markers[i].openInfoWindowHtml(infoContent[i]);
}

function getDirections(fromAddress) {
	if ( !isGLoaded )
		return;
		
	if ( fromAddress.length < 5 ) {
		var divError = document.getElementById('direction_error');
		divError.innerHTML = 'Please enter your full address.';
		divError.style.display = 'block';
	}
	
	var query = "from: " + fromAddress + " to: " + address;
	gdir.load(query);
}

function handleErrors(){
	if ( !isGLoaded )
		return;
		
	var str = '';
	
   if ( gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS )
		str = "The specified location could not be found. This may be due to the fact that the address is relatively new, or it may be incorrect.";

else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		str = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.";
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	 	str = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.";
 
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		str = "The given key is either invalid or does not match the domain for which it was given.";

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		str = "A directions request could not be successfully parsed.";
   else 
		str = "An unknown error occurred.";
	
	var divError = document.getElementById('direction_error');
	divError.innerHTML = str;
	divError.style.display = 'block';
}

function onGDirectionsLoad(){ 
	if ( !isGLoaded )
		return;
		
	markers[0].hide();
	markers[0].closeInfoWindow();
	
	var fm = gdir.getMarker(1).getIcon();
	fm.image = iconPath + 'gmarker.png';

	var divMap = document.getElementById('map');
	var divDirections = document.getElementById('directions');
	var divError = document.getElementById('direction_error');
	
	divError.style.display = 'none';
}

function extendByRatio(bounds, ratio) {
	if ( !isGLoaded )
		return;
		
	 var largerBounds = new GLatLngBounds(bounds.getSouthWest(), bounds.getNorthEast());
	 
	 // get lat, lng of north east and south west
	 var northEastLat = bounds.getNorthEast().lat();
	 var northEastLng = bounds.getNorthEast().lng();
	 var southWestLat = bounds.getSouthWest().lat();
	 var southWestLng = bounds.getSouthWest().lng();
	 var diffLat = northEastLat - southWestLat;
	 var diffLng = northEastLng - southWestLng;
	 
	 // multiply with ratio
	 northEastLat += diffLat * ratio;
	 southWestLat -= diffLat * ratio;
	 northEastLng += diffLng * ratio;
	 southWestLng -= diffLng * ratio;
	 
	 // extend north east
	 largerBounds.extend(new GLatLng(northEastLat, northEastLng));
	 largerBounds.extend(new GLatLng(southWestLat, southWestLng));

	return largerBounds;
} 