﻿var map;
var gdir;
var storeAddress;
var fromAddress;
var toAddress;
var dirn;
var html = "";

/*  */

function delayDirections()
{
        customPanel(map,"map",dirn,document.getElementById("directions"));
}

        // ============ custom direction panel ===============
        function customPanel(map,mapname,dirn,div) {
            // ===== local functions =====

            // === waypoint banner ===
            function waypoint(point, type, address) {
                var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
                html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
                html += '  <tr style="cursor: pointer;" onclick='+target+'>';
                html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
                html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
                html += '    </td>';
                html += '    <td style="vertical-align: middle; width: 100%;">';
                html +=        address;
                html += '    </td>';
                html += '  </tr>';
                html += '</table>';
            }

            // === route distance ===
            function routeDistance(dist) {
                html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '</div>';
            }      

            // === step detail ===
            function detail(point, num, description, dist) {
                var target = '"' + mapname+".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; text-align: right;">';
                html += '      <a href="javascript:void(0)"> '+num+'. </a>';
                html += '    </td>';
                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>';
            }

            // === Copyright tag ===
            function copyright(text) {
                html += '<div style="font-size: 0.86em;">' + text + "</div>";
            }

            // === read through the GRoutes and GSteps ===
            for (var i=0; i<dirn.getNumRoutes(); i++) {
                if (i==0) {
                    var type="play";
                } else {
                    var type="pause";
                }
                var route = dirn.getRoute(i);
                var geocode = route.getStartGeocode();
                var point = route.getStep(0).getLatLng();
                // === Waypoint at the start of each GRoute
                waypoint(point, type, geocode.address);
                routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");

                for (var j=0; j<route.getNumSteps(); j++) {
                    var step = route.getStep(j);
                    // === detail lines for each step ===
                    detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
                }
            }

            // === the final destination waypoint ===   
            var geocode = route.getEndGeocode();
            var point = route.getEndLatLng();
            waypoint(point, "stop", geocode.address);

            // === the copyright text ===
            copyright(dirn.getCopyrightsHtml());

            // === drop the whole thing into the target div
alert(html);
            div.innerHTML = html;

        } // ============ end of customPanel function ===========
        
function showDirections_new()
{
    if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById(directionsMap));
        dirn = new GDirections(map);

        GEvent.addListener(dirn,"error", function() {
            alert("Directions Failed: "+dirn.getStatus().code);
        });

        dirn.load("from: Blackpool to: Preston to: Blackburn", {getSteps:true});

        // ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
        // == The delay is required in case we rely on GDirections to perform the initial setCenter ==
        GEvent.addListener(dirn,"load", function() {
            //setTimeout('customPanel(map,"map",dirn,document.getElementById("directions"))', 1);
            setTimeout('delayDirections()', 1);
        });
    }
}

function showDirections()
{
   
   
   if (GBrowserIsCompatible())
    {
      
   // Size the map to the smaller version and show
        // the directions pane.
        setElementDimensions(directionsMap, 505, 480);
        setElementDimensions(directions, 360);

		// using showelement from menu.js -- takes obj as parameter
        showElement(document.getElementById(directions));

        map = new GMap2(document.getElementById(directionsMap));
        map.addControl(new GLargeMapControl());

        // add the map/satellite/hybrid controls
        map.addControl(new GMapTypeControl());

        gdir = new GDirections(map, document.getElementById(directions));
/*
        G_START_ICON.image = "images/icon_start.png";
        G_START_ICON.iconSize = new GSize(44, 26);
        G_START_ICON.iconAnchor = new GPoint(22, 13);
        G_START_ICON.shadow = "images/icon_start_shadow.png";
        G_START_ICON.shadowSize = new GSize(83, 28);

        // G_PANEL_ICON.image = "images/icon_start.png";
        // GDirections.PANEL_ICON
        
        G_END_ICON.image = "images/ikea_logo_flagger_top.png";
        G_END_ICON.iconSize = new GSize(56, 25);
        G_END_ICON.shadowSize = new GSize(75, 30);
        G_END_ICON.iconAnchor = new GPoint(28, 13);
        G_END_ICON.shadow = "images/ikea_logo_flagger_shadow.png";
*/
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        setDirections(fromAddress, toAddress, "en" );
/*
        // Override default marker
        var icon = new GIcon();
        icon.image = "images/IKEAicon.gif";
        icon.shadow = "";
        icon.iconSize = new GSize(41, 15);
        icon.shadowSize = new GSize(0, 0);
        icon.iconAnchor = new GPoint(18, 8);
        icon.infoWindowAnchor = new GPoint(18, 0);

        var marker = new GMarker(map.getCenter(), icon);

        var marker = gdir.getMarker(0);
        alert(marker);             // = marker;
*/
    //var poly = gdir.getPolyline(); 
//alert(poly);
//    var startPoint = poly.getVertex(0); 
//    var endPoint = poly.getVertex(poly.getVertexCount()-1); 
//alert(startPoint);
//alert(endPoint);
    }
}

function setDirections(fromAddress, toAddress, locale)
{
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function handleErrors()
{
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	    //showErrMsg("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	    showErrMsg("The address you entered is invalid or could not be found.");
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	    //showErrMsg("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	    showErrMsg("The address you entered is invalid or could not be found.");
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	    //showErrMsg("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.\n Error code: " + gdir.getStatus().code);
	    showErrMsg("The address you entered is invalid or could not be found.");
    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	    showErrMsg("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else
    {
        showErrMsg("An unknown error occurred.");
        hideElement("directions");
        hideElement("map");
    }
}

function showErrMsg(message)
{
    showElement(document.getElementById(divErrMsg));
    document.getElementById(divErrMsg).innerHTML = message;
    document.getElementById(divErrMsg).className = "errorMessage";

    // Hide the directions pane and show the full size
    // non-directions map.
	
    hideElement(document.getElementById(directions));
    hideElement(document.getElementById(map));
    //showNonDirectionsMap();
}

function hideErrMsg()
{
    document.getElementById(divErrMsg).innerHTML = "";
    hideElement(document.getElementById(divErrBox));
    document.getElementById(divErrBox_FromAdr).className = "";
}

function onGDirectionsLoad()
{
    // Use this function to access information about the latest load() results.
    // Ex:   document.getElementById("getStatus").innerHTML = gdir.getStatus().code;

    // If the status code returns a succesful completion then wait half a second for the
    // page to finish rendering, then loop through all "<td>" tags and replace any text
    // containing coordinates with a customer friendly address.
    if (gdir.getStatus().code == 200)
    {
	    var t=setTimeout("replaceCoordinates();",500)
    }
}

function replaceCoordinates()
{
    var searchFor = "42.299626, -71.382411";
    var replaceWith = "1245 Worcester Street, Natick, MA 01760";

    var allTD = document.getElementsByTagName("td");
    var countTD = allTD.length;

    for (var iElement = 0; iElement < countTD; iElement++)
    {
	    // Compare only the first 5 digits. Google at times will append a trailing
	    // "0" to the coordinates passed in, which will break the search logic if
	    // we compare the entire string.
	    if (allTD.item(iElement).innerHTML.substring(0, 5) == searchFor.substring(0,5))
	    {
		    allTD.item(iElement).innerHTML = replaceWith;
	    }
    }
}

function showMap()
{
    if (GBrowserIsCompatible())
    {
        hideElement("directions");
        // Set map to use entire page width.
        setElementDimensions("map", 505, 480);

        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());

        // Get the store info to display in the info window
        var coordinates = toAddress;

        // Create an array element for each group of store info
        var arrCoordinates = coordinates.split(", ");

        var mapPoint = new GLatLng(arrCoordinates[0], arrCoordinates[1]);

        var tab1Header = "Address";
        var tab1Contents = storeAddress;

        map.setCenter(mapPoint, 8);

        var icon = new GIcon();
        icon.image = "images/ikea_logo_flagger_top.png";
        icon.shadow = "images/ikea_logo_flagger_shadow.png";
        icon.iconSize = new GSize(83, 30);
        icon.shadowSize = new GSize(103, 34);       
        icon.iconAnchor = new GPoint(42, 31);
        icon.infoWindowAnchor = new GPoint(42, 2);
        
        var marker = new GMarker(map.getCenter(), icon);
        //var marker = new GMarker(map.getCenter());

        // Our info window content
        var infoTabs = [
	        new GInfoWindowTab(tab1Header, tab1Contents)//,
	        //new GInfoWindowTab(tab2Header, tab2Contents)
        ];

        GEvent.addListener(marker, "click", function() {
			        marker.openInfoWindowTabsHtml(infoTabs);
		        });

        // Add point to the map
        map.addOverlay(marker);

        // Set the map zoom
        map.setZoom(map.getZoom() + 8);

        // Open info window automatically
        marker.openInfoWindowTabsHtml(infoTabs);
        
        // add the map/satellite/hybrid controls
        map.addControl(new GMapTypeControl());
        
        map.enableScrollWheelZoom();        
        map.savePosition();
    }
}

function cellClick(name)
{
    var index = getStoreIndex(name)
    stores[index].marker.openInfoWindowTabsHtml(stores[index].infoTabs);
    var mapPoint = new GLatLng(stores[index].latitude, stores[index].longitude);
    map.setCenter(mapPoint, 11);
}

function storeMarkerClick(name)
{
		if (rows != null)
		{
			var index = getRowIndex(name)
			rowClick(row[index][0], row[index][2]);
		}
}

function showStoresMap(lat, lng)
{
    if (GBrowserIsCompatible())
    {
        // Set map to use entire page width.
        setElementDimensions(resultsMap, 505, 480);

        map = new GMap2(document.getElementById(resultsMap));
		
        map.addControl(new GLargeMapControl());

        // get the GLatLngBounds object
        var bounds = getBoundsObject(lat, lng, stores);

        // set the center point of the map
        var mapPoint = bounds.getCenter();

        var tab1Header = "Address";
        var tab1Contents = "<b>Your starting address:</b><br>" + fromAddress;

        map.setCenter(mapPoint);

//        var marker = new GMarker(new GLatLng(lat, lng));
        
				var icon = new GIcon();
				icon.image = "images/icon_start.png";
				icon.shadow = "images/icon_start_shadow.png";
				icon.iconSize = new GSize(44, 26);
				icon.shadowSize = new GSize(83, 28);
				icon.iconAnchor = new GPoint(22, 13);
				icon.infoWindowAnchor = new GPoint(18, 0);
    
				var marker = new GMarker(new GLatLng(lat, lng), icon);

        // Our info window content
        var infoTabs = [
	        new GInfoWindowTab(tab1Header, tab1Contents)//,
	        //new GInfoWindowTab(tab2Header, tab2Contents)
        ];

        GEvent.addListener(marker, "click", function() {
			        marker.openInfoWindowTabsHtml(infoTabs);
		        });
/*
				if (rows != null)
				{
					GEvent.addListener(marker, "click", function() {
							storeMarkerClick('Stoughton');
		        });
				}
*/				
        // add the markers for the closest stores
        showStores(stores)
        
        // Add point to the map
        map.addOverlay(marker);

        // Set the map zoom
        var zoomLevel = map.getBoundsZoomLevel(bounds);
        map.setZoom(zoomLevel);

        // add the map/satellite/hybrid controls
        map.addControl(new GMapTypeControl());

        map.enableScrollWheelZoom();
        map.savePosition();
    }
}

function getBoundsObject(lat, lng, storeArray)
{
    var minLat = lat;
    var maxLat = lat;
    var minLng = lng;
    var maxLng = lng;

    for (var i = 0; i < storeArray.length; i++)
    {
        if (storeArray[i].latitude < minLat)
        {
            minLat = storeArray[i].latitude;
        }
        else if (storeArray[i].latitude > maxLat)
        {
            maxLat = storeArray[i].latitude;
        }

        if (storeArray[i].longitude < minLng)
        {
            minLng = storeArray[i].longitude;
        }
        else if (storeArray[i].longitude > maxLng)
        {
            maxLng = storeArray[i].longitude;
        }
    }
//    alert('minLat = ' + minLat + '\nmaxLat = ' + maxLat + '\nminLng = ' + minLng + '\nmaxLng = ' + maxLng);
    return new GLatLngBounds(new GLatLng(maxLat, minLng), new GLatLng(minLat, maxLng)); 
}

function Store() {
}

function showUSMap()
{
    if (GBrowserIsCompatible())
    {
        // Set map to use entire page width.
        setElementDimensions(USmap, 505, 340);

        map = new GMap2(document.getElementById(USmap));
        map.addControl(new GLargeMapControl());

        var mapPoint = new GLatLng(37.5, -95);

        var tab1Header = "Address";
        var tab1Contents = fromAddress;

        map.setCenter(mapPoint, 7);

        showStores(stores);

        // Set the map zoom
        map.setZoom(map.getZoom() - 4);

        // add the map/satellite/hybrid controls
        map.addControl(new GMapTypeControl());

        map.enableScrollWheelZoom();
        map.savePosition();
    }
}

function showStores(storeArray)
{
    for (var i = 0; i < storeArray.length; i++)
    {
        marker = getMarker(storeArray[i]);

        storeArray[i].marker = marker;
        
        // Add point to the map
        map.addOverlay(marker);
    }
}

function showPopup(name)
{
    var index = getStoreIndex(name)
    if (index != null) {
			stores[index].marker.openInfoWindowTabsHtml(stores[index].infoTabs);
    }
}

function getStoreIndex(name)
{
    for (var i = 0; i < stores.length; i++)
    {
        if (stores[i].name == name)
        {
            return i;
        }
    }
}

function getRowIndex(name)
{
    for (var i = 0; i < rows.length; i++)
    {
        if (rows[i][1].name == name)
        {
            return i;
        }
    }
}

function getMarker(store)
{
    var icon = new GIcon();
    icon.image = "images/ikea_logo_flagger_top.png";
    icon.shadow = "images/ikea_logo_flagger_shadow.png";
    icon.iconSize = new GSize(83, 30);
    icon.shadowSize = new GSize(103, 34);
    icon.iconAnchor = new GPoint(42, 31);
    icon.infoWindowAnchor = new GPoint(42, 2);
    
    var marker = new GMarker(new GLatLng(store.latitude, store.longitude), icon);
    
    var tab1Header = 'Address';
    var strAddressText = '<span class="tab"><b>IKEA ' + store.name + '</b><br>'
    strAddressText += store.address + '<br>';
    strAddressText += store.city + ', ';
    strAddressText += store.state + ' ';
    strAddressText += store.zip + '<br/><br/>';
    strAddressText += '<b>Get directions:<br/></b>';
		if (fromAddress != null){
			strFromAddress = fromAddress;
		}
		else{
			strFromAddress = '';
		}		
    strAddressText += '<input type="text" id="address' + store.id + '" value="' + strFromAddress + '" onkeyup="if(event.keyCode==\'13\') {submitMarkerDirections(this.value, \'' + store.StoreCodeName + '\');}">';
    strAddressText += '<input type="button" value="Go" onclick="getDirections(\'' + store.StoreCodeName + '\', document.getElementById(\'address' + store.id + '\').value);"><br/></span>';
    var tab1Contents = strAddressText;

    var tab2Header = 'Store Info';
    var strStoreInfoText = '<b>IKEA ' + store.name + '</b><br>';
    if (store.phone != '')
    {
        strStoreInfoText += 'Phone: ' + store.phone + '<br>';
    }
		strStoreInfoText += 'Hours: ' + store.hours + '<br>';
		strStoreInfoText += '<center>';
		strStoreInfoText += '<a href="' + store.StoreLink + '" target="_blank"><img src="images/btn_gotostore.gif" border="0"></a><br>';

    if (store.VirtualTourLink != '')
    {
        strStoreInfoText += '<a href="' + store.VirtualTourLink + '" target="_blank">Take a virtual tour</a>'
    }
    strStoreInfoText += '</center>';
    var tab2Contents = strStoreInfoText
        
    // Our info window content
    var infoTabs = [
        new GInfoWindowTab(tab1Header, tab1Contents),
        new GInfoWindowTab(tab2Header, tab2Contents)
    ];

    store.infoTabs = infoTabs;
    
    GEvent.addListener(marker, "click", function() {
	        marker.openInfoWindowTabsHtml(store.infoTabs);
	    });
	    
    return marker;
}

function getDirections(storeid, address)
{
    //alert(storeid);
    //alert(address);
    document.location.href = 'Directions.aspx?Store=' + storeid + '&Address=' + address;
}

function showElement(elementID)
{	
    document.getElementById(elementID).style.display = "block";
    document.getElementById(elementID).style.visibility = "visible";
}

function hideElement(elementID)
{
    document.getElementById(elementID).style.display = "none";
    document.getElementById(elementID).style.visibility = "hidden";
}

function setElementDimensions(elementID, width, height)
{
    document.getElementById(elementID).style.width = width + "px";
		if (height != null){
			document.getElementById(elementID).style.height = height + "px";
		}
}

function submitMarkerSearch(strValue)
{
	if (strValue != '')
	{
		document.getElementById('txtAddress').value = strValue;
		document.forms[0].submit();
	}
}


function submitSearch() {



	if (document.getElementById(txtAddress).value != '')
	{
		// document.forms[0].submit();

	     document.getElementById('aspnetForm').submit();


	}
}



function submitMarkerDirections(strValue, strStore)
{
	if (strValue != '')
	{
		document.location.href = 'Directions.aspx?store=' + strStore + '&address=' + URLEncode(strValue);
	}
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}
