var route_finder, mapviewer, route, loading
var max_zindex = 1002;
var bShowWidgets = true;
var addressSelectList = new Array();
var oActiveAddress = new Object();
var startPoint = "";
var lastQuery = "";
var sInitLinkPos = 'CalculateDirections';
var sLinkPos = sInitLinkPos;


function showRoute()
{
	addressSelectList = new Array();
	oActiveAddress = new Object();
	
	if (oActiveStoreObject) {
		routeInit();
	}
	if (!opener) {
		lastQuery = "";
	}
	//callRoute(startQS);
}


function searchRoute()
{
	$('routeSearchAddress').removeClassName('required');
	var reqField = $('routeSearchAddress');
	if (reqField && (!reqField.value || reqField.value.length == 0 || reqField.value == 'none' || reqField.value == labels["routeSearchAddress"])) {
		$('routeSearchAddress').addClassName('required');
	} else {
		sLinkPos = sInitLinkPos;
		callRoute();
	}
}


function routeInit()
{
	if ($('searchdirections-extrainfo')) {
		$('searchdirections-extrainfo').removeClassName('active');			
		$('searchdirections-extrainfo').addClassName('inactive');		
	}
	if ($('searchdirections-mapmain')) {
		$('searchdirections-mapmain').innerHTML = '';
		mapviewer = new MultimapViewer( $('searchdirections-mapmain') );
		mapviewer.removeAllOverlays();
		mapviewer.addEventHandler('changeZoom',checkAerialCoverage);		
		
		if (oActiveStoreObject && oActiveStoreObject.point) {
			// Create an MMLatLon Instance
			var pos = new MMLatLon(oActiveStoreObject.point.lat, oActiveStoreObject.point.lon);
			mapviewer.goToPosition(new MMLocation(pos, 15));
		} else {
			mapviewer.goToPosition(new MMLocation(new MMLatLon( 42.3508, -71.0717 ), 5));
		}
		mapviewer.setAllowedZoomFactors(6, 17);
		mapviewer.redrawMap();
		mapviewer.setOptions({units: distance_unit});
	}

    route_finder = new MMRouteRequester(resultsLoaded);
    loading = document.getElementById('loading');
    loadingStatus(false);
}


function loadingStatus(piStatus)
{
	var overlay = $('route-overlay-white');	
	if (piStatus) {
		if (!overlay) {
			setTimeout("loadingStatus(false)", 10000);
			var sLoader  = '<div id="route_disable_background_white">&nbsp;</div>';
				sLoader += '<img src="img/loader.gif" alt="'+ labels["loading"] +'"/><br/>';
				sLoader += '<span>'+ labels["loading"] +'</span>';
			var wrap = new Element('div', {id:'route-overlay-white'}).update(sLoader);
			if ($('searchmap-rightcontent')) {
				if ($('searchmap-rightcontent').firstChild) {
					$('searchmap-rightcontent').insertBefore(wrap, $('searchmap-rightcontent').firstChild);		
				}
			}
		}
	} else {
		if ($('search_valid_address')) {
			$('search_valid_address').disabled = "";
		}
		if (overlay) {
			$('searchmap-rightcontent').removeChild(overlay);
		}
	}	
}


function createStepMarker(location, instruction, text, zindex) 
{
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
	marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}


