/*
 * EasyRouteSystem - Beta Example
 * 
 * You may not copy/use this code without permission.
 * 
 * @author Justin Carlson <justin.carlson@gmail.com>
 * @version 0.5.5
 * 
 * TODO: Clean up route validation
 * 
 */

// define global vars
var map; // google maps
var gdir; // google directions
var geocoder; // google geocoder
var previousEntry = null;

// speed trap ( limit number of active queries )
var busy = false;

// version 0.0.1 vars
var tripOrigin = null;

// version 0.1.5 added collection
var EasyKit = new Object();
EasyKit.length = 0; // Manual Hash Count

// base model for markers
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = base_url + "/images/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

// Extend jQuery with a fade loop
jQuery.fn.toggleFade = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);
}; 

// when jQuery is ready, bind key capture to input boxes, and focus on the input box
$(document).ready(function() {

 $("#origin").keypress(function (e) {
   if( e.which == 13 ) {
   	 $('#addbutton').click();
   	 return false;
   }
 });
                        
 $("#destination").keypress(function (e) {
   if( e.which == 13 ) {
   	 $('#addbutton').click();
   	 return false;
   }
 });
 
 $('#origin').focus();	
                         
}); 

// init called by the browser onload event, setup various api objects 
function initialize() {
	
	if (GBrowserIsCompatible()) {
		        
        // create directions api
        gdir = new GDirections(null, null);   
        GEvent.addListener(gdir, "load", EasyLoader);
        GEvent.addListener(gdir, "error", EasyErrors);
        
        // create geocoder for validations
        geocoder = new GClientGeocoder();
        
        // setup EasyKit 
        EasyKit['totalduration'] = 0;
        EasyKit['totaldistance'] = 0;
        
    }
	
	if (firstViewing) {
		setTimeout('welcomeMat()',300);		
	}

}

// welcome first time users ( first time session not ever )
function welcomeMat() {
	$.jGrowl("<strong>Welcome!</strong><br/>To begin, enter a starting location by typing a city, state, or zip code and click the button.", { life: 12000 });
}
function welcomeFirstEntry() {
	$.jGrowl("<strong>Excellent!</strong><br/>Now enter the location you're traveling to and click the add destination button again.", { life: 8000 });
}
function welcomeFirstRoute() {
	$.jGrowl("<strong>Congratulations!</strong><br/>You have entered your first route.", { life: 5000 });
	$.jGrowl("You can click the map icon beside the total miles to view a map.", { life: 7000 });
	$.jGrowl("You may click the export or email icons to save your directions.", { life: 9000 });
}


// get directions from 2 text entries
function getDirections(from,to,returnId) {
	
	// cache is disabled for now
	lookupAndCache(from,to,returnId);
	return;
	
	// do a local lookup first	
	$.ajax({
    url: 'read/?from='+from+'&to='+to,
    type: 'GET',
    dataType: 'text',
    timeout: 1000,
    error: function(error){
		lookupAndCache(from,to,returnId);
    },
    success: function(data){
        if(data==0) {
        	lookupAndCache(from,to,returnId);
        } else {
        	handleCachedEntry(data,returnId);
        }
    }
	});
}

function lookupAndCache(from,to,returnId) {
	
	busy = true;
	gdir.startLocation = from;
	gdir.endLocation = to;
	gdir.newHandleId = returnId;
	gdir.load("from: " + from + " to: " + to,{getSteps:true,getPolyline:true});
	
}

function toggleMap() {
	
	jQuery.blockUI({ css: { 
        border: 'none', 
        padding: '15px',
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.5', 
        color: '#fff' 
    },message: '<span><img src="images/ajaxsmb.gif" /> Just a moment...</span>' } ); 
	setTimeout('doToggleMap()',300);
	
}

function doToggleMap() {
	
	$('#detailscontainer').toggle();
	if ( $('#detailscontainer').is(':hidden') ) {
		
		$('#maplink').text('show directions and map');
		
	} else {

		$('#maplink').text('hide directions and map');
		
		if (GBrowserIsCompatible()) {
			
			map = new GMap2(document.getElementById("map_canvas"));
			map.setCenter(EasyKit['bounds'].getCenter());
			map.setZoom(map.getBoundsZoomLevel(EasyKit['bounds']));
	        var mapControl = new GMapTypeControl();
	        map.addControl(mapControl);
	        map.addControl(new GLargeMapControl());        
	        DrawMap(true);
		}
	}
	$.unblockUI();
}

