//<![CDATA[
var mapviewer, route_finder, route, loading, start_geocoder, end_geocoder, start_latlong, end_latlong, routing_timeout;
var max_zindex = 1000;
var max_results = 1;
var start_geocoded = false;
var end_geocoded = false;
var error_occured = false;

var iconLocation = getRoot() + 'garysgreattrips/images/';

var divTrips = 'TripsPostCodes';
var countryCode = 'GB';
var divSearch = 'SearchCity';
var divMap = 'mapviewer';
var boxClassName = 'altinfobox';
var divRouteStep = 'routeSteps';
var divMapSearchPane = 'mapsearchpane';
var divLoader = 'map-loading';
var divToggle = 'toggle';
var divStart = 'start';
var divEnd = 'end';
var drivingId = 'driving';
var walkingId = 'walking';
var timeId = 'time';
var shortestId = 'shortest';
var flagCounter = 1;
var processed = 0;
var loaded = 0;
/* ------------------------------------------------------------- */
/* CODED BY: VANDAD NAHAVANDIPOOR */

function mapReset(){
    start_geocoder = null;
    end_geocoder = null;
    route = null;
    mapviewer = null;
    route_finder = null;
}

function getRoot() {
    var url = document.location.toString(); //url
    var e_url = ''; //edited url
    var p = 0; //position
    var p2 = 0; //position 2
    p = url.indexOf("//");
    e_url = url.substring(p + 2);
    p2 = e_url.indexOf("/");
    var root_url = url.substring(0, p + p2 + 3);
    return root_url;

}

function getDirections()
{
// 	console.log(error_occured+' -> getDirections:: '+start_geocoded+"::"+end_geocoded)
	if ((start_geocoded == true) && (end_geocoded == true))
	{
		clearInterval(routing_timeout);
		if (error_occured == false)
		{
			callRoute();
		}
	}
	else
	{
		if (error_occured == false)
		{ 
		    if(typeof routing_timeout == 'undefined')
			    routing_timeout = setInterval(getDirections, 500);
		}
		else
		{
			clearInterval(routing_timeout);
		}
	}
}


function MessageObject() {
    this.PostCode = "";
    this.CountryCode = "";
    this.PopupMessage = "";
    this.LatLon = "";
    this.Text = "0";
    this.Name = "";
}

var MessageArray = new Array();
var PosArray = new Array();

function AddMessage(CountryCode, PostCode, PopupMessage, Name, Text) {
    var MyObj = new MessageObject();
    MyObj.CountryCode = CountryCode;
    MyObj.PostCode = PostCode;
    MyObj.PopupMessage = PopupMessage;
    MyObj.Name = Name;
    MyObj.Text = Text;
    MessageArray.push(MyObj);
}

function AddLatLonToMessageObjectByPostCode(PostCode, LatLon) {
    var Counter = 0;
    var CurrentObject = new MessageObject();
    for (Counter = 0; Counter < MessageArray.length; Counter++) {
        CurrentObject = MessageArray[Counter];
        if (CurrentObject.PostCode.toLowerCase() == PostCode.toString().toLowerCase()) {
            CurrentObject.LatLon = LatLon;
            return (true);
        }
    }
    return (false);
}

function GetMarkerMessageObjectByMarkerLatLon(LatLon) {
    var Counter = 0;
    var CurrentObject = new MessageObject();
    for (Counter = 0; Counter < MessageArray.length; Counter++) {
        CurrentObject = MessageArray[Counter];
        if (CurrentObject.LatLon.toString().toLowerCase() == LatLon.toString().toLowerCase()) {
            return (CurrentObject);
        }
    }
    return (null);
}

function addMarkerByPos(pos) {
    PosArray.push(pos);
    //      alert (flagCounter+" "+pos);

    //mapviewer.removeAllOverlays(); 
    /* Now here before we start to show the marker, get the message that is associated with this position */
    MyMessageObject = GetMarkerMessageObjectByMarkerLatLon(pos);
    if (flagCounter > 5) {
        flagCounter = 1;
    }
//    if (isMulti) {
//        var icon = new MMIcon(iconLocation + 'Placemark-' + flagCounter + '.png');
//    } else {
    var icon = new MMIcon(iconLocation + 'Placemark-1.png');
//    }
    icon.iconSize = new MMDimensions(60, 70);
    icon.iconAnchor = new MMPoint(26, 57);
    marker = mapviewer.createMarker(pos, { 'label': MyMessageObject.Name, 'icon': icon });
    
    //
    //var el = document.createElement('h1');
    //var Child = document.createElement("p");
    //alert(MyMessageObject.PopupMessage);
    //Child.innerHTML = MyMessageObject.PopupMessage;
    //el.appendChild (Child);
    //marker.setInfoBoxContent(el);
    marker.setInfoBoxContent(MyMessageObject.PopupMessage, {});
    
    


    if (flagCounter > 1) {
        mapviewer.goToPosition(mapviewer.getAutoScaleLocation(PosArray), 12);
    } 
    else {
        var postCode = document.getElementById(divSearch).innerHTML;
        mapviewer.goToPosition(new MMLocation(new MMAddress({ qs: postCode, country_code: countryCode, postal_code: postCode }), 12));
    }
    mapviewer.resetPosition();
    flagCounter++;

}