function callRoute() 
{
	if (!opener) {
		hitboxLink('SFCalculateDirectionsButton', sLinkPos);
	}
	
	var query = undefined;
	var locations = new Array();
	
	var selAddress = $('search_valid_address');
	if (selAddress && selAddress.value.length > 0) {
		var tmp = $F('search_valid_address').split("|");
		query = new Object();
		query.point = new Object();
		query.point.lat = tmp[0];
		query.point.lon = tmp[1];
		startPoint = tmp[2];
	} else if ($('routeSearchAddress')) {
		if ($F('routeSearchAddress')) {
			startPoint = $F('routeSearchAddress');
			query = new Array($F('routeSearchAddress'));
		}
	} else {
		query = lastQuery;
	}
	
	if (query != undefined && query.length > 0 || typeof(query) == "object") {
		if ($('search_valid_address')) {
			$('search_valid_address').disabled = "disabled";
		}
		lastQuery = query;		
		loadingStatus( true );
		addLocation(1, locations, query);
		addLocation(2, locations, oActiveStoreObject);
		
		var sWalkingMode = null;
		if (opener) {
			if (opener.document.getElementById("route-mode-walking")) {
				sWalkingMode = opener.document.getElementById("route-mode-walking").checked;
			}
		} else {
			if ($('route-mode-walking')) {
				sWalkingMode = $F('route-mode-walking');
			}
		}
		
		//bWalkingMode = (opener) ? opener.document.getElementById("route-mode-walking").checked : $('route-mode-walking').checked;
		
		route = new MMRoute(locations);
		route.optimize_for = 'time';
		route.mode = (sWalkingMode != null && sWalkingMode != false) ? 'walking' : 'driving';
		route.exclude = '';
		route.optimize_intermediates = 'true';
		route.lang = store_locator_language;
		route_finder.request(route);
		setTimeout("loadingStatus(false)", 10000);
	}
}


function cleanUp()
{
	if ($('searchdirections-extrainfo')) {
		$('searchdirections-extrainfo').innerHTML = "";
	}
    mapviewer.removeAllOverlays();
    markers = new Array();
}


function addLocation(num, locations, target)
{
    var address = new MMAddress();
	if (target.point) {
		var pos = new MMLatLon(target.point.lat, target.point.lon);
		if (num == 2) {
			if (countryCode.toLowerCase() == "cn") {
				// Add the offset for china
				 pos = adjustLatLon(pos);
			}
		}
		locations.push(new MMLocation(pos, 15));
	} else {
		if (target.length == 1) {
			address.qs = target;
			if ($('countryList')) {
				if ($F('countryList')) {
					address.country_code = $F('countryList');
				}	
			} else if (opener && opener.document.getElementById("countryList")) {
				address.country_code = opener.document.getElementById("countryList").value;
			}
		} else {
			for(var a = 0; a < target.length; a++) {
				var tmp = target[a].split('=');
				if(tmp[0] == 'countryCode') {
					tmp[0] = 'country_code';
				}
				eval('address.' + tmp[0] + '=tmp[1]');
			}		
		}
		locations.push(new MMLocation(address, 15));
	}
}


function resultsLoaded()
{
	cleanUp();
	if (route.error_code) {
        if (route.error_code == 'MM_ROUTE_GEOCODING_ERRORS') {
            processGeocodingErrors(route.geocoding_errors);
        } else {
            //alert(route.error_code + ': ' + route.error_explanation);
			alert(messages['noMultimapResponse']);
        }
    } else {
		if ($('address-list')) {
			$('address-list').innerHTML = "";
			$('address-list').removeClassName('active');			
			$('address-list').addClassName('inactive');
		}
		setAddressError(false);
		
        mapviewer.goToPosition(mapviewer.getAutoScaleLocation(route.bounds));
        displayStages(route);

        for (var i = 0, l = route.polyLine.length; i < l; ++i) {
			mapviewer.addOverlay(route.polyLine[i]);
        }
    }

	if (bShowWidgets==true) {
		var widget = new MMPanZoomWidget(new MMBox(10, 10, undefined, undefined),'NewPanZoomWidget',true);
		mapviewer.addWidget(widget);
		mapviewer.addWidget(getLocalInfoWidget());
	}	
	
	if (opener && opener.mapviewer) {
		mapviewer.setZoomFactor(opener.mapviewer.getZoomFactor());
		var mapcentre = opener.mapviewer.getCurrentPosition();
        mapviewer.goToPosition(new MMLatLon(mapcentre.lat, mapcentre.lon));		
	}
	
    loadingStatus(false);
}