function DrawMap(forceRedraw) {
	
	if(forceRedraw==true) {
		map.closeInfoWindow();
		map.clearOverlays();
		$('#text_canvas').html('');
	}
	
	for (var key in EasyKit) {
		
		if (typeof EasyKit[key]['route']  != "undefined" && (typeof EasyKit[key]['drawn']  == "undefined" || forceRedraw == true)) {
			
			// todo: display the text
			DisplayRouteText(EasyKit[key]);
			
			// add the marker
	        map.addOverlay(EasyMarker(EasyKit[key]['startLatLng']));
	        map.addOverlay(EasyMarker(EasyKit[key]['endLatLng']));
	          
			// draw the line
	        EasyKit[key]['poly'].color = "#0000ff";
	        EasyKit[key]['poly'].easyid = key;
			map.addOverlay(EasyKit[key]['poly']);
			EasyKit[key]['drawn'] = true;
			
		}		
	}
	map.setCenter(EasyKit['bounds'].getCenter());
	map.setZoom(map.getBoundsZoomLevel(EasyKit['bounds']));

}

function DisplayRouteText(Kit) {
	
	
	var routeHtml = '<p class="dirheading"><strong>From ' + Kit['startLocation'] + ' to ' + Kit['endLocation'] + '</strong></p>';
		for (var s=0; s<Kit['route'].getNumSteps(); s++) {
            var step = Kit['route'].getStep(s);
            routeHtml += fetchDetailText(step.getLatLng(), step.getDescriptionHtml(), step.getDistance().html);
        }
	$('#text_canvas').append(routeHtml);
	
}

function fetchDetailText(point, description, dist) {
	
    var target = "map.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"));";
    html = '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
    html += '  <tr style="cursor: pointer;" onclick="'+target+'">';
    html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
    html +=        description;
    html += '    </td>';
    html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
    html +=        dist;
    html += '    </td>';
    html += '  </tr>';
    html += '</table>';
    return html;
    
}

function EasyMarker(point) {
	
	var EasyIcon = new GIcon(baseIcon);
	EasyIcon.image = base_url + "/images/marker.png";
    var markerOptions = { icon:EasyIcon };
    var marker = new GMarker(point, markerOptions);
    return marker;
}

function EasyLoader(response) {
	
	
	if(gdir.getNumRoutes()>0) {

		// update the previousEntry
		previousEntry = gdir.endLocation;
				
		// update EasyKit
		EasyKit[gdir.newHandleId] = new Array();
		EasyKit[gdir.newHandleId]['poly'] = gdir.getPolyline();
		EasyKit[gdir.newHandleId]['startLocation'] = gdir.startLocation;
		EasyKit[gdir.newHandleId]['endLocation'] = gdir.endLocation;
		EasyKit[gdir.newHandleId]['route'] = gdir.getRoute(0);
		EasyKit[gdir.newHandleId]['startLatLng'] = EasyKit[gdir.newHandleId]['route'].getStep(0).getLatLng();
		EasyKit[gdir.newHandleId]['endLatLng'] = EasyKit[gdir.newHandleId]['route'].getEndLatLng();
		EasyKit[gdir.newHandleId]['distance'] = EasyKit[gdir.newHandleId]['route'].getDistance().html;
		EasyKit[gdir.newHandleId]['duration'] = EasyKit[gdir.newHandleId]['route'].getDuration().html;
		EasyKit['totalduration'] = (parseInt(EasyKit['totalduration']) + parseInt(EasyKit[gdir.newHandleId]['route'].getDuration().seconds));
		EasyKit['totaldistance'] = (parseInt(EasyKit['totaldistance']) + parseInt(EasyKit[gdir.newHandleId]['route'].getDistance().meters));
		EasyKit.length++;
		
		// update bounds object
		if (typeof EasyKit['bounds']  == "undefined") {
			EasyKit['bounds'] = gdir.getBounds();
		}
			
		// store route steps and update bounds
		EasyKit[gdir.newHandleId]['steps'] = new Array();
		for (var j=0; j<EasyKit[gdir.newHandleId]['route'].getNumSteps(); j++) {	
	          EasyKit[gdir.newHandleId]['steps'][j] = EasyKit[gdir.newHandleId]['route'].getStep(j);
	          EasyKit['bounds'].extend(EasyKit[gdir.newHandleId]['steps'][j].getLatLng());
	    }
		
        // update display with distance and time
        $('#' + gdir.newHandleId ).html( EasyKit[gdir.newHandleId]['distance'] + ' (about ' + EasyKit[gdir.newHandleId]['duration'] + ')');
        
        // update totals
        var minutes = Math.round((((parseInt(EasyKit['totalduration'])/60))*100))/100;
        var hours = Math.floor(minutes/60);
        var mins = Math.floor(minutes%60);
        if(hours>0) {
        	if(hours>1) {
        		var duration = hours + ' hours, ' + mins + ' minutes';
        	} else {
        		var duration = hours + ' hour, ' + mins + ' minutes';
        	}
        } else {
        	var duration = mins + ' minutes';
        }
        var miles = Math.round((parseInt(EasyKit['totaldistance'])/1609.344)*100)/100;    
        $('#total').html(miles + '&nbsp;mi&nbsp;(about&nbsp;' + duration + ')');
        $('#totals').fadeOut('fast').fadeIn('slow');

        // update map
    	if(map) {
    		DrawMap();
    	}
      }  
	
	busy = false;
	$.unblockUI();
	
}

// type 1 routes are a chain, remove a link and you lose all the links below it
function removeRoute(handle) {
	
	var removed = 0;
	var removalFlag = false;
	for (var key in EasyKit) {
		if (typeof EasyKit[key]['route']  != "undefined") {
			if (key == handle && removalFlag == false ) {
				removalFlag = true;
			}
			if (removalFlag == true) {
				removeDestination(key);
				removed++;
			} else {
				previousEntry = EasyKit[key]['endLocation'];
			}
		}
		
	}
	if (removed>1) {
		$.jGrowl("<strong>Where did the rest of my route go?</strong><br/>It was removed because it occured after the stop you deleted.");
	}
	// reset route to origin starting point
	if(EasyKit.length<1) {
		previousEntry = tripOrigin;
	}
	
}

// type n>1 routes can be altered line by line
function removeDestination (handle) {
	
	// update UI
	$('#' + handle ).parent().addClass('error');
    $('#' + handle ).text('This portion of your trip is being removed.');
    $('#' + handle ).parent().fadeTo(1500, 1).hide(1200);
    $('#' + handle ).parent().remove();
   
    // remove from EasyKit
	EasyKit['totalduration'] = (parseInt(EasyKit['totalduration']) - parseInt(EasyKit[handle]['route'].getDuration().seconds));
	EasyKit['totaldistance'] = (parseInt(EasyKit['totaldistance']) - parseInt(EasyKit[handle]['route'].getDistance().meters));
	EasyKit.length--;
	delete EasyKit[handle];
	
	 // update totals
    var minutes = Math.round((((parseInt(EasyKit['totalduration'])/60))*100))/100;
    var hours = Math.floor(minutes/60);
    var mins = Math.floor(minutes%60);
    if(hours>0) {
    	if(hours>1) {
    		var duration = hours + ' hours, ' + mins + ' minutes';
    	} else {
    		var duration = hours + ' hour, ' + mins + ' minutes';
    	}
    } else {
    	var duration = mins + ' minutes';
    }
    var miles = Math.round((parseInt(EasyKit['totaldistance'])/1609.344)*100)/100; 
	
    // update UI
	if(EasyKit.length>0) {
		$('#total').html(miles + '&nbsp;mi&nbsp;(about&nbsp;' + duration + ')');
        $('#totals').fadeOut('fast').fadeIn('slow');
        
        // redraw map
    	if(map) {
    		DrawMap(true);
    	}
    	
	} else {
		$('#totals').fadeOut('fast');

	    // update map
		if(map) {
			toggleMap();
		}		
	}
	
}