function GeocodingEndedCallbackFunction(param1, param2) {
    if (param2 == null) {
        var PostCode = param1[0].address;
        var Pos = new String(param1.toString());
        Pos = Pos.substr(Pos.indexOf("coords : (", 0) + 10, Pos.length);
        Pos = Pos.substr(0, Pos.indexOf(")", 0));

        var LongLatArray = new Array();
        LongLatArray = Pos.split(",");
        var LatLon = new MMLatLon(LongLatArray[0], LongLatArray[1]);
        if (AddLatLonToMessageObjectByPostCode(PostCode, LatLon) == true) {
            addMarkerByPos(LatLon);
        }
    }
    else {
        $("#" + divMap).html(param2);
        $("#showhide").html("We are sorry, there is no map for this location.");
    }
}

function addMarkerByCountryAndPostCode(CountryCode, PostCode, PopupMessage, Name, Text) {
    AddMessage(CountryCode, PostCode, PopupMessage, Name, Text);
    var MyAddress = new MMAddress({ qs: PostCode, country_code: CountryCode, postal_code: PostCode });
    start_geocoder = new MMGeocoder(GeocodingEndedCallbackFunction);
    start_geocoder.geocode(MyAddress);
}

/* ------------------------------------------------------------- */

function showMap(id) {
    mapReset();
    if (typeof id != 'undefined') {
        divTrips = 'TripsPostCodes' + id;
        divSearch = 'SearchCity' + id;
        $('div.mapLink').find('a').each(function() {
            if ($(this).hasClass('select')) {
                $(this).removeClass('select');
            }
        });
        $("#" + id).addClass("select");
    }
    else {
        divTrips = 'TripsPostCodes';
        divSearch = 'SearchCity';
    }
    MessageArray = new Array();
    PosArray = new Array(); 
    isMulti = true;
    if (document.location.toString().indexOf("locationDetails") > 0) {
        isMulti = false;
    }
    var Map = document.getElementById(divMap);
    flagCounter = 1;
    if (Map != null) {
        flagCounter = 1;
        var postCode = document.getElementById(divSearch).innerHTML;
        //Add the map
        mapviewer = MMFactory.createViewer(document.getElementById(divMap));
        //mapviewer.goToPosition( new MMLatLon( 42.3508, -71.0717 ) );
        mapviewer.goToPosition(new MMLocation(new MMAddress({ qs: postCode, country_code: countryCode, postal_code: postCode }), 12));

        

        mapviewer.addEventHandler('endGeocode', endGeocode);
        pan_zoom_widget = new MMPanZoomWidget();
        mapviewer.addWidget(pan_zoom_widget);
        overview_widget = new MMOverviewWidget();
        mapviewer.addWidget(overview_widget);  
        
    }
    if (typeof id == 'undefined') {
        $('#submit').click(function(event) {
            event.preventDefault();
            error_occured = false;
            start = $('#' + divStart).val().replace(/\s/g, '');
            end = $('#' + divEnd).val().replace(/\s/g, '');
            callStartGeocoder({ 'qs': start, 'country_code': '' });
            callEndGeocoder({ 'qs': end, 'country_code': '' });
            routing_timeout = setInterval(getDirections, 500);
        });
        $('#' + divToggle).click(function(event) {
            event.preventDefault();
            if (!$(this).hasClass('toggled')) {
                $(this).addClass('toggled');
                if ($('#' + divRouteStep).text() != '') {
                    $('#' + divRouteStep).show();
                }
                else {
                    $('#' + divMapSearchPane).show();
                }
            }
            else if ($(this).hasClass('toggled')) {
                $(this).removeClass('toggled');
                $('#' + divLoader + ', #' + divMapSearchPane + ', #' + divRouteStep).hide();
            }
        });
    }
}