function displayStages(pRoute)
{
    var curr_step = 1;
    var stages = pRoute.stages;
    var container = $('searchdirections-extrainfo');
	if (container) {
		container.removeClassName('inactive');			
		container.addClassName('active');
		
		container.appendChild(new Element('h2').update(labels['routeCaption']));
		//var searchAddress = (opener && opener.document.getElementById("routeSearchAddress").value) ?  opener.document.getElementById("routeSearchAddress").value : $F('routeSearchAddress');
		var sStart = (stages[0].start_address && stages[0].start_address.display_name) ? stages[0].start_address.display_name : startPoint;
		var sSummary = '';
			sSummary += labels['routeStart'] + ' ' + sStart;
			sSummary += '<br />' + labels['routeEnd'] + ' ' + oActiveStoreObject.bizname+", "+getAddress(oActiveStoreObject); //stages[stages.length - 1].end_address;
			sSummary += '<br />' + labels['routeTotalDist'] + ' ' + pRoute["distance"][distance_unit] +" "+distance_unit;
		var sTime = "";
		if (pRoute.duration.days > 0) { 
			sTime += pRoute.duration.days + ' ' + labels['routeDays'] + ' ';
		}
		if (pRoute.duration.hours > 0) { 
			sTime += pRoute.duration.hours + ' ' + labels['routeHours'] + ' '; 
		}
		if (pRoute.duration.minutes > 0) { 
			sTime += pRoute.duration.minutes + ' ' + labels['routeMins'] + ' '; 
		}
		if(sTime.length > 0)
		{
			sSummary += '<br />' + labels['routeTotalTime'] + ' ' + sTime;
		}
		
		container.appendChild(new Element('p').update(sSummary));
	
		for (var count=0; count < stages.length; count++) {
			var sStageSummary = '';
			
			if (stages.length > 1) {
				var sStageStart = (stages[count].start_address && stages[count].start_address.display_name) ? stages[count].start_address.display_name : startPoint;
				sStageSummary += '<strong>' + labels['routeStage'] + ' ' + (count + 1) + '<' + '/strong>';
				sStageSummary += '<br />' + labels['routeStart'] + ' ' + sStageStart;
				sStageSummary += '<br />' + labels['routeEnd'] + ' ' + oActiveStoreObject.town; //stages[count].end_address;
				sStageSummary += '<br />' + labels['routeStageDist'] + ' ' + stages[count]["distance"][distance_unit] +" "+distance_unit;
				sStageSummary += '<br />' + labels['routeStageTime'] + ' ';
				
				if (stages[count].duration.days > 0) { 
					sStageSummary += stages[count].duration.days + ' ' + labels['routeDays'] + ' '; 
				}
				if (stages[count].duration.hours > 0) { 
					sStageSummary += stages[count].duration.hours + ' ' + labels['routeHours'] + ' '; 
				}
				if (stages[count].duration.minutes > 0) { 
					sStageSummary += stages[count].duration.minutes + ' ' + labels['routeMins'] + ' '; 
				}
			}
			
			sStageSummary += '<br />' + labels['routeStageSum'] + ' ' + stages[count].summary;
			container.appendChild(new Element('p').update(sStageSummary));
	
			var stageList = new Element('ol', {id:'stage_' + count, start: 'curr_step'});
			var steps = stages[count].steps;
	
			for (var stepCount=0; stepCount < steps.length; stepCount++) {
				var text = curr_step;
				var zindex = max_zindex - curr_step + 1;
				if (count == stages.length - 1 && stepCount  == steps.length - 1) {
					zindex = max_zindex;
				}
	
				var instruction = steps[stepCount].instruction;
				var roadname = steps[stepCount].road_name;
				var roadnumber = steps[stepCount].road_number;
	
				if (roadname && roadnumber) {
					instruction += ' ' + roadname + ' (' + roadnumber + ') ';
				} else if (roadname) {
					instruction += ' ' + roadname + ' ';
				} else if (roadnumber) {
					instruction += ' ' + roadnumber + ' ';
				}
	
				var distance = '';
				
				if (steps[stepCount]["distance"][distance_unit] > 0) {
					distance += ' - ' + steps[stepCount]["distance"][distance_unit] +" "+distance_unit;
				}
	
				stageList.appendChild(new Element('li').update(instruction + distance));
				createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
	
				++curr_step;
			}
			container.appendChild(stageList);
		}
	
		var aCopyright = new Array();
		if (pRoute.copyright) {
			aCopyright.push('Copyright: ' + pRoute.copyright); 
		}
		if (pRoute.disclaimer) {	
			aCopyright.push('Disclaimer:  <a href="' + pRoute.disclaimer +'">' + pRoute.disclaimer +'<' + '/a>'); 
		}
	
		container.appendChild(new Element('p').addClassName("copyright").update(aCopyright.join(' | ')));
	}
}