function resetAll() {

	EasyKit = new Object();
	EasyKit.length = 0;
    EasyKit['totalduration'] = 0;
    EasyKit['totaldistance'] = 0;
    
	busy = false;
	$.unblockUI();
	if(map) {
		map.closeInfoWindow();
		map.clearOverlays();
	}
	$('#destinations').text('');
	$('#detailscontainer').hide();
	$('#actionbar').fadeOut('slow');
	$('.destination').fadeOut().text('');
	$('#totals').fadeOut('slow');
	tripOrigin = '';
	tripDestination = '';
	previousEntry = '';
	gdir.newOriginText = null;
    gdir.newDestinationText = null;
	gdir.newHandleId = null;
	$('#exceldata').text('');
	$('#maplink').text('show directions and map');
	$('#entrylabel').text('Enter a City, State, or Zip:');
	
}

// once a desitation passes validation ( geocodes ) it's added
function doAddDestination(optionalType) {
		
	// get entry
	var locationText = $('#origin').val();			
		
	// handle multiple route types
	if( typeof optionalType != "undefined" ) {
		
		// several destiations one origin
		if(optionalType == 2) {		
			previousEntry = tripOrigin;
		} 
		
		// several trips ( different origin and destination )
		if(optionalType == 3) {
			
			// get entry
			tripOrigin = $('#origin').val(); 
			previousEntry = $('#origin').val();
			locationText = $('#destination').val(); 
			
			// validate entry
			if (locationText == '') {
				alert('You must enter a city, state, or zip code.');
				$('#origin').focus();
				return;
			}
		}		
	} else {
		//default: each origin is a new destination on one trip
	}

	// Route Container
	parentDivContent = '';
	
	if (tripOrigin == '' || tripOrigin == null ) {
	
		// first entry
		tripOrigin = locationText;
		previousEntry = locationText;
				
		// first location during session
		if (firstViewing) {
			welcomeFirstEntry();
		}
				
		// build html
		parentDivContent+= '<span>Starting from <strong>';
		parentDivContent+= tripOrigin + '</strong></span>&nbsp;';
		var mockedMilesId = $.md5(locationText);
		mockedMiles = '';
		
		$('#entrylabel').fadeOut('fast').text('Enter next stop:').fadeIn('fast');
		
		// reset all if you remove this first entry on a type null, 1 or 2 
		if( optionalType != 3 ) {
			// reset the lines
			var deleteLine = '<img class="lineControl" onClick="resetAll();return false;" title="Click here to reset trip. (Start Over)" src="images/reset.jpg">';
		}
		
	} else {
	
		// first route calculated for session
		if (firstViewing) {
			welcomeFirstRoute();
			firstViewing = false;
		}
		
		// new entry
		$('#actionbar').fadeIn();
	
		// create a unique id for the row
		var elementCounter = 2;
		var mockedMilesId = $.md5(previousEntry + locationText);
		while ($('#' + mockedMilesId).length) {
			mockedMilesId += elementCounter;
			elementCounter++;
		}
		
		// delete lines
		if( typeof optionalType == "undefined" ) {
			var deleteLine = '<img class="lineControl"  onClick="removeRoute(\''+mockedMilesId+'\');return false;"  title="Click here to remove this line from the trip." src="images/delete.jpg">';
		} else {
			var deleteLine = '<img class="lineControl"  onClick="removeDestination(\''+mockedMilesId+'\');return false;"  title="Click here to remove this line from the trip." src="images/delete.jpg">';
		}
		
		
		// build html
		mockedMiles = '<div id="' + mockedMilesId + '"><img src="images/ajaxsm.gif"></div>';
		parentDivContent+= '<span>Traveling from <strong>' + previousEntry + '</strong>';
		parentDivContent+= ' to <strong>' + locationText + '</strong></span>';
		
		// get directions
		if(map) {
			map.closeInfoWindow();
		}
		getDirections(previousEntry,locationText,mockedMilesId);
		
	}
	
	// string together the html
	var parentDiv = '';
	var newDivId = mockedMilesId + 'container';
	parentDiv+= '<div id="' + newDivId + '" class="destination">' + deleteLine;		
	
	parentDivContent+= '</strong>';
	parentDivContent+= mockedMiles;
	
	var newLocation = parentDiv + parentDivContent + '</div>';
	
	$('#destinations').append(newLocation);
	$('#' + newDivId).fadeOut('fast').fadeIn('slow');
	$('#origin').val('').focus();
	$("#destination").val('');
	
}

// function called from the templates
function addDestination(optionalType) {

	// get entry
	var locationText = $('#origin').val();		
		
	// validate entry
	if (locationText == '') {	
		alert('You must enter a city, state, or zip code.');
		$('#origin').focus();
		return;
	}			
	if (busy) {
		$.blockUI({ message: '<span><img src="images/ajaxsm.gif" /> Just a moment...</span>' });
		setTimeout('addDestination(' + optionalType + ')',500); 
		return;
	}	

	// always validate
	validateAndAddOrigin(optionalType);
	
}

// validates and adds an origin 
function validateAndAddOrigin(optionalType) {

	if (geocoder) {
	        geocoder.getLocations(
	          $('#origin').val(),
	          function(response) {
	            if (!response) {
	              alert("The location '" + $('#origin').val() + "' could not be found.	");
	              $('#origin').val('');
	            } else {
	            	
	            	if( typeof response.Placemark != "undefined" ) {
	            	
	            		if (response.Placemark.length>1) {
	            			
	            			alert('That location is too ambiguous, please be more specific.');
	            			
		            	} else {
		            		
		            		$('#origin').val(response.Placemark[0].address);
			            	if(optionalType==3) {
			            		validateAndAddDestination(optionalType);
			            	} else {
			              		doAddDestination(optionalType);
			              	}
		            	}
			         } else {
			  	          alert("The location '" + $('#origin').val() + "' could not be found.	");
			         }
		            	
	            }
	          }
	        );
	}

}

//validates and adds a destination 
function validateAndAddDestination(optionalType) {

	// validate entry
	if ($('#destination').val() == '') {	
		alert('You must enter destination city, state, or zip code.');
		$('#destination').focus();
		return;
	}			

	if (geocoder) {
			geocoder.getLocations(
	          $('#destination').val(),
	          function(response) {
		            if (!response) {
		              alert("The destination '" + $('#destination').val() + "' could not be found.");
		              $('#destination').val('');
		            } else {
		            	
		            	if( typeof response.Placemark != "undefined" ) {
			            	
		            		if (response.Placemark.length>1) {
		            			
		            			alert('That location is too ambiguous, please be more specific.');
		            			
			            	} else {
			            		
			            		$('#destination').val(response.Placemark[0].address);
			            		doAddDestination(optionalType);
			            		
			            	}
			            } else {
			  	              alert("The location '" + $('#destination').val() + "' could not be found.	");
		            	}
		            }
	          }
	        );
	}

}

// pop the email input box and display the map
function sendMail() {
	addressPrompt();
}

// pops the email input box
function addressPrompt() {

	jQuery.blockUI({ css: { 
        border: 'none', 
        padding: '15px',
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.9', 
        color: '#fff' 
    },message: '<div id="mailbox">Send email to: <input type="text" size="35" name="sendto" id="sendto" /><p><button onClick="doSendMail();return false;">Send</button>&nbsp;<button onClick="cancelSendMail();return false;">Cancel</button></p></div>' } );

	// bind to the enter key
	$("#sendto").keypress(function (e) {
		   if( e.which == 13 ) {
			 doSendMail();
		   	 return false;
		   }
		 });
	
}

// submits the mail form
function doSendMail() {
	
	if(isValidEmail($('#sendto').val())) {
		
		// clear the field holders
		$('#text_canvas').html('');
		
		var EasyKitCSV = '';
		
		// must have routes
		if (EasyKit.length>0) {
			
		// populate data to send
		var now = new Date();
		var stamp = parseInt(now.getTime().toString().substring(0,10));
		document.cookie = 'EasyResCt=' + EasyKit.length;
		document.cookie = 'EasyStamp=' + stamp;
		for (var key in EasyKit) {
			if (typeof EasyKit[key]['route']  != "undefined") {
				DisplayRouteText(EasyKit[key]);
				var minutes = Math.round((((parseInt(EasyKit[key]['route'].getDuration().seconds)/60))*100))/100;
		        var hours = Math.floor(minutes/60);
		        var mins = Math.floor(minutes%60);
		        if(hours>0) {
		        	if(hours>1) {
		        		var duration = hours + ' hours, ' + mins + ' minutes';
		        	} else {
		        		var duration = hours + ' hour, ' + mins + ' minutes';
		        	}
		        } else {
		        	var duration = mins + ' minutes';
		        }
		        var miles = Math.round((parseInt(EasyKit[key]['route'].getDistance().meters)/1609.344)*100)/100;    
		        var line = EasyKit[key]['startLocation'] + '__COLUMN__';			
				line += EasyKit[key]['endLocation'] + '__COLUMN__';
				line += miles + '__COLUMN__';
				line += duration + '__COLUMN__';
				line += EasyKit[key]['startLatLng'] + '__COLUMN__';
				line += EasyKit[key]['endLatLng'];	
				line += '__NEWLINE__';
				EasyKitCSV += line;
			}
		}
		
		$.post("email/directions",
				   { 
					 mailaddress: $('#sendto').val(),
					 maildataA: $('#textcontainer').html(),
					 maildataB: EasyKitCSV,
					 maildataC: $.md5(stamp + ' with ' + EasyKit.length)
					},
				   	function(data){

						if(data=='quota') {
							$('#mailbox').append('<span class="error"><strong>Error:</strong>&nbsp;Maximum Email Quota Reached.</span>');
							$.jGrowl("<strong>Whoops!</strong><br/>Your email could not be sent due to a daily email limit in effect. You may click the excel icon to download a spreadsheet of your trip instead.", { life: 12000 });
							
						}
						if(data=='fail') {
							$('#mailbox').append('<span class="error">Could not send, please try again.</span>');
						}
						if(data=='sent') {
							$.jGrowl("<strong>Mail Sent!</strong><br/>Your email was sent. You may send more mail by clicking the mail icon again.", { life: 12000 });
							jQuery.unblockUI();
						}
						
					}
				);
		
		
		} else {
			alert('Invalid Request!');
		}
	}			
}

function showTos() {
	
	jQuery.blockUI({ css: { 
		width:          '60%', 
        top:            '10%', 
        left:           '20%',
        height: '400px',
        border: '1px solid #999999', 
        padding: '15px',
        backgroundColor: '#dddddd', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.9', 
        color: '#fff' 
    },message: '<div id="textcontent"><p><strong class="left">Terms of Use</strong><a href="#" onClick="jQuery.unblockUI();">close</a></p><iFrame id="textframe" src="terms/"></iFrame></div>' } );
	
}

function showPrivacy() {
	
	jQuery.blockUI({ css: { 
		width:          '60%', 
        top:            '10%', 
        left:           '20%',
        height: '400px',
        border: '1px solid #999999', 
        padding: '15px',
        backgroundColor: '#dddddd', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.9', 
        color: '#fff' 
    },message: '<div id="textcontent"><p><strong class="left">Privacy Policy</strong><a href="#" class="right" onClick="jQuery.unblockUI();">close</a></h3></p><iFrame id="textframe" src="privacy/"></iFrame></div>' } );
	
}

function mailMan() {
	
	if(isValidEmail($('#sendto').val())) {
		
		// clear the field holders
		$('#text_canvas').html('');
		$('#maildataB').text('');
		
		// must have routes
		if (EasyKit.length>0) {
		
		// populate data to send
		for (var key in EasyKit) {
			if (typeof EasyKit[key]['route']  != "undefined") {
				DisplayRouteText(EasyKit[key]);
				var minutes = Math.round((((parseInt(EasyKit[key]['route'].getDuration().seconds)/60))*100))/100;
		        var hours = Math.floor(minutes/60);
		        var mins = Math.floor(minutes%60);
		        if(hours>0) {
		        	if(hours>1) {
		        		var duration = hours + ' hours, ' + mins + ' minutes';
		        	} else {
		        		var duration = hours + ' hour, ' + mins + ' minutes';
		        	}
		        } else {
		        	var duration = mins + ' minutes';
		        }
		        var miles = Math.round((parseInt(EasyKit[key]['route'].getDistance().meters)/1609.344)*100)/100;    
				
		        var line = EasyKit[key]['startLocation'] + '__COLUMN__';			
				line += EasyKit[key]['endLocation'] + '__COLUMN__';
				line += miles + '__COLUMN__';
				line += duration + '__COLUMN__';
				line += EasyKit[key]['startLatLng'] + '__COLUMN__';
				line += EasyKit[key]['endLatLng'];	
				line += '__NEWLINE__';
				$('#maildataB').append(line);
			}
		}
		
		$('#mailaddress').val($('#sendto').val());
		$('#maildataA').text($('#textcontainer').html());
		$('#exportToMail').submit();
		
		} else {
			alert('Invalid Request');
		}
		
		jQuery.unblockUI();
		
	} else {
		alert('Please enter a valid email address or click cancel.');
	}
}

// hides mail input box
function cancelSendMail() {
	
	jQuery.unblockUI();
}

// submits the export form
function excelExport() {
	
	jQuery.blockUI({ css: { 
        border: 'none', 
        padding: '15px',
        backgroundColor: '#000', 
        '-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '.5', 
        color: '#fff' 
    },message: '<span><img src="images/ajaxsmb.gif" /> Just a moment...</span>' } ); 
	
	for (var key in EasyKit) {
		
		if (typeof EasyKit[key]['route']  != "undefined") {
			
			var minutes = Math.round((((parseInt(EasyKit[key]['route'].getDuration().seconds)/60))*100))/100;
	        var hours = Math.floor(minutes/60);
	        var mins = Math.floor(minutes%60);
	        if(hours>0) {
	        	if(hours>1) {
	        		var duration = hours + ' hours, ' + mins + ' minutes';
	        	} else {
	        		var duration = hours + ' hour, ' + mins + ' minutes';
	        	}
	        } else {
	        	var duration = mins + ' minutes';
	        }
	        var miles = Math.round((parseInt(EasyKit[key]['route'].getDistance().meters)/1609.344)*100)/100;    
			
			var line = '"' + EasyKit[key]['startLocation'] + '",';
			line += '"' + EasyKit[key]['endLocation'] + '",';
			line += '"' + miles + '",';
			line += '"' + duration + '",';
			line += '"' + EasyKit[key]['startLatLng'] + '",';
			line += '"' + EasyKit[key]['endLatLng'] + '"';	
			line += '__NEWLINE__';
			$('#exceldata').append(line);
		}
	}
	$('#exportToExcel').submit();
	
	jQuery.unblockUI();
	
}

function printPage() {
	try {
		printPreview();
	} catch(e) {
		window.print();
	}
}

function printPreview()
{
	var OLECMDID = 7;
	/* OLECMDID values:
	* 6 - print
	* 7 - print preview
	* 1 - open window
	* 4 - Save As
	*/
	var PROMPT = 1; // 2 DONTPROMPTUSER
	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
	document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	WebBrowser1.ExecWB(OLECMDID, PROMPT);
	WebBrowser1.outerHTML = "";
}


// validate an email address
function isValidEmail(email) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   return reg.test(email);
}

// handle errors from gdirections
function EasyErrors() {

	$('#' + gdir.newHandleId ).parent().addClass('error');
    $('#' + gdir.newHandleId ).text('Error: Could not find the location entered.');
    $('#' + gdir.newHandleId ).parent().fadeTo(1500, 1).hide(1200);
    
    setTimeout('domParentRemover(\'' + gdir.newHandleId + '\')',2000);
    
    busy = false;        	
}

function domParentRemover(handle) {
	$('#' + gdir.newHandleId ).parent().remove();
}

// reset form fields ( old )
function resetFields() {
	document.getElementById('inputform').reset();
	tbodyHandle = document.getElementById('destinations');
	for(var i = tbodyHandle.rows.length - 1; i > -1; i--)
	{
	    tbodyHandle.deleteRow(i);
	}
}


try {

    window.onload = setTimeout("initialize();",900);
	window.onunload = GUnload();
	
} catch(e){}