/*function addDraggableTabbedMarker() {
mapviewer.removeAllOverlays();
var pos = mapviewer.getCurrentPosition(); 
marker = mapviewer.createMarker( pos, {'label' : 'Draggable marker', 'draggable' : true } );
var tabs = [
new MMInfoBoxTab( 'Tab 1', '<h1>Tab 1 Body<' + '/h1>' ),
new MMInfoBoxTab( 'Tab 2', '<h1>Tab 2 Body with more content<' + '/h1>' ),
new MMInfoBoxTab( 'Tab 3', '<h1>Tab 3 Body<' + '/h1><p>There is some more content in here<' + '/p>' ),
];
marker.setInfoBoxContent( tabs ); 
marker.openInfoBox (); 
} */




// Function to clear-down fully any marker variable history:
function removeAllOverlaysAndHistory() {
    mapviewer.removeAllOverlays();
    marker = null;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function endGeocode(type, target, location, error_code) {



    var PostCodes = new String();
    PostCodes = document.getElementById(divTrips).innerHTML;
    var PostCodesArray = new Array();
    PostCodesArray = PostCodes.split("~");
    var Counter = 0;
    for (Counter = 0; Counter < PostCodesArray.length - 2; Counter += 3) {
        var PostCode = trim(PostCodesArray[Counter].replace("&nbsp;", " "));
        var TripDescription = PostCodesArray[Counter + 1];
        var TripName = PostCodesArray[Counter + 2];
        addMarkerByCountryAndPostCode(countryCode, PostCode, String(TripDescription), String(TripName), (Counter / 3) + 1);
    }



    /*if( error_code ) {
    alert( 'There was a problem geocoding that address: '+error_code );
    return;
    } 
        
    mapviewer.removeOverlay( marker );
    addMarker();*/
}

// -----------------------------------------------------------


function onLoad() {
    // Construct Map Viewer and display default location:
//     mapviewer = MMFactory.createViewer( document.getElementById( 'mapviewer' ) );
//     mapviewer.goToPosition( new MMLocation( new MMLatLon( 42.3508, -71.0717 ) ,15 ) );
    showMap();
    // Construct the route requester with our callback function:
    var funcRef = resultsLoaded;
    route_finder = MMFactory.createRouteRequester( funcRef, mapviewer );

    loading = document.getElementById( divLoader );
    loadingStatus( false );
}

function loadingStatus( bool ) {
    // If we're loading values we want to disable the form elements
    // and display a spinning icon to show activity
    loading.style.display = bool ? 'block' : 'none';
}

function createStepMarker(location, instruction, text, zindex) {
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}        

function callRoute() {
    cleanUp();
    // Add each of the selected waypoints. The addLocation function will only add
    //  a location if a selection was made from the corresponding select box:
    var locations = new Array();
    
    locations.push(new MMLocation(start_latlong));
    locations.push(new MMLocation(end_latlong));

    loadingStatus( true );
    route = new MMRoute( locations );
		var shortest = document.getElementById(shortestId).checked;
		var time = document.getElementById(timeId).checked;
    if (shortest == true) {
        route.optimize_for = 'distance';
    } else if (time == true) {
        route.optimize_for = 'time';
    } 

    var walking = document.getElementById(walkingId).checked;
		var driving = document.getElementById(drivingId).checked;
    if (walking == true) {
        route.mode = 'walking';
    } else if (driving == true) {
        route.mode = 'driving'; 
    }
        
    route_finder.request(route);
}
   
function cleanUp () {
    // Remove any existing route and directions, in preparation for displaying a new one:    
    var stepsContainer = document.getElementById(divRouteStep);
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    stepsContainer.style.display = 'none';
    mapviewer.removeAllOverlays();
    markers = new Array();
}

function resultsLoaded() {
    if (route.error_code) {
        // Display an error message, if applicable:
				var container = document.getElementById(divRouteStep);
				container.innerHTML = '<div class="directions">We are sorry - the following error occurred: <' + 'br/><br /><' + 'em>' + route.error_explanation + '<' + '/em></div><a id="backlink" href="javascript:resetSearch()">New Search</a>';
				container.style.display = 'block';
				error_occured = true;
    } else {
        // use getAutoScaleLocation to show the entire route on the map, with the route bounds:
        mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
        displayStages(route);
        // Show the route on the map with PolyLines, by adding each polyline returned:
        for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
          mapviewer.addOverlay(route.polyLine[i]);
        }
    }
    loadingStatus( false );
}
function resetSearch(){
    document.getElementById(divRouteStep).style.display='none'; 
    document.getElementById(divRouteStep).innerHTML=''; 
    document.getElementById(divMapSearchPane).style.display='block';
}