function processGeocodingErrors(errors)
{
    try
    {
	    for (var i = 0; i < errors.length; i++) {
			if (errors[i].error_code == 'MM_GEOCODE_NO_MATCHES' || errors[i].error_code == 'MM_SEARCH_NO_MATCHES') {
				//alert('No matching locations for Location ' + errors[i].input_id);
				//Fehlermeldung setzen
				setAddressError(true, messages['noRoutingMatches']);
			} else if (errors[i].error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
				var tmpSortKey = sortKey;
				sLinkPos = 'CalculateDirectionsRefined';

				sortKey = "address.display_name";
				errors[i].results.sort(usort);
				sortKey = tmpSortKey;				
				addressSelectList = errors[i].results;

				var sValue = "";
				var select = new Element('select', {id:'search_valid_address', tabindex:1, name:'search_valid_address', onchange:"callRoute();"}).addClassName("select-valid-address");
					select.appendChild(new Element('option', {value:sValue}).update(messages['confirmAddress']));
				for (var j = 0; j < errors[i].results.length; j++) {
					sValue = errors[i].results[j]["coords"]["lat"]+"|"+errors[i].results[j]["coords"]["lon"]+"|"+errors[i].results[j].address.display_name;
					select.appendChild(new Element('option', {value:sValue}).update(errors[i].results[j].address.display_name));
				}
				if ($('address-list')) {
					$('address-list').removeClassName('inactive');
					$('address-list').addClassName('active');
					$('address-list').innerHTML = "";
					$('address-list').appendChild(select);
					$('search_valid_address').onchange = callRoute; //ie fix
					$('search_valid_address').disabled = "";
				}
				setAddressError(true, messages['refineSearch']);
			}
			loadingStatus(false);
		}
	} catch(E) {}
}

function setAddressError(pbValue, message)
{
	if (pbValue) {
		if ($('searchdirections-address') && !$('sdir-errtext')) {	
			$('searchdirections-address').removeClassName('searchdirections-address-normal');
			$('searchdirections-address').addClassName('searchdirections-address-error');			
			var error = new Element('div', {id:'sdir-errtext'}).update(message);
			if ($('searchdirections-address').firstChild) {
				$('searchdirections-address').insertBefore(error, $('searchdirections-address').firstChild);
			}
		}		
	} else {
		if ($('searchdirections-address')) {
			if ($('sdir-errtext')) {
				$('searchdirections-address').removeChild($('sdir-errtext'));
			}
			$('searchdirections-address').removeClassName('searchdirections-address-error');
			$('searchdirections-address').addClassName('searchdirections-address-normal');									
		}
	}
}

function transferAddress()
{
	if ($('search_valid_address')) {
		if ($F('search_valid_address')) {
			if ($('routeSearchAddress')) {
				$('routeSearchAddress').value = addressSelectList[$F('search_valid_address')].address.display_name;
			}
		}
	}
}