﻿// JScript File
    var map;
    var gdir;
    var geocoder = null;
    var addressMarker;
	var gmarkers = [];
	var htmlAddresses = [];
	var originalAddresses = [];
    var mquerystring='';
    var zone = 33       // NORWAY
    var southhemi = false;
    
    function initializeToAddress(toaddress) {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
		    
		  map.addControl(new GLargeMapControl());
		  map.addControl(new GHierarchicalMapTypeControl());

          // bind a search control to the map, suppress result list
          //map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
		geocoder = new GClientGeocoder();
        map.setCenter(new GLatLng(65.472024, 10.468946), 4);
        setDirections('', toaddress, 'no');
      }
    }

    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
		    
		  map.addControl(new GLargeMapControl());
		  map.addControl(new GHierarchicalMapTypeControl());

          // bind a search control to the map, suppress result list
          //map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
		geocoder = new GClientGeocoder();
        if (gup("lat")=="" || gup("lng")=="" || gup("z")=="")
        {
	        map.setCenter(new GLatLng(65.472024, 10.468946), 4);
            setDirections(gup("from"), gup("to"), 'no');
	    }
	    else
	    {
	        map.setCenter(new GLatLng(gup("lat"), gup("lng")), gup("z"));
        }
      }
    }

    function initializesmall() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
          //map.removeMapType(G_HYBRID_MAP);
		  map.addControl(new GSmallMapControl());
		  //map.addControl(new GMapTypeControl());
		  map.addControl(new GHierarchicalMapTypeControl());

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
		geocoder = new GClientGeocoder();
	    map.setCenter(new GLatLng(65.472024, 10.468946), 4);
      }
    }

    function setDirections(fromAddress, toAddress, locale) {
		var i=1;
		var viaString='';
		while(document.getElementById("via" + i)!=null)
		{
			viaString+=" to: " + DecodeChars(document.getElementById("via" + i).value);
			i++;
		}
		//alert("from: " + fromAddress + viaString + " to: " + toAddress);
		fromAddress = DecodeChars(fromAddress);
		toAddress = DecodeChars(toAddress);
	    if(fromAddress!='' && (toAddress!='' || viaString!=''))
	    {
	        //document.getElementById("spnWebMapSearchCount").innerHTML = WebMapSearchCount(toAddress);
            document.getElementById("tblRoute").style.display='';
	    	showFirmAddress(toAddress, locale, true);
	    	gdir.load("from: " + fromAddress + viaString + " to: " + toAddress,{ "locale": locale });
	    	document.getElementById("directions").style.height='400px';
	    }
	    else if(toAddress!='' && (window.location.href.toLowerCase().indexOf("mapsearchfirm.aspx")>-1 || window.location.href.toLowerCase().indexOf("mapsearchperson.aspx")>-1))
	        showFirmAddress(toAddress, locale, false);
	    else if(toAddress!='' && window.location.href.toLowerCase().indexOf("mapsearch.aspx")>-1)
	    {
	    	showFirmAddress(toAddress, locale, false);
	        showToAddress(toAddress, locale, false);
	    }
	    else if(fromAddress!='' && window.location.href.toLowerCase().indexOf("mapsearch.aspx")>-1)
	    {
	    	showFirmAddress(fromAddress, locale, false);
	        showToAddress(fromAddress, locale, false);
	    }
		else if(toAddress!='')
			showAddress(toAddress, locale);

		return true;
    }

    function gup(name)
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		var returnValue='';
		if( results != null )
		{
			returnValue = DecodeChars(results[1]);
		}
		return returnValue;
			
	}
    
    function DecodeChars(returnValue)
    {
        while(returnValue.indexOf('%C3%A6')>-1)
			returnValue = returnValue.replace('%C3%A6', 'æ');

        while(returnValue.indexOf('%c3%a6')>-1)
			returnValue = returnValue.replace('%c3%a6', 'æ');

		while(returnValue.indexOf('%C3%86')>-1)
			returnValue = returnValue.replace('%C3%86', ('æ').toUpperCase());
			
		while(returnValue.indexOf('%C3%B8')>-1)
			returnValue = returnValue.replace('%C3%B8', 'ø');

		while(returnValue.indexOf('%c3%b8')>-1)
			returnValue = returnValue.replace('%c3%b8', 'ø');

		while(returnValue.indexOf('%C3%98')>-1)
			returnValue = returnValue.replace('%C3%98', ('Ø'));

		while(returnValue.indexOf("%C3%A5")>-1)
			returnValue = returnValue.replace('%C3%A5', 'å');

		while(returnValue.indexOf("%c3%a5")>-1)
			returnValue = returnValue.replace('%c3%a5', 'å');

		while(returnValue.indexOf("%C3%85")>-1)
			returnValue = returnValue.replace('%C3%85', ('å').toUpperCase());

		while(returnValue.indexOf("%26")>-1)
			returnValue = returnValue.replace('%26', '&');

		while(returnValue.indexOf('%20')>-1)
			returnValue = returnValue.replace('%20', ' ');

		while(returnValue.indexOf('+')>-1)
			returnValue = returnValue.replace('+', ' ');

		while(returnValue.indexOf('%2B')>-1)
			returnValue = returnValue.replace('%2B', '+');
			
	    return returnValue;
    }
    
    function ParseForQueryString(returnValue)
	{
	    return returnValue;
	    
	    //CODE IS CORRECT BUT NOT IN USE : LOVEY THAKRAL
	    // dont remove the following code
		while(returnValue.toLowerCase().indexOf('æ')>-1)
		{
			returnValue = returnValue.replace('æ', '%c3%a6');
        }

		while(returnValue.indexOf(('æ').toUpperCase())>-1)
		{
			returnValue = returnValue.replace(('æ').toUpperCase(), '%C3%A6');
        }
			
		while(returnValue.indexOf('ø')>-1)
		{
			returnValue = returnValue.replace('ø', '%c3%b8');
        }

		while(returnValue.indexOf(('ø').toUpperCase())>-1)
		{
			returnValue = returnValue.replace(('ø').toUpperCase(), '%C3%B8');
        }

		while(returnValue.indexOf("å")>-1)
		{
			returnValue = returnValue.replace('å', '%c3%a5');
        }

		while(returnValue.indexOf(('å').toUpperCase())>-1)
		{
			returnValue = returnValue.replace(('å').toUpperCase(), '%C3%A5');
        }

		while(returnValue.indexOf("&")>-1)
		{
			returnValue = returnValue.replace('&', '%26');
        }

		while(returnValue.indexOf(' ')>-1)
		{
			returnValue = returnValue.replace(' ', '%20');
		}

		return returnValue;
			
	}
	
	function ValidateMapRoute()
	{
	    if(document.getElementById("from").value=="")
	    {
	        alert("Start-field must be filled out before calculating route.");
	        document.getElementById("from").focus();
	        return false;
	    }
	    
	    if(document.getElementById("spnVia").innerHTML!="")
	    {
	        var i=1;
		    while(document.getElementById("via" + i)!=null)
		    {
	            if(document.getElementById("via" + i).value=="")
	            {
	                alert("Via" + i + "-field must be filled out before calculating route.");
	                document.getElementById("via" + i).focus();
	                return false;
	            }
			    i++;
		    }
	    }
	    
	    if(document.getElementById("to").value=="")
	    {
	        alert("Stopp-field must be filled out before calculating route.");
	        document.getElementById("to").focus();
	        return false;
	    }
	    
	    return OpenRouteMap(true);
	}
    
    function ValidateMapRouteWithoutWarning()
	{
	    if(document.getElementById("from").value=="")
	    {
	        //alert("Start-feltet må fylles ut før du beregner kjørerute.");
	        document.getElementById("from").focus();
	        return false;
	    }
	    
	    if(document.getElementById("spnVia").innerHTML!="")
	    {
	        var i=1;
		    while(document.getElementById("via" + i)!=null)
		    {
	            if(document.getElementById("via" + i).value=="")
	            {
	                //alert("Via" + i + "-feltet  må fylles ut før du beregner kjørerute.");
	                document.getElementById("via" + i).focus();
	                return false;
	            }
			    i++;
		    }
	    }
	    
	    if(document.getElementById("to").value=="")
	    {
	        //alert("Stopp-feltet må fylles ut før du beregner kjørerute.");
	        document.getElementById("to").focus();
	        return false;
	    }
	    
	    return OpenRouteMap(false);
	}
	
    function OpenRouteMap(IsBtnClick) 
    {
        var locale = 'no';
		var i=1;
		var viaString='';
		
		while(document.getElementById("via" + i)!=null)
		{
			viaString+="&via" + i + "=" + ParseForQueryString(document.getElementById("via" + i).value);
			i++;
		}
		//alert("from=" + document.getElementById("from").value + viaString + "&to=" + document.getElementById("to").value);
//		if (IsBtnClick)
//		{
//		    var theForm = document.forms[0];
//		    theForm.target = "";
//		    theForm.action ="/mapsearch.aspx?from=" + ParseForQueryString(document.getElementById("from").value) + viaString + "&to=" + ParseForQueryString(document.getElementById("to").value);
//		    theForm.submit();
//		}
//		else
		    window.location.href="/mapsearch.aspx?from=" + ParseForQueryString(document.getElementById("from").value) + viaString + "&to=" + ParseForQueryString(document.getElementById("to").value);
        return false;
    }

    function RefreshWebMapSearch(searchValue) 
    {
		window.location.href="/mapsearchweb.aspx?to=" + ParseForQueryString(searchValue);
        return false;
    }
    
	function handleErrors(){
	    var errormsg = 'Unfortunately, we can not find one of the addresses in your route. This may be due to the address you entered is incorrect or is brand new and has not been updated in our map';
//       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
//        errormsg = "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;
//	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
//	     errormsg = "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;
//	   
//	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
//	     errormsg = "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;

//////	   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)
//	     errormsg = "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)
//	     errormsg = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
//	    
//	   else errormsg = "An unknown error occurred.";
	   
	    errormsg = "<span style='color:red'>" + errormsg + "</span>";
	    if (document.getElementById('divSingleAddress')!=null)
	    {
	        document.getElementById('divSingleAddress').innerHTML = errormsg;
            document.getElementById('trSingleAddress').style.display = '';
            document.getElementById('tblRoute').style.display = 'none';
	    }
	    else
            document.getElementById("directions").innerHTML = errormsg;
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
	
	function CreateViaControls(spnVia, value)
	{
		var i=1;
		while(document.getElementById("via" + i)!=null)
		{
			i++;
		}
		if(i>10)
		    return false;
		var viaControl=''
        viaControl += '<table width="285px" border="0" cellspacing="0" cellpadding="0">';
        viaControl += '<tr>';
        viaControl += '<td height="13" align="left" valign="top"></td>';
        viaControl += '</tr>';
        viaControl += '<tr>';
        viaControl += '<td width="100%">';
        viaControl += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
        viaControl += '<tr>';
        viaControl += '<td width="9" align="left" valign="middle">&nbsp;</td>';
        viaControl += '<td width="43" align="left" valign="middle" class="Black Light11" style="font-weight:bold;" id="viaText' + i + '"><img src="/images/map/via' + i + '.gif" /></td>';
        viaControl += '<td width="4" align="left" valign="middle">&nbsp;</td>';
        var btnControl = 'submitRoute';
        viaControl += '<td width="240" align="left" valign="middle"><input type="text" class="TextBox2" id="via' + i + '" style="width:235px; height:21px;" value="' + value + '" onkeyup=\'setAutoSearch(event, this, "submitRoute", "divSearchVia' + i + '", "imgRouteSearch");\' onkeydown=\'selectSearchElement(event, this, "submitRoute", "divSearchVia' + i + '", "imgRouteSearch");\' onkeypress=\'return setSelectedByEnter(event, this, "submitRoute", "divSearchVia' + i + '", "imgRouteSearch", true);\' onblur=\'SetOnBlur(this, "divSearchVia' + i + '", "imgRouteSearch");\' /></td>';
        //viaControl += '<td width="240" align="left" valign="middle"><input type="text" class="TextBox2" id="via' + i + '" style="width:235px; height:21px;" value="' + value + '" onkeypress="return clickButtonVia(event);" /></td>';
        viaControl += '</tr>';
        viaControl += '<tr>';
        viaControl += '<td width="9" align="left" valign="middle"></td>';
        viaControl += '<td width="43" align="left" valign="middle"></td>';
        viaControl += '<td width="4" align="left" valign="middle"></td>';
        viaControl += '<td width="240" align="left" valign="middle"><div id="divSearchVia' + i + '" style="position:absolute; width: 456px; display:none; z-index:9999;" class="BgWhite TblBdr16 Pad5"></div></td>';
        viaControl += '</tr>';
        viaControl += '</table>';
        viaControl += '</td>';
        viaControl += '</tr>';
        viaControl += '<tr>';
        viaControl += '<td width="100%">';
        viaControl += '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
        viaControl += '<tr>';
        viaControl += '<td width="8" align="left" valign="middle">&nbsp;</td>';
        viaControl += '<td width="31" align="left" valign="middle" class="Black Light11">&nbsp;</td>';
        viaControl += '<td width="17" align="left" valign="middle">&nbsp;</td>';
        viaControl += '<td width="124" align="left" valign="middle" class="Light10 Blue3">Address or location</td>';
        viaControl += '<td width="105" align="left" valign="middle" class="Light10 Blue3 link_10"><a href="#" onclick="return MoveUp('+i+')" id="up' + i + '" class="Blue3">Up</a> <a href="#" onclick="return MoveDown('+i+')" id="down' + i + '" class="Blue3">Down</a> <a href="#" onclick="return RemoveViaControls(' + i + ');" id="remove' + i + '" class="Blue3">Remove</a></td>';
        viaControl += '</tr>';
        viaControl += '</table>';
        viaControl += '</td>';
        viaControl += '</tr>';
        viaControl += '</table>';

		var newElement=document.createElement("span" + i);
	    //New we will give it the specified ID so we can manage it later if necessary
	    newElement.setAttribute("id", "spnVia" + i);
	    //Insert the HTML content into the new element
	    newElement.innerHTML=viaControl;
	
	    //Get a reference to the element that will contain the new element
	    var container = document.getElementById(spnVia);
	    //Now we just need to insert our new element into the containing element
	    container.appendChild(newElement, container);
	    
//		document.getElementById(spnVia).innerHTML += viaControl;
		return false;
	}
	
	function SwapSnu()
	{
	    var ctrlValue;
	    var fromControl, toControl;
        fromControl = document.getElementById('from');
        toControl = document.getElementById('to');
	    ctrlValue = fromControl.value;
	    fromControl.value = toControl.value;
	    toControl.value = ctrlValue;
	    
	    return false;
	}
	
	function MoveDown(CtrlId)
	{
	    var ctrlValue;
	    var fromControl, toControl;
	    
	    if (CtrlId=='from')
	    {   
	        fromControl = document.getElementById('from');
	        if(document.getElementById('via1') != null)
	            toControl = document.getElementById('via1');
	        else
	            toControl = document.getElementById('to');
	    }
	    else
	    {
	        fromControl = document.getElementById('via' + CtrlId);
	        if(document.getElementById('via' + (parseInt(CtrlId)+1)) != null)
	            toControl = document.getElementById('via' + (parseInt(CtrlId)+1));
	        else
	            toControl = document.getElementById('to');
	    }
	    
	    ctrlValue = fromControl.value;
	    fromControl.value = toControl.value;
	    toControl.value = ctrlValue;
	    
	    return false;
	}

	function MoveUp(CtrlId)
	{
	    var ctrlValue;
	    var fromControl, toControl;
	    
	    if (CtrlId=='to')
	    {   
	        fromControl = document.getElementById('to');
	        if(document.getElementById('spnVia').innerHTML != '' && document.getElementById('via' +  document.getElementById('spnVia').childNodes.length) != null)
	            toControl = document.getElementById('via' +  document.getElementById('spnVia').childNodes.length);
	        else
	            toControl = document.getElementById('from');
	    }
	    else
	    {
	        fromControl = document.getElementById('via' + CtrlId);
	        if(document.getElementById('via' + (parseInt(CtrlId)-1)) != null)
	            toControl = document.getElementById('via' + (parseInt(CtrlId)-1));
	        else
	            toControl = document.getElementById('from');
	    }
	    
	    ctrlValue = fromControl.value;
	    fromControl.value = toControl.value;
	    toControl.value = ctrlValue;
	    
	    return false;
	}
	
	function RemoveViaControls(CtrlId)
	{
	    // CtrlId == null >> it will remove last element
	    //Get a reference to the element containgint the element we are removing
	    var parentElement = document.getElementById('spnVia');

	    var childElement;
	    if(CtrlId!=null)
	        childElement = document.getElementById('spnVia' + CtrlId);
	    else if(parentElement.childNodes.length==0)
	        return false;
	    else
	    {
	        childElement = document.getElementById('spnVia' + parentElement.childNodes.length);
	    }	    
	    
	    try
	    {
	        parentElement.removeChild(childElement);
	    }
	    catch(e)
	    {
	        childElement = document.getElementById('spnVia' + parentElement.childNodes.length);
	        parentElement.removeChild(childElement);
	        return false;
	    }
	    
	    if(CtrlId!=null)
	    {
	        for(var i=CtrlId; i<=parentElement.childNodes.length; i++)
	        {
                var oldId = parseInt(i+1);
                if(document.getElementById('spnVia' + i)==null && document.getElementById('spnVia' + oldId)!=null)
                {
                    document.getElementById('spnVia' + oldId).id='spnVia' + i;
                    document.getElementById('viaText' + oldId).id='viaText' + i;
                    document.getElementById('viaText' + i).innerHTML='<img src="/images/map/via' + i + '.gif" />';
                    document.getElementById('via' + oldId).id='via' + i;
                    document.getElementById('up' + oldId).id='up' + i;
                    document.getElementById('down' + oldId).id='down' + i;
                    document.getElementById('remove' + oldId).id='remove' + i;
                }
	        }
	    }
	    return false;
	}
	
	function WebMapSearchCount(address)
	{
	    var resultsCount = 0;
////	    try
////	    {
////	        geocoder.getLatLng(address,null);
////    			
////			    // ====== Perform the Geocoding ======        
////			    var result=address;
////			    var searchStr=address;
////			    searchStr = searchStr.replace(/\%20/g, " ");

////		    searchStr = searchStr.replace(/\%DF/g, "ß");


////		    searchStr = searchStr.replace(/\%F6/g, "ö");
////		    searchStr = searchStr.replace(/\%D6/g, "Ö");

////		    searchStr = searchStr.replace(/\%E4/g, "ä");
////		    searchStr = searchStr.replace(/\%C4/g, "Ä");


////		    searchStr = searchStr.replace(/\%E6/g, "æ");
////		    searchStr = searchStr.replace(/\%C6/g, "Æ");
////		    searchStr = searchStr.replace(/\%F8/g, "ø");
////		    searchStr = searchStr.replace(/\%D8/g, "Ø");
////		    searchStr = searchStr.replace(/\%E5/g, "å");
////		    searchStr = searchStr.replace(/\%C5/g, "Å");
////            geocoder.getLocations(result, function (result)
////                                        { 
////                                            if (result.Status.code == G_GEO_SUCCESS)
////				                                    resultsCount = result.Placemark.length;
////		                                }
////		                         );
////		}
////		catch(e)
////		{
////		    resultsCount = 0;
////		}
		return (resultsCount==0?"":"(" + resultsCount + ")");
	}
	
	//--------  ---------//	
	
	function setAddressFromGoogleList(address, locale)
	{
	    RefreshWebMapSearch(address);
//	    document.getElementById("q").value=address;
//		setDirections(address, '', locale);
		return false;
	}
	
	function showAddress(address, locale)
	{
	    document.getElementById("tblRoute").style.display='';
	    document.getElementById("spnWebMapSearchCount").innerHTML = "(0)";
		if (geocoder)
		{
//        	geocoder.getLatLng(address,function(point)
//										{
//											/*
//											if (!point)
//											{
//												alert(address + " not found");
//											}
//											else
//											{
//												map.setCenter(point, 13);
//												var marker = new GMarker(point);
//												map.addOverlay(marker);
//												marker.openInfoWindowHtml('<span style="color:#3333CC; font-size:13px; font-weight:bold;">Address:</span><br/><br/>' + address);
//											}
//											*/
//										}
//								);
			
			// ====== Perform the Geocoding ======        
			var result=address;
			var searchStr=address;
			searchStr = searchStr.replace(/\%20/g, " ");

		searchStr = searchStr.replace(/\%DF/g, "ß");


		searchStr = searchStr.replace(/\%F6/g, "ö");
		searchStr = searchStr.replace(/\%D6/g, "Ö");

		searchStr = searchStr.replace(/\%E4/g, "ä");
		searchStr = searchStr.replace(/\%C4/g, "Ä");


		searchStr = searchStr.replace(/\%E6/g, "æ");
		searchStr = searchStr.replace(/\%C6/g, "Æ");
		searchStr = searchStr.replace(/\%F8/g, "ø");
		searchStr = searchStr.replace(/\%D8/g, "Ø");
		searchStr = searchStr.replace(/\%E5/g, "å");
		searchStr = searchStr.replace(/\%C5/g, "Å");
        geocoder.getLocations(result, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              	mHTML = ""; 
              	//mHTML = "<div style='left:0px;top:0px;'>";
              	document.getElementById("spnWebMapSearchCount").innerHTML = "(" + result.Placemark.length + ")";
              	mHTML = mHTML + '<table width="300" border="0" cellspacing="0" cellpadding="0">';
                mHTML = mHTML + '    <tr>';
                mHTML = mHTML + '      <td align="left" valign="top"><table width="300" border="0" cellspacing="0" cellpadding="0">';
                mHTML = mHTML + '        <tr>';
                mHTML = mHTML + '          <td align="left" valign="top" class="Light11 Black">Found ' + result.Placemark.length + ' listing on </td>';
                mHTML = mHTML + '        </tr>';
                mHTML = mHTML + '        <tr>';
                mHTML = mHTML + '          <td height="18" align="left" valign="top"><h1 class="Title1">' + address + '</h1></td>';
                mHTML = mHTML + '        </tr>';
                mHTML = mHTML + '      </table></td>';
                mHTML = mHTML + '    </tr>';
                mHTML = mHTML + '    <tr>';
                mHTML = mHTML + '      <td height="20" align="left" valign="middle"><table width="300" border="0" cellspacing="0" cellpadding="0">';

				for (var i=0; i<result.Placemark.length; i++) 
				{
					var p = result.Placemark[i].Point.coordinates;
                    var lat = p[1];
                    var lng = p[0];
				    var adresse = result.Placemark[i].address;
                    var id = "marker" + i;
                    CreatePlacemarker(i, lat, lng, 'Adresse', adresse, adresse, "");
                    mHTML = mHTML + '        <tr class="Pad6TL">';
                    mHTML = mHTML + '          <td width="13" align="left" valign="middle"><img src="/images/map/bullet1.jpg" width="5" height="5" /></td>';
                    mHTML = mHTML + '          <td width="287" align="left" valign="middle" class="link_12"><a id="'+ id +'" href="javascript:Info('+i+')" onmouseover="hover.over(this.id)" onmouseout="hover.out(this.id)">' + adresse + '</a></td>';
                    mHTML = mHTML + '        </tr>';
				}

                mHTML = mHTML + '      </table></td>';
                mHTML = mHTML + '    </tr>';
                mHTML = mHTML + '</table>';
//				mHTML = mHTML + '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
//              mHTML = mHTML + "<tr><td colspan='2' style='text-align:left; vertical-align:top; padding-left:15px; padding-top:5px; padding-bottom:5px;' class='Light11 Black'>Fant " + result.Placemark.length + " treff på&nbsp;<h1 class='Title1'>" + address + "</h1></td></tr>";
//				for (var i=0; i<result.Placemark.length; i++) 
//				{
//					var p = result.Placemark[i].Point.coordinates;
//                    var lat = p[1];
//                    var lng = p[0];
//				    var adresse = result.Placemark[i].address;
//                    var id = "marker" + i;
//                    CreatePlacemarker(i, lat, lng, 'Adresse', adresse, adresse, "");
//                    mHTML = mHTML + '<tr><td style="width:7%; text-align:center; vertical-align:top;">&bull;</td><td style="width:93%; text-align:left; vertical-align:top;" class="link_12"><a class="link_12" id="'+ id +'" href="javascript:Info('+i+')" onmouseover="hover.over(this.id)" onmouseout="hover.out(this.id)">' + adresse + '<\/a></td></tr>';
//                    mHTML = mHTML + "<tr><td style='height:5px;' colspan='2'></td></tr>";
//				}
//				mHTML = mHTML + "</table>";
				document.getElementById("directions").innerHTML = mHTML;
				
				if(result.Placemark.length==1)
				{
				    var p = result.Placemark[0].Point.coordinates;
                    map.setCenter(new GLatLng(p[1],p[0]),14);
				}
				    
              // centre the map on the first result
//              var p = result.Placemark[0].Point.coordinates;
//              map.setCenter(new GLatLng(p[1],p[0]),14);
            }
            // ====== Decode the error status ======
            else {
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Manglende adresse: Adresse parametere mangler eller har ingen verdi.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Ukjent adresse";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Utilgjengelig adresse:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Feil Nøkkel: kontakt support@nettkatalogen.no";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              if(document.getElementById("lblFirmRecords").innerHTML!="" && window.location.href.toLowerCase().indexOf('mapsearchfirm.aspx')==-1)
                window.location.href="/mapsearchfirm.aspx?to=" + address;
              else
                alert('Could not find "'+searchStr+ '" ' + reason);
              
            }
          }
        );

		}
	}    
    
    function CreatePlacemarkerUTMtoGEO(i, x, y, name, adresse, originaladdress, extraHtml)
    {
        try
        {
            var latlon = ConvertUTMToGEO(x, y, zone, southhemi);
            if (latlon!=null)
            {
                CreatePlacemarker(i, latlon[1], latlon[0], name, adresse, originaladdress, extraHtml);
            }
            else
            {
                geocoder.getLatLng(originaladdress, function(point)
			        {
			            if(point!=null)
			            {
			                map.setCenter(point, 14);
						    var marker = new GMarker(point);
						    map.addOverlay(marker);
						    //map.addOverlay(createMarker(point, name, extraHtml, adresse, i, originaladdress));
						    marker.openInfoWindowHtml('<span class="Light11" style="font-weight:bold;">' + name + ':</span><br/><br/>' + originaladdress);
                        }
			        }
		        );
            }
        }
        catch(e)
        {
        }        
    }
    
    function CreatePlacemarker(i, lat, lng, name, adresse, originaladdress, extraHtml)
    {
        var point = null;
        var id = "marker" + i;
        name = DecodeHTMLText(name);
        var html = "<p class='Light12 Black'><b>"+name+"</b></p><p class='Pad12T Light11 Black'>" + originaladdress + "</p>";
        html += "<p class='Pad12T link_10 Light10 Black'>";
        extraHtml = DecodeHTMLText(extraHtml);
        html += extraHtml;
        html += "<a href='/mapsearch.aspx?to=" + adresse + "&x=" + lat + "&y=" + lng + "'>Zoom hit</a>";
        html += "<br />";
        html += "Route <a href='/mapsearch.aspx?from=" + adresse + "'>Start Location</a> <a href='/mapsearch.aspx?to=" + adresse + "'>Stop Location</a>";
        html += "<\/p>";
        var category = "category" + i;
        if (lat==null)
        {
            geocoder.getLatLng(originaladdress, function(point)
				    {
				        if(point!=null)
                            map.addOverlay(createMarker(point, name, html, category, id, originaladdress));
				    }
			    );
        }
        else
        {
            point = new GLatLng(lat,lng);
            //alert(point);alert(name);alert(html);alert(category);alert(id);alert(originaladdress);
            map.addOverlay(createMarker(point, name, html, category, id, originaladdress));
        }        
    }
    
    function DecodeHTMLText(extraHtml)
    {
        while(extraHtml.indexOf('&amp;')>-1)
			extraHtml = extraHtml.replace('&amp;', '&');

        while(extraHtml.indexOf('%2F')>-1)
			extraHtml = extraHtml.replace('%2F', '/');

        while(extraHtml.indexOf('%3A')>-1)
			extraHtml = extraHtml.replace('%3A', ':');

        while(extraHtml.indexOf('&lt;')>-1)
			extraHtml = extraHtml.replace('&lt;', '<');

        while(extraHtml.indexOf('&gt;')>-1)
			extraHtml = extraHtml.replace('&gt;', '>');
			
		return extraHtml;
    }
 // Create the markers and set up the event window
 function createMarker(point, name, html, category, id, originaladdress) {
// alert(point);
  var marker = new GMarker(point);
   // Store category, name, id and icon as marker properties
   marker.category = category;
   marker.name = name;
   marker.id = id;
//   marker.icon = "/images/map/blue-dot.png";
   //marker.setImage("/images/map/blue-dot.png");
   GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
   });
  // Hovering over the markers
  GEvent.addListener(marker, "mouseover", function() {
//   marker.setImage("/images/map/white-dot.png");
   marker.openInfoWindowHtml(html);
//   var hovered = document.getElementById(id);
//   if(hovered) {
//    hovered.className = "Light10_Bold Blue";
//    actual = hovered; // Store this element
//   }
  });

  GEvent.addListener(marker, "mouseout", function() {
//    marker.setImage("/images/map/blue-dot.png");
//     if(actual) { actual.className= "Light10 Brown3"; }
  });

  gmarkers.push(marker);
  htmlAddresses.push(html);
  originalAddresses.push(originaladdress);
  return marker;
 }


    function CreatePlacemarkerSmallIcon(i, lat, lng, name, adresse, originaladdress, extraHtml)
    {
        var point = null;
        var id = "marker" + i;
        name = DecodeHTMLText(name);
        var html = "<p class='Light12 Black'><b>"+name+"</b></p><p class='Pad12T link_10 Light11 Black'>" + originaladdress + "<\/p>";
        html += "<p class='Pad12T link_10 Light10 Black'>";
        extraHtml = DecodeHTMLText(extraHtml);
        html += extraHtml;
        
        html += "<a href='/mapsearch.aspx?to=" + adresse + "&x=" + lat + "&y=" + lng + "'>Zoom hit</a>";
        html += "<br />";
        html += "Route <a href='/mapsearch.aspx?from=" + adresse + "'>Start Location</a> <a href='/mapsearch.aspx?to=" + adresse + "'>End Location</a>";
        html += "<\/p>";
        var category = "category" + i;
        if (lat==null)
        {
            geocoder.getLatLng(originaladdress, function(point)
				    {
				        if(point!=null)
                            map.addOverlay(createMarkerSmall(point, name, html, category, id, originaladdress));
				    }
			    );
        }
        else
        {
            point = new GLatLng(lat,lng);
            //alert(point);alert(name);alert(html);alert(category);alert(id);alert(originaladdress);
            map.addOverlay(createMarkerSmall(point, name, html, category, id, originaladdress));
        }        
    }

 // Create the markers and set up the event window
 function createMarkerSmall(point, name, html, category, id, originaladdress) 
 {
 
    var new_icon = new GIcon();
    new_icon.image = "/images/map/red.gif";
    new_icon.size = new GSize(16,16);
    new_icon.iconAnchor = new GPoint(8,9);
    new_icon.infoWindowAnchor = new GPoint(7,7);

    var opt = {};
    opt.icon = new_icon;
    opt.draggable = false; 
    opt.clickable = true;
    opt.dragCrossMove = true;

    var marker = new GMarker(point,opt);

    // Store category, name, id and icon as marker properties
    marker.category = category;
    marker.name = name;
    marker.id = id;
    //marker.icon = "/images/map/red.gif";
    //marker.setImage("/images/map/red.gif");
    GEvent.addListener(marker, "click", function() 
        {
            marker.openInfoWindowHtml(html);
        }
    );
    
    // Hovering over the markers
    GEvent.addListener(marker, "mouseover", function() {
    //marker.setImage("/images/map/red.gif");
    marker.openInfoWindowHtml(html);
    //var hovered = document.getElementById(id);
    //   if(hovered) {
    //    hovered.className = "Light10_Bold Blue";
    //    actual = hovered; // Store this element
    //   }
      });

    GEvent.addListener(marker, "mouseout", function() {
    //marker.setImage("/images/map/red.gif");
    //if(actual) { actual.className= "Light10 Brown3"; }
    });

    gmarkers.push(marker);
    htmlAddresses.push(html);
    originalAddresses.push(originaladdress);
    return marker;
}
    
var hover = { // Hovering over the links
 over: function(id) {
    // Set another background color for the link
    //  var hovered = document.getElementById(id);
    //  hovered.className = "Light10_Bold Blue";

    // Set another marker icon
    map.closeInfoWindow();
    
    for(var i =0; i < gmarkers.length; i++) {
    if(gmarkers[i].id == id)
    {
//        gmarkers[i].setImage("/images/map/white-dot.png");
        gmarkers[i].openInfoWindowHtml(htmlAddresses[i]);
        break;
    }
  }
 },

 out: function(id) {
  // Set the default link background
//  var hovered = document.getElementById(id);
//  hovered.className = "Light10 Brown3";

  // Set the default marker icon
//  for(var i =0; i < gmarkers.length; i++) {
//    if(gmarkers[i]!=null && gmarkers[i].id == id) 
//    {
//        gmarkers[i].setImage("/images/map/blue-dot.png");
//        break;
//    }
//  }
 }
}

 function Info(i) {
  //GEvent.trigger(gmarkers[i],"click");
  window.location.href ="/mapsearch.aspx?to=" + originalAddresses[i] ;
 }

    function showToAddress(address, locale, addMarker)
	{
		if (geocoder)
		{
			// ====== Perform the Geocoding ======        
			var result=address;
			var x = gup("x");
			var y = gup("y");
			var name = gup("line1");
			var titleurl = '';
			if (name=='')
			    name = '<span class="Light11 Black" style="font-weight:bold;">Adresse</span>';
			else
		    {
//		        var linkurl = gup("urlp");
//		        if (linkurl!='')
//		        {
//		            name = '<span class="link"><a href="' + linkurl + '" class="Light11 Blue" style="font-weight:bold;">' + name + '</a></span>';
//		        }
//		        else
		        name = '<span class="Light11 Black" style="font-weight:bold;">' + name + '</span>';
                titleurl = name + '<br/>';		        
		    }
            geocoder.getLatLng(result, function(point)
			        {
			        //alert(point);
			            if(point!=null)
			            {
			                map.setCenter(point, 14);
						    var marker = new GMarker(point);
						    map.addOverlay(marker);
						    marker.openInfoWindowHtml(name + ':<br/><br/><span class="Light11 Black">' + result + '</span>');
						    document.getElementById('trSingleAddress').style.display = '';
						    document.getElementById('divSingleAddress').innerHTML = titleurl + result;
                        }
                        else
                        {
                            if(x!='' && y!='' && x.indexOf(".")==-1 && y.indexOf(".")==-1)
                            {
                                CreatePlacemarkerUTMtoGEO(1, x, y, name, result, result, "");
                                var point1 = new GLatLng(x,y);
                                map.setCenter(point1, 14);
			                    var marker = new GMarker(point1);
			                    map.addOverlay(marker);
			                    marker.openInfoWindowHtml(name + ':<br/><br/><span class="Light11 Black">' + result + '</span>');
			                    document.getElementById('trSingleAddress').style.display = '';
						        document.getElementById('divSingleAddress').innerHTML = titleurl + result;
                            }
                            else if(x!='' && y!='' && x.indexOf(".")>-1 && y.indexOf(".")>-1)
                            {
                                CreatePlacemarker(1, x, y, name, address, address, "");
                                var point1 = new GLatLng(x,y);
                                map.setCenter(point1, 14);
			                    var marker = new GMarker(point1);
			                    map.addOverlay(marker);
			                    marker.openInfoWindowHtml(name + ':<br/><br/><span class="Light11 Black">' + result + '</span>');
			                    document.getElementById('trSingleAddress').style.display = '';
						        document.getElementById('divSingleAddress').innerHTML = titleurl + result;
                            }
                            else
                            {
                                var errormsg = "<span style='color:red'>Unfortunately, we can not find the address “" + result + "”. This may be due to the address you entered is incorrect or is brand new and has not been updated in our map</span>";
	                            if (document.getElementById('divSingleAddress')!=null)
	                            {
	                                document.getElementById('divSingleAddress').innerHTML = errormsg;
                                    document.getElementById('trSingleAddress').style.display = '';
                                    document.getElementById('tblRoute').style.display = 'none';
	                            }
	                            else
                                    document.getElementById("directions").innerHTML = errormsg;
                            }   
                        }
			        }
		        );
		}
	}
	
    function showFirmAddress(address, locale, addMarker)
	{
	    document.getElementById("spnWebMapSearchCount").innerHTML = "(0)";
		if (geocoder)
		{
			// ====== Perform the Geocoding ======        
			var result=address;
			var searchStr=address;
			searchStr = searchStr.replace(/\%20/g, " ");
		    searchStr = searchStr.replace(/\%DF/g, "ß");
		    searchStr = searchStr.replace(/\%F6/g, "ö");
		    searchStr = searchStr.replace(/\%D6/g, "Ö");
		    searchStr = searchStr.replace(/\%E4/g, "ä");
		    searchStr = searchStr.replace(/\%C4/g, "Ä");
		    searchStr = searchStr.replace(/\%E6/g, "æ");
		    searchStr = searchStr.replace(/\%C6/g, "Æ");
		    searchStr = searchStr.replace(/\%F8/g, "ø");
		    searchStr = searchStr.replace(/\%D8/g, "Ø");
		    searchStr = searchStr.replace(/\%E5/g, "å");
		    searchStr = searchStr.replace(/\%C5/g, "Å");
            geocoder.getLocations(result, function (result)
              { 
                // If that was successful
                if (result.Status.code == G_GEO_SUCCESS) {
				    document.getElementById("spnWebMapSearchCount").innerHTML = "(" + result.Placemark.length + ")";
    //                if (addMarker)
    //                {
    //                  var p = result.Placemark[0].Point.coordinates;
    //                  map.setCenter(new GLatLng(p[1],p[0]),14);
    //                }
                }
                // ====== Decode the error status ======
              }
            );

		}
	}
	