function displayStages(route) {
    var curr_step = 1;
    var stages = route.stages; 
    var container = document.getElementById(divRouteStep);
		var directions = document.createElement('div');
		directions.className="directions";
    var h2 = document.createElement('h2');
    h2.appendChild(document.createTextNode('Travel directions'));
    directions.appendChild(h2);
    
    var summary = '';
    // Show the total route distance in Miles:
    summary += 'Total Distance: ' + route.distance.miles + ' mile(s)';
    // Show the total duration of trip. Note that we display the Days, Hours, and Minutes by
    //  accessing each property: 
    summary += '<br />Estimated Total Time: ';
    if (route.duration.Days > 0) { summary += route.duration.days + ' day(s) '; }
    if (route.duration.Hours > 0) { summary += route.duration.hours + ' hour(s) '; }
    if (route.duration.Minutes > 0) { summary += route.duration.minutes + ' minute(s) '; }
    var p = document.createElement('p');
		p.className = 'summary';
    p.innerHTML = summary;
    directions.appendChild(p);
    
    // The route will be returned in stages. Each stage goes from one specified 'location' to the next:
    for (var count=0; count < stages.length; count++) {
        // Show some summary information about each stage:
        var stage_summary = '';
        stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
        // Show the stage distance, in miles:
        stage_summary += '<br />Stage Distance: ' + stages[count].distance.miles + ' mile(s)';
        // Show the stage duration, in days, hours and minutes:
        stage_summary += '<br />Estimated Stage Time: ';
        if (stages[count].duration.days > 0) { stage_summary += stages[count].duration.days + ' day(s) '; }
        if (stages[count].duration.hours > 0) { stage_summary += stages[count].duration.hours + ' hour(s) '; }
        if (stages[count].duration.minutes > 0) { stage_summary += stages[count].duration.minutes + ' minute(s) '; }
        var p = document.createElement('p');
				p.className = 'stage';
        p.innerHTML = stage_summary;
        directions.appendChild(p);
        
        var ol = document.createElement('ul');
        ol.id = 'stage_' + count;
        ol.start = curr_step;

        var steps = stages[count].steps;
    
        // Now we will display each step instruction within this stage:
        for (var stepCount=0; stepCount < steps.length; stepCount++) {
            // Label the current marker with the step number:
            var text = curr_step;
            // Make the higher numbered step markers appear 'on top of' lower ones:
            var zindex = max_zindex - curr_step + 1;
            
            // Use 'S' as marker text if this is the first step of the entire route:
            if (count == 0 && stepCount  == 0) {
                text = 'S';
            }        
            // Use 'F' as marker text if this is the last step of the entire route:      
            if (count == stages.length - 1 && stepCount  == steps.length - 1) {
                text = 'F';
                zindex = max_zindex; 
           }                
            // Create a written 'instruction' using the roadname and/ or roadnumber:
            var instruction = steps[stepCount].instruction;
            var roadname = steps[stepCount].road_name;
            var roadnumber = steps[stepCount].road_number; 

            if (roadname && roadnumber) {
                instruction += '<br />' + roadname + ' (' + roadnumber + ') ';
            } else if (roadname) {
                instruction += '<br />' + roadname + ' ';
            } else if (roadnumber) {
                instruction += '<br />' + roadnumber + ' ';
            }
            
            // Show the distance of this particular step:
            var distance = '';                    
            if (steps[stepCount].distance.miles > 0) { distance += steps[stepCount].distance.miles + ' mile(s) '; }
            if (distance != '') { distance = '' + distance + '' };
            
            var li = document.createElement('li');
            li.innerHTML = '<span class="mark">'+text+'</span><span class="info"><strong>'+ instruction +'</strong><br /><span class="mileage">' + distance + '<'+'/span></span><br style="clear: both;" />';
            ol.appendChild(li);
            
            // Create the step marker, using the instruction and marker text we previously created:
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            
            ++curr_step;
        }
				
				directions.appendChild(ol);
        container.appendChild(directions);
				var backlink=document.createElement('div');
				backlink.innerHTML='<a id="backlink" href="javascript:resetSearch()">New Search</a>';
				container.appendChild(backlink);
    }


    container.style.display = 'block';
    $('#' + divMapSearchPane).hide();
    $('#routeSteps ul').jScrollPane();
    // Add copyright and disclaimer, as required:
		/*
    var copyright = '';
    if (route.copyright) {copyright += 'Copyright: ' + route.copyright; }
    if (route.disclaimer)  {copyright += '<br />Disclaimer:  <a href="' + route.disclaimer +'">' + route.disclaimer +'<' + '/a>'; }
    
    var p = document.createElement('p');
    p.innerHTML = copyright;
    container.appendChild(p);            
		*/
}

// --------------------------------------------------------------------

function callStartGeocoder( fields ) {
		start_geocoded = false;
    // create a new address object
    var address = new MMAddress();
    address.qs = fields.qs;
    
    // clear any existing items from previous geocoding requests
    cleanUp();
    // perform the geocode
    start_geocoder = MMFactory.createGeocoder(processStartResults);
    start_geocoder.count = max_results;
    start_geocoder.geocode(address);
}

function processStartResults() {
    
    // callback function registered with the geocoder to handle geocoding results
    // if an error occurred, inform the user
    if (start_geocoder.error_code && start_geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
        var container = document.getElementById(divRouteStep);
        container.innerHTML = '<div class="directions">We are sorry - the following error occurred: <' + 'br /><br /><' + 'em>' + start_geocoder.error_explanation + '<' + '/em></div><a id="backlink" href="javascript:resetSearch()">New Search</a>';
        container.style.display = 'block';
				error_occured = true;
        return false;
    }
    results = start_geocoder.result_set;
    if(results != null){
        //loop through the result set
        for (var count=0; count < results.length; count++) {
            var address = results[count].address;
            start_latlong = results[count].coords;
            //console.log('Start: '+start_latlong);
				    start_geocoded = true;
            $('#' + divStart).trigger('start:loaded');
        }
    }
}

function callEndGeocoder( fields ) {
		end_geocoded = false;
    // create a new address object
    var address = new MMAddress();
    address.qs = fields.qs;
    
    // clear any existing items from previous geocoding requests
    cleanUp();
    // perform the geocode
    end_geocoder = MMFactory.createGeocoder(processEndResults);
    end_geocoder.count = max_results;
    end_geocoder.geocode(address);
}

function processEndResults() {
    
    // callback function registered with the geocoder to handle geocoding results
    // if an error occurred, inform the user
    if (end_geocoder.error_code && end_geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
        var container = document.getElementById(divRouteStep);
        container.innerHTML = '<div class="directions">We are sorry - the following error occurred: <' + 'br /><br /><' + 'em>' + end_geocoder.error_explanation + '<' + '/em></div><a id="backlink" href="javascript:resetSearch()">New Search</a>';
        container.style.display = 'block';
				error_occured = true;
        return false;
    }
    results = end_geocoder.result_set;
    if(results != null){
        //loop through the result set
        for (var count=0; count < results.length; count++) {
            end_latlong = results[count].coords;
            //console.log("End: "+end_latlong);
				    end_geocoded = true;
            $('#' + divEnd).trigger('end:loaded');
        }
      }
  }

  function printMap(name) {
      var postCode = document.getElementById(divSearch).innerHTML;
 
      var query = "";
      var pos = mapviewer.getCurrentPosition();
      query += "lat=" + pos.lat;
      query += "&lon=" + pos.lon;
      if(!error_occured){
          if( end_geocoder != null){
             if(typeof start_geocoder != 'undefined'){
                  query += "&qs_1=" + start_geocoder.result_set[0].address.postal_code;
                  query += "&countryCode_1=" + countryCode;
              }
             query += "&qs_2=" + end_geocoder.result_set[0].address.postal_code;
             query += "&countryCode_2=" + countryCode;
             query += "&displayName_2=" + name; 
             query += "&advanced=true";
             var url="http://www.multimap.com/directions/print/?";
          }
          else{
             var url="http://www.multimap.com/maps/print/?";
             if( start_geocoder != null){
                  query += "&loc_lat=" + start_geocoder.result_set[0].coords.lat;
                  query += "&loc_lon=" + start_geocoder.result_set[0].coords.lon;
              }
             query += "&displayName=" + name;
             
          }
          
          if( route != null){
              query += "&mode=" + route.mode;
              query += "&optimizeFor=" + route.optimize_for;
          }
      }
      query += "&zoomFactor=" + mapviewer.getZoomFactor();
      query += "&mapType=" + mapviewer.getMapType();  
  

      
     
//?countryCode=GB&lat=55.347&lon=-2.29369&zoomFactor=6&loc_lat=51.509&loc_lon=-0.1261&mapType=4&displayName=sdfsdfsdf
      
//http://www.multimap.com/directions/print/?qs_1=ST10&countryCode_1=GB&qs_2=ST10+4DB&countryCode_2=GB&mode=driving&optimizeFor=time&tab=list&zoomFactor=14&lat=52.99496&lon=-1.92346&qs=ST10+4DB&countryCode=GB&&mapType=4&advanced=true     
      pagePrintPreview = window.open(url + query, "PrintPreview", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=800,height=800,left = 340,top = 212");

  }
//]]> 
// -->