// ==================================================================================================
//	StudioLine Google API Wrapper
//
//	Author: JS
//	Copyright 2008, H&M Systems Software, Inc.
// --------------------------------------------------------------------------------------------------
//	This JavaScript file is used as the common wrapper around the Google Maps API by
//	Geo.StudioLine.net, which is a web site free of charge.
//	The StudioLine software also uses this API wrapper on Geo.StudioLine.net to output Google
//	Maps in an HTML control of the software.
// --------------------------------------------------------------------------------------------------
//	08-APR-09 AS Changed pan control to new 3D version
// ==================================================================================================



// --------------------------------------------------------------------------------------------------
//	Global Constants
// --------------------------------------------------------------------------------------------------

var strMapDivName = "SLMap";

var map = null;
var CrossH = null;
var CrossV = null;
var width = 0;
var height = 0;
var mgr = null;
var geocoder = null;
var AllPoints = null;
var icons = {};
var allmarkers = [];
var hiliteMarkers = [];
var bNeedCrossHair = 0;
var CurrentMarker = null;
var focusMarkerOvl;
var pathPoints = [];
var ptlLastpathPt = 0;
var path = 0;
var currentView;
var ovMap = null;
var ClickedID = null;
var ProgramAskForClicks = 0;
var hilit = null;
var im_marker = 0;
var im_allow_dragging = 0;
var gLocalSearch;
var gSearchForm;
var results;
var lastPlace;
var bInBatchMode = false;

// insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement
// for Netscape 6/Mozilla by Thor Larholm me@jscript.dk
// Usage: include this code segment at the beginning of your document
// before any other Javascript contents.

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) 
                this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else 
			    this.parentNode.appendChild(parsedNode);
			break;
		}
	}

HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
	{
try{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
		}catch(e)
		{
		}
	}


HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}

function CrossHair(bHorz) {
    this.bHorz = bHorz;
}
CrossHair.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
CrossHair.prototype.initialize = function(map) {
    var container = document.createElement("div");
    container.style.top = 0;
    container.style.left = 0;
    container.style.width = "1px";
    container.style.height = "1px";
    container.style.border = "0px solid black";
    container.style.background = "transparent";
    container.style.zIndex = 0;
    container.style.position = 'fixed';
    //        container.style.filter = 'Shadow(color=#C0C0C0, offx=3, offy=3)'
    img = new Image;
    if (this.bHorz)
        img.src = 'CrossHairH.png';
    else
        img.src = 'CrossHairV.png';
    container.appendChild(img);
    //        map.getPane(3).appendChild(container);        

    map.getContainer().appendChild(container);
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
CrossHair.prototype.getDefaultPosition = function() {
    if (this.bHorz)
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(width / 2 - 40, height / 2 - 2));
    else
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(width / 2 - 3, height / 2 - 40));
}

function PosHilite(latlng, html, pic) {
    this.latlng = latlng;
    this.html = html;
    this.pic = pic;
    this.id = "";
}

PosHilite.prototype = new GControl();

PosHilite.prototype.initialize = function(map) {
    this.map_ = map;
    var c1 = this.map_.fromLatLngToDivPixel(this.latlng);
    var container = document.createElement("div");

    container.style.top = c1.y - 35 + "px";
    container.style.left = c1.x - 9 + "px";

    container.style.width = "20px";
    container.style.height = "40px";
    container.style.border = "0px solid black";
    //    container.style.background = "opaque";
    container.style.zIndex = 0;
    container.style.position = 'absolute';

    var HeaderHtml = '<span id=g1>' +
		'<b><a onClick="CloseInfo();"><img src="iconH.png"></a></span>';
	container.innerHTML = HeaderHtml;
/*	try{
		container.insertAdjacentHTML("AfterBegin", HeaderHtml);
	}catch(e)
	{
		;
	}
*/
    //        container.style.filter = 'Shadow(color=#C0C0C0, offx=3, offy=3)'
    /*    img = new Image;
    if (this.bHorz)
    img.src = 'CrossHairH.png';
    else
    img.src = 'CrossHairV.png';
    container.appendChild(img);
    */
    //        map.getPane(3).appendChild(container);
    draggable = true;
    map.getPane(G_MAP_FLOAT_PANE).appendChild(container);
    //    map.getContainer().appendChild();
    return container;
}


PosHilite.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
    map.removeOverlay(this.im_marker);
    delete this.im_marker;
    im_marker = null;
}



function ImageView(lat, lng, html, pic) {
    this.lat = lat;
    this.lng = lng;
    this.latlng = new GLatLng(lat, lng);
    this.html = html;
    this.pic = pic;
    this.id = "";
}

ImageView.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.


ImageView.prototype.DoSize = function() {
    if (this.img.width == 0) {
        setTimeout("ChkInfoSize()", 500);
        return;
    }
    if (this.img.complete == false) {
        setTimeout("ChkInfoSize()", 1500);
        delete this.img;
        this.img = new Image;
        this.img.src = this.pic;
        return;
    }

    if (typeof (nMapThumbSize) != "undefined")
    // The web application will set a thumbnail size
    {
        this.Scaling = nMapThumbSize / Math.max(this.img.height, this.img.width);
        this.img.width = Math.round(this.img.width * this.Scaling);
        this.img.height = Math.round(this.img.height * this.Scaling);
    }
    var Backround = "transparent";

    var c1 = this.map_.fromLatLngToDivPixel(this.latlng);
    var container = document.createElement("div");
    var containerbottom = document.createElement("div");
    this.containerTop.appendChild(containerbottom);
    container.style.zIndex = 32000;
    var Header = document.createElement("div");
    var CloseBtn = document.createElement("div");
    var HeaderHtml;
    var BtnHeight = 20;
    var Btntop = 0;
    if (im_allow_dragging) {
		HeaderHtml =   '<span id=g1><b><a onClick="CloseInfo();"><img src="CloseImageB.png" title="' + arrStrings["BtnCloseTitle"] + '"></a></b></span>';
        BtnHeight = 10;
        Btntop = 2;
    }
    else
        HeaderHtml = '<span id=g1>' +
		'<b><a onClick="CloseInfo();"><img src="CloseImage.png" title="' + arrStrings["BtnCloseTitle"] + '"></a></span>';
	var bInsertAdjAvail=true;
/*	try{
		CloseBtn.insertAdjacentHTML("AfterBegin", HeaderHtml);
		}catch(e)
		{
			bInsertAdjAvail = false;// Function not supported
		}
*/
	CloseBtn.innerHTML=HeaderHtml;
    Header.appendChild(CloseBtn);
    var CenterBtn = document.createElement("div");

    if (im_allow_dragging)
        HeaderHtml = '<span id=g1><b><a></a></span>';
    else

        HeaderHtml = HeaderHtml =   '<span id=g1><b><a onClick="CenterImage('+this.latlng.lat()+','+this.latlng.lng()+');"><img src="CenterImage.png" title="' + arrStrings["BtnCenterTitle"] + '"></a></span>';
    //        	'<b><a onClick="CenterImage(90,40);">[o]</a></span>';
    //    if (!im_allow_dragging)

	CenterBtn.innerHTML=HeaderHtml;
//	if(bInsertAdjAvail==true)
//		CenterBtn.insertAdjacentHTML("AfterBegin", HeaderHtml);

    Header.appendChild(CenterBtn);

    container.appendChild(Header);

    var ImageDiv = document.createElement("div");
    //		ImageDiv.appendChild(this.img);			// this changes img size from 90 to 9000 in IE8
    var ImageNode = document.createElement('img');
    with (ImageNode) {
        setAttribute('src', this.img.src);
        setAttribute('width', this.img.width);
        setAttribute('height', this.img.height);
    }
    ImageDiv.appendChild(ImageNode);
    container.appendChild(ImageDiv);

    var TextDiv = document.createElement("div");
    var TextDivA = document.createElement("div"); // Shadowed Text

    container.appendChild(TextDivA);
    container.appendChild(TextDiv);

    this.containerTop.appendChild(container);
    //      	container.appendChild(img);

    this.containerTop.style.top = c1.y + "px";
    this.containerTop.style.left = c1.x + "px";
    this.containerTop.style.width = this.img.width + 25 + "px";

    this.containerTop.style.height = this.img.height + 200 + "px";
    this.containerTop.style.border = "0px solid black";
    //		containerTop.setAttribute("background-Image",'Shadow1.png');
    this.containerTop.style.position = "absolute";
    this.containerTop.style.backgcolor = "black";
    this.containerTop.style.zIndex = 32000;
    this.containerTop.style.backgcolor = "black";

    containerbottom.style.top = 1 + "px";
    containerbottom.style.left = 1 + "px";
    containerbottom.style.width = this.img.width + 15 + "px";
    containerbottom.style.height = this.img.height + 200 + "px";
    containerbottom.style.border = "0px solid black";
    var newimage = "url(Shadow2.png)";
    //     containerbottom.style.backgroundImage = newimage;
    containerbottom.style.position = "absolute";
    containerbottom.style.backgcolor = "transparent";

    container.style.top = 0 + "px";
    container.style.left = 0 + "px";
    container.style.width = this.img.width + 20 + "px";
    container.style.height = this.img.height + 200 + "px";
    container.style.border = "0px solid black";
    //    container.style.background = "white";
    //    containerbottom.style.backgroundImage = newimage;
    container.style.position = "absolute";
    container.style.background = newimage;
    container.style.zIndex = 32000;

    //    container.style.background = "transparent";
    //    container.style.backgroundImage = newimage;


    Header.style.width = this.img.width + 20 + "px";
    Header.style.height = BtnHeight + 4 + "px";
    Header.style.border = "0px solid black";
    //    Header.style.background = "#CCCCCC";

    Header.style.background = "black";
    Header.style.position = "absolute";
    Header.style.textAlign = "right";

    CloseBtn.style.top = Btntop + "px";
    CloseBtn.style.left = this.img.width - 7 + (20 - BtnHeight) + "px";
    CloseBtn.style.width = BtnHeight + "px";
    CloseBtn.style.height = BtnHeight + "px";
    CloseBtn.style.border = "0px solid gray";
    CloseBtn.style.background = "transparent";

    CloseBtn.style.position = "absolute";
    CloseBtn.style.textAlign = "center";
    CloseBtn.style.font = "small Arial";
    CloseBtn.style.padding = "0px";
    CloseBtn.style.margin = "1px";
    CloseBtn.style.textAlign = "left";
    CloseBtn.style.fontSize = "16px";

    CenterBtn.style.top = 0 + "px";
    CenterBtn.style.left = 5 + "px";
    CenterBtn.style.width = 20 + "px";
    CenterBtn.style.height = BtnHeight + "px";

    CenterBtn.style.border = "0px solid gray";
    CenterBtn.style.background = "transparent";
    CenterBtn.style.position = "absolute";
    CenterBtn.style.textAlign = "center";
    CenterBtn.style.font = "small Arial";
    CenterBtn.style.padding = "0px";
    CenterBtn.style.margin = "1px";
    CenterBtn.style.textAlign = "left";
    CenterBtn.style.fontSize = "13px";
    CenterBtn.style.visible = false;

    ImageDiv.style.top = BtnHeight + 9 + "px";
    ImageDiv.style.left = 7 + "px";
    ImageDiv.style.width = this.img.width + "px";
    ImageDiv.style.height = this.img.height + "px";
    ImageDiv.style.border = "3px solid white";
    ImageDiv.style.background = "transparent";
    ImageDiv.style.position = "absolute";


    TextDivA.style.top = 34 + this.img.height + "px";
    TextDivA.style.left = 6 + "px";
    TextDivA.style.width = this.img.width + 5 + "px";
    TextDivA.style.height = 100 + "px";
    TextDivA.style.border = "0px solid black";
    TextDivA.style.background = Backround;
    TextDivA.style.position = "absolute";
    TextDivA.style.font = "small Aria";
    //    TextDivA.style.font = "Verdana";
    TextDivA.style.padding = "0px";
    TextDivA.style.margin = "1px";
    TextDivA.style.textAlign = "left";
    TextDivA.style.fontSize = "11px";
    TextDivA.style.color = "gray";
    var Html = '<p>' +
			this.html + '</p>';
    //    TextDivA.insertAdjacentHTML("AfterBegin", Html);
    TextDiv.style.top = 33 + this.img.height + "px";
    TextDiv.style.left = 5 + "px";
    TextDiv.style.width = this.img.width + 5 + "px";
    TextDiv.style.height = 100 + "px";
    TextDiv.style.border = "0px solid black";
    TextDiv.style.background = Backround;
    TextDiv.style.position = "absolute";
    //    TextDivA.style.font = "Verdana";
    TextDiv.style.font = "small Arial";
    TextDiv.style.padding = "0px";
    TextDiv.style.margin = "1px";
    TextDiv.style.textAlign = "left";
    TextDiv.style.fontSize = "11px";
    TextDiv.style.color = "white";
    var Html = '<p>' +
			this.html + '</p>';
	TextDiv.innerHTML=Html;
//	if(bInsertAdjAvail==true)
//		TextDiv.insertAdjacentHTML("AfterBegin", Html);


    container.style.height = this.img.height + 45 + TextDiv.scrollHeight + "px";
    this.containerTop.style.height = this.img.height + 35 + TextDiv.scrollHeight + "px";
    containerbottom.style.height = this.img.height + 45 + TextDiv.scrollHeight + "px";
    TextDiv.style.height = TextDiv.scrollHeight + "px";

}


ImageView.prototype.initialize = function(map) {
    var c1 = map.fromLatLngToDivPixel(this.latlng);

    this.img = new Image;
    this.img.src = this.pic;
    this.map_ = map;

    this.containerTop = document.createElement("div");
    map.getPane(G_MAP_FLOAT_PANE).appendChild(this.containerTop);
    //     if(TextDiv.scrollHeight > 100)
    setTimeout("ChkInfoSize()", 500);
    //        ImageView.DoSize();
    //		map.getContainer().appendChild(container);

    this.div_ = this.containerTop;
    this.hilit = new PosHilite(this.latlng, this.img.src, this.pic);
    //    map.addControl(this.hilit);

    var CursorIcon = new google.maps.Icon(google.maps.DEFAULT_ICON, "IconH.png");

    CursorIcon.dragCrossSize = new google.maps.Size(26, 32);
    CursorIcon.dragCrossAnchor = new google.maps.Point(13, 16);
    CursorIcon.shadow = 'Icon_Shadow.png'
    CursorIcon.shadowSize = new GSize(44, 32);
    CursorIcon.iconSize = new GSize(26, 32);
    if (im_allow_dragging) {
        im_marker = new google.maps.Marker(
			    this.latlng,
			    { icon: CursorIcon, draggable: true, zIndexProcess: GetStaticZIndex(32500) });
        im_marker.InfoWnd = this;

        GEvent.addListener(im_marker, "dragstart", function() {
            this.InfoWnd.div_.style.top = -10000 + "px";
            this.InfoWnd.div_.style.left = -10000 + "px";

        });

        GEvent.addListener(im_marker, "dragend", function() {
            this.InfoWnd.latlng = im_marker.getPoint();
            var c1 = this.InfoWnd.map_.fromLatLngToDivPixel(im_marker.getPoint());
            this.InfoWnd.div_.style.top = c1.y + "px";
            this.InfoWnd.div_.style.left = c1.x + "px";
            allmarkers[this.InfoWnd.id].setLatLng(im_marker.getPoint());
            ClickedID = this.InfoWnd.id;
            QueryAddress(im_marker.getPoint().lat(), im_marker.getPoint().lng());
            if (!bInBatchMode)
                mgr.refresh();

        });
    }
    else {
        im_marker = new google.maps.Marker(
			    this.latlng,
			    { icon: CursorIcon, draggable: false, zIndexProcess: GetStaticZIndex(32500) });

    }

    this.map_.addOverlay(im_marker);

    return this.containerTop;
}
// Copy our data to a new Rectangle
ImageView.prototype.copy = function() {
    return new ImageView(this.lat, this.lng, this.html,
						   this.pic);
}

ImageView.prototype.remove = function() {
    //    this.div_.parentNode.removeChild(this.div_);
    map.removeControl(this);
    map.removeControl(this.hilit);
    map.removeOverlay(im_marker);
    delete im_marker;
}

ImageView.prototype.click = function() {
    alert("Click");
}

ImageView.prototype.redraw = function(force) {
    // We only need to redraw if the coordinate system has changed
    //	if (!force) 
    //        return;

    // Calculate the DIV coordinates of two opposite corners of our bounds to
    // get the size and position of our rectangle
    var c1 = this.map_.fromLatLngToDivPixel(this.latlng);

    // Now position our DIV based on the DIV coordinates of our bounds
    this.div_.style.width = '200px';
    this.div_.style.height = '200px';
    this.div_.style.left = c1.x;
    this.div_.style.top = c1.y;
}

function ChkInfoSize() {
    currentView.DoSize();
}


function ResizeView(vElement) {
    //Find Browser Window Size

    var loc;
    try {
        if (map)
            loc = map.getCenter();

        var myWidth = 0, myHeight = 0;

        if (vElement != undefined && vElement != null) {
            // caller wants control size with DIV properties
            myWidth = vElement.clientWidth;
            myHeight = vElement.clientHeight;
        }
        else if (typeof (window.innerWidth) == 'number') {
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        }

        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }

        else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        var bSizeChanged = false;
        if (width != myWidth)
            bSizeChanged = true;
        if (height != myHeight)
            bSizeChanged = true;
        if (bSizeChanged)
            if (ovMap != null)
            ovMap.hide();

        width = myWidth;
        height = myHeight;

        if (bNeedCrossHair && CrossH == null)
            bSizeChanged = true;
        var el = document.getElementById(strMapDivName);
        if (el != null) {
            el.style.top = 0;
            el.style.left = 0;
            el.style.width = width;
            el.style.height = height;
        }
        if (bSizeChanged) {
            if (CrossH) {
                map.removeControl(CrossH);
                map.removeControl(CrossV);
                delete CrossH;
                delete CrossV;
            }
            if (bNeedCrossHair) {
                CrossH = new CrossHair(1);
                map.addControl(CrossH);
                CrossV = new CrossHair(0);
                map.addControl(CrossV);
            }
            if (map)
                map.checkResize();


            if (ovMap != null)
                ovMap.show();
            if (loc)
                map.setCenter(loc);

mapControlOverviewMapControl.hide();
mapControlOverviewMapControl.show();

        }

        if (im_marker) {
            if (map) {
                var c1 = map.fromLatLngToDivPixel(im_marker.getPoint());
                if (im_marker.InfoWnd) {
                    im_marker.InfoWnd.div_.style.top = c1.y + "px";
                    im_marker.InfoWnd.div_.style.left = c1.x + "px";
                }
            }
        }
    } catch (e) {
    }    
}

function MapResized() {
    ResizeView(document.getElementById(strMapDivName));
}

function GetLastMidLatitude() {
    try {
        var loc = map.getCenter();
        return loc.lat();
    }
    catch (err) {
        return -999.2;
    }
}

function GetLastMidLongitude() {
    try {
        var loc = map.getCenter();
        return loc.lng();
    } catch (err) {
        return -999.2;
    }
}

function GetLastActiveLat(id) {
    try {
        if (allmarkers[id] == null)
            return -999.2;
        return allmarkers[id].getLatLng().lat();
    }
    catch (err) {
        return -999.2;
    }
}

function GetLastActiveLng(id) {
    try {
        if (allmarkers[id] == null)
            return -999.2;
        return allmarkers[id].getLatLng().lng();
    } catch (err) {
        return -999.2;
    }
}

function GetLastActiveID() {
    try {
        if (im_marker == null)
            return -999;
        return im_marker.id;
    }
    catch (err) {
        return -999;
    }
}


function AddImage(id, lat, lng, imgUrl, ImgText) {

	lat= CheckLat(lat);
	lng= CheckLng(lng);

    var LatLng = new GLatLng(lat, lng);

    var marker = new GMarker(LatLng, new GIcon(G_DEFAULT_ICON, 'iconN.png'));
    marker.html = '<div style="width: 240px; background-color: white; text-align:center; color: black">' +
			'<p><img src="' + imgUrl + '" alt="" /></p></div>' +
			'<br><div style="width: 240px; background-color: white; color: black">' +
			ImgText + '</div>';

    marker.id = id;
    marker.lat = lat;
    marker.lng = lng;
    marker.imgUrl = imgUrl;
    marker.imgText = ImgText;

    GEvent.addListener(marker, 'click', function() {
        // currentMarker = marker;
        ShowInfo(marker.id, marker.getLatLng().lat(), marker.getLatLng().lng(), marker.imgUrl, marker.imgText);
	try { handleItemSelect( marker.id ) } catch(e){};
        // marker.openInfoWindowHtml(marker.html);
    }
		);
    var icn = marker.getIcon();
    icn.image = 'iconN.png';
    icn.shadow = 'Icon_Shadow.png';
    icn.shadowSize = new GSize(44, 32);
    icn.iconSize = new GSize(26, 32);
    mgr.addMarker(marker, 0);

    allmarkers[id] = marker;

    AllPoints.extend(LatLng);
    if(!bInBatchMode)
        mgr.refresh();
    return marker;
}

function AddPathPoint(lat, lng) {
	lat= CheckLat(lat);
	lng= CheckLng(lng);

    var latlng = new GLatLng(lat, lng);
    pathPoints[ptlLastpathPt] = latlng;
    AllPoints.extend(latlng);

    ptlLastpathPt++;
}
function ShowPath() {
    path = new GPolyline(pathPoints);
    map.addOverlay(path);
}

function AddLine(Lat, Long, Lat1, Long1) {

	Lat= CheckLat(Lat);
	Long= CheckLng(Long);
	Lat1= CheckLat(Lat);
	Long1= CheckLng(Long);

    var latlngs = [];
    latlngs[0] = new GLatLng(Lat, Long);
    latlngs[1] = new GLatLng(Lat1, Long1);

    var line = new GPolyline(latlngs);
    map.addOverlay(line);
}

function AddImageQuiet(id, lat, lng, imgUrl, ImgText) {

	lat= CheckLat(lat);
	lng= CheckLng(lng);

    var LatLng = new GLatLng(lat, lng);

    var marker = new GMarker(LatLng, new GIcon(G_DEFAULT_ICON, 'iconN.png'));
    marker.html = '<div style="width: 240px; background-color: white; text-align:center; color: black">' +
			'<p><img src="' + imgUrl + '" alt="" /></p></div>' +
			'<br><div style="width: 240px; background-color: white; color: black">' +
			ImgText + '</div>';
    marker.id = id;
    marker.lat = lat;
    marker.lng = lng;
    marker.imgUrl = imgUrl;
    marker.imgText = ImgText;

    GEvent.addListener(marker, 'click', function() {
        //			    currentMarker = marker;
        ShowInfo(marker.id, marker.getLatLng().lat(), marker.getLatLng().lng(), marker.imgUrl, marker.imgText);
        ClickedID = marker.id;
        //			marker.openInfoWindowHtml(marker.html);
    }
		);
    var icn = marker.getIcon();
    icn.image = 'iconN.png';
    icn.shadow = 'Icon_Shadow.png';
    icn.shadowSize = new GSize(44, 32);
    icn.iconSize = new GSize(26, 32);
    mgr.addMarker(marker, 0);

    allmarkers[id] = marker;

    AllPoints.extend(LatLng);
}

function RemoveImage(id) {
    mgr.removeMarker(allmarkers[id]);
    allmarkers[id] = null;
    if (!bInBatchMode)
        mgr.refresh();
}

function UpdateMarkers() {
    if(!bInBatchMode)
        mgr.refresh();
}

function GetClickedMarker() {
    ProgramAskForClicks = 1;
    return ClickedID;
}
function RemoveInfo() {
    if (currentView) {
        map.removeControl(currentView);
        currentView.remove();
        delete currentView;
        currentView = null;
    }
}
function EnsureVisible(id) {
    try {

        var marker = allmarkers[id];
        if (marker != null) {
            var bounds = map.getBounds();
            if (!bounds.containsLatLng(marker.getLatLng())) {
                if (map)
                    map.setCenter(marker.getLatLng());
            }

        }
    }
    catch (err) {
        ;
    }
}

function NavigateTo(id, lan, lon) {
	if(lan>360)
		lan=0;
	if(lon>360)
		lon=0;

    EnsureVisible(id);
}

function HiLiteImage(id, lat, lng, imgUrl, ImgText) {

	lat= CheckLat(lat);
	lng= CheckLng(lng);

    var marker = new GMarker(new GLatLng(lat - 0.001, lng - 0.001), new GIcon(G_DEFAULT_ICON, 'iconH.png'));
    marker.id = id;
    marker.lat = lat;
    marker.lng = lng;
    marker.imgUrl = imgUrl;
    marker.imgText = ImgText;
    GEvent.addListener(marker, 'click', function() {
        ShowInfo(marker.id, marker.getLatLng().lat(), marker.getLatLng().lng(), marker.imgUrl, marker.imgText);
        ClickedID = marker.id;
    });

    map.addOverlay(marker);
    hiliteMarkers[id] = marker;


    if (allmarkers[id] == null) {
        AddImage(id, lat, lng, imgUrl, ImgText);
    }
    allmarkers[id].setLatLng(new GLatLng(lat, lng));
    allmarkers[id].imgText = ImgText;
    EnsureVisible(id);
    hilit = new PosHilite(lat, lng, imgUrl, ImgText);
}


function UnHiLiteImage(id, lat, lng, imgUrl, ImgText) {

    if (allmarkers[id] != null) {
        var marker = allmarkers[id];
		marker.imgUrl = imgUrl;
		marker.imgText = ImgText;
        marker.lat = lat;
        marker.lng = lng;
        marker.setLatLng(new GLatLng(lat, lng));
	}
	else
	    AddImageQuiet(id, lat, lng, imgUrl, ImgText);
	
/* 
    if (hiliteMarkers[id] != null) {
        map.removeOverlay(hiliteMarkers[id]);
        delete hiliteMarkers[id];
        hiliteMarkers[id] = null;
    }

	lat= CheckLat(lat);
	lng= CheckLng(lng);

   if (allmarkers[id] == null) {
        AddImage(id, lat, lng, imgUrl, ImgText);

    }
    allmarkers[id].setLatLng(new GLatLng(lat, lng));
    RemoveInfo();
    delete hilit;
*/
}
function SetMarkerText(id, text) {
    try {
        var marker = allmarkers[id];
        if (marker != null) {
            marker.imgText = text;
        }
    } catch (e) {

    }
}

function CloseInfo() {
    if (currentView) {
        map.removeControl(currentView);
        currentView.remove();
        delete currentView;
        currentView = null;
    }

}

function LngFromPixel(x1, y1) {
    var x = parseInt(x1);
    var y = parseInt(y1);
    var Pt = new GPoint(x, y);
    var value = map.fromContainerPixelToLatLng(Pt);

    return CheckLng(value.lng());
}

function LatFromPixel(x1, y1) {
    var x = parseInt(x1);
    var y = parseInt(y1);
    var Pt = new GPoint(x,y);
    var value = map.fromContainerPixelToLatLng(Pt);
    return CheckLat(value.lat());
}

function ShowInfo(id, Lat, Long, imgUrl, ImgText) {
    var bNew = 1;
    if (currentView) {
        if (currentView.id != id) {
            map.removeControl(currentView);
            currentView.remove();
            delete currentView;

        }
        else
            bNew = 0;
    }
    if (bNew == 1) {
        SetMarkerText(id,ImgText);
        currentView = new ImageView(CheckLat(Lat), CheckLng(Long), ImgText, imgUrl);
        currentView.id = id;
        map.addControl(currentView);
    }
}

function ShowMarkerInfo(id) {
    var bNew = 1;
    if (currentView) {
        if (currentView.id != id) {
            map.removeControl(currentView);
            currentView.remove();
            delete currentView;

        }
        else
            bNew = 0;
    }
    if (bNew == 1) {
       try{
            var marker = allmarkers[id];
            if(marker != null)
            {
                currentView = new ImageView(marker.getLatLng().lat(), marker.getLatLng().lng(), marker.imgText, marker.imgUrl)
                currentView.id = marker.id;
                map.addControl(currentView);
            }
            }catch(e)
            {
            
            }
    
    }
}

function ResetAll(width, height) {
    if (map != null) {
        mgr.clearMarkers();
        delete AllPoints;
        AllPoints = new GLatLngBounds();
        allmarkers = [];

    }
}

function ResetMarker() {
    if (map != null) {
        mgr.clearMarkers();
        allmarkers = [];

    }
}

function ResetPath(width, height) {
    map.removeOverlay(path);
    delete path;
    path = 0;
    ptlLastpathPt = 0;
    pathPoints = [];

}

function GetPathLenth() {
    if (path != null) {
        var value = path.getLength();
        return value;

    }
}
function CenterImage(lat, lng) {
	if(map)
		map.setCenter(new GLatLng(CheckLat(lat), CheckLng(lng)), map.getZoom());
}
function DoBestMap(vZoomOut) {
    var center = AllPoints.getCenter();

    var oSize = AllPoints.toSpan();
    if (oSize.lat() == 0 && oSize.lng() == 0 && vZoomOut != undefined)
    // we have a single point, override with explicit Zoom Level
        var newZoom = map.getBoundsZoomLevel(AllPoints) - vZoomOut
    else
    // use default zoom level
        var newZoom = map.getBoundsZoomLevel(AllPoints) - 1;

    if (map.getZoom() != newZoom) {
        map.setCenter(center, newZoom);
    } else {
        map.panTo(center);
    }

}

function ShowRect(Lat1,Lng1,Lat2,Lng2,offs) {

    var Points = null;
    Points = new GLatLngBounds();
    Points.extend(new GLatLng(parseFloat(Lat1), parseFloat(Lng1)));
    Points.extend(new GLatLng(parseFloat(Lat2),parseFloat(Lng2)));
    var center = Points.getCenter();

    var oSize = Points.toSpan();
    var newZoom = map.getBoundsZoomLevel(Points);
//	newZoom += parseInt(offs);

    if (map.getZoom() != newZoom) {
        map.setCenter(center, newZoom);
    } else {
        map.panTo(center);
    }

}


function RemoveCrossHair() {
    if (CrossH) {
        map.removeControl(CrossH);
        delete CrossH;
        map.removeControl(CrossV);
        delete CrossV;
        CrossH = CrossV = null;
    }
}

function AddCrosshairControl(vNeedCrossHair) {
    bNeedCrossHair = (vNeedCrossHair == undefined || vNeedCrossHair == true ? true : false);
    if (CrossH) {
        map.removeControl(CrossH);
        delete CrossH;
        map.removeControl(CrossV);
        delete CrossV;
    }
    if (bNeedCrossHair) {
        CrossH = new CrossHair(0);
        map.addControl(CrossH);
        CrossV = new CrossHair(1);
        map.addControl(CrossV);
    }
}
function RefreshCrosshairControl() {
    ResizeView();
}

function addToMap(response) {
    // Retrieve the object
    place = response.Placemark[0];

    // Retrieve the latitude and longitude
    point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);

    // Center the map on this point
    map.setCenter(point, 13);

    // Create a marker
    marker = new GMarker(point);

    // Add the marker to map
    map.addOverlay(marker);

    // Add address information to marker
    var streetAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
    var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
    var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
    var zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;

    // Add address information to marker
    marker.openInfoWindowHtml(place.address + '<br />' +
            streetAddress + '<br />' +
            city + ', ' + state + ' ' + zip);
    
}

function FindLocation(what, where) {

    results.style.width = "300px";
    results.style.height = "0px";
    results.style.top = "-2px";
    results.style.left = "105px";

    gLocalSearch.searchForm.input.value = where;
    gLocalSearch.execute();
 /*   
    geocoder.getLocations(where, addToMap);
*/    
    geocoder.getLatLng(
		  where,
		  function(point) {
		      if (point) {
		          map.setCenter(point, 13);
		      }
		  }
		);
		
}

function WriteToDocument(text) {
    document.write(text);
}


function GetStaticZIndex(n_ZIndex) {
    return function() { return n_ZIndex; };
}

function EnableMarkerDrag() {
    im_allow_dragging = true;
}

function CheckLat(latIn) {
    var lat = parseFloat(latIn);
	if(lat >90.0)
		return 0.0;
	if(lat < -90.0)
		return 0.0;
	return lat;

}

function CheckLng(lngIn)
{
    var lng = parseFloat(lngIn);
    if (lng > 180.0)
		return 0.0;
	if(lng < -180.0)
		return 0.0;
	return lng;

}

function QueryAddress(lat, lng) {
    lastPlace = null;
    lat = CheckLat(lat);
    lng = CheckLng(lng);

    var latlng = new GLatLng(lat, lng);
    
    if (latlng != null) {
        geocoder.getLocations(latlng, SaveAddress);
    }
}

function GetLastAdressInfo(Field) {
    if (!lastPlace)
        return "";
       try{
    switch (Field) {
        case "Country":
            return (lastPlace.AddressDetails.Country.CountryName);
            break;
        case "City":
            return (lastPlace.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
            break;
        case "State":
            return (lastPlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
            break;
        case "Street":
            return (lastPlace.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName);
            break;
    }
    }catch(e)
    {
        return "";
    }
}

function GetLastCity() {
    return lastPlace.city;
}

function SaveAddress(response) {

    if (!response || response.Status.code != 200) {
//         alert("Status Code:" + response.Status.code);
		;
    } else {
        lastPlace = response.Placemark[0];
    }
}


function ShowSearchControl(){

    // Create a separate div for the results
    results = document.createElement('div');
    results.style.top = "-1px";
    results.style.left = "140px";
    results.style.width = "0px";
    results.style.height = "0px";
    results.style.position = 'fixed';
    results.style.backgcolor = "transparent";
    results.style.border = "0px solid black";
    results.style.position = "absolute";
    results.style.zIndex = 32000;
    
//    document.body.appendChild(results);

    var aOptions = new Object();
    aOptions.resultList = results;
    aOptions.listingTypes = "blended";
    gLocalSearch = new google.maps.LocalSearch(aOptions)
    map.addControl(gLocalSearch, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(-1, -30)));
    map.getContainer().appendChild(results);
}
function WorkBatched() {
    bInBatchMode = true;
}
function BatchedWorkDone() {
    bInBatchMode = false;
    mgr.refresh();

}

var mapControlMapTypeControl;
var mapControlLargeMapControl;
var mapControlScaleControl;
var mapControlOverviewMapControl;

function ShowStdControls() {
    map.addControl(mapControlMapTypeControl);
    map.addControl(mapControlLargeMapControl);
    map.addControl(mapControlScaleControl);
    map.addControl(mapControlOverviewMapControl);

}

function HideStdControls() {
    map.removeControl(mapControlMapTypeControl);
    map.removeControl(mapControlLargeMapControl);
    map.removeControl(mapControlScaleControl);
    map.removeControl(mapControlOverviewMapControl);

}

function initialize(vElement, vZoomLevel) {
    if (GBrowserIsCompatible()) {
        var nZoomLevel = (vZoomLevel == undefined ? 0 : vZoomLevel)

        map = new GMap2(document.getElementById(strMapDivName));

        ResizeView(vElement);

        map.setCenter(new GLatLng(0, 0), vZoomLevel);
        mgr = new MarkerManager(map);
        map.enableScrollWheelZoom();

        //		map.addControl( new GMapTypeControl() );	
        map.addMapType(G_PHYSICAL_MAP);
        mapControlMapTypeControl = new GHierarchicalMapTypeControl(); // Set up map type menu relationships
        mapControlMapTypeControl.clearRelationships();
        mapControlMapTypeControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, arrStrings["LblSatelliteLabels"], true);
        mapControlLargeMapControl = new GLargeMapControl3D();
        mapControlScaleControl = new GScaleControl();
        mapControlOverviewMapControl = new GOverviewMapControl();

        ShowStdControls();

        var mini = mapControlOverviewMapControl.getOverviewMap();

        AllPoints = new GLatLngBounds();

        geocoder = new GClientGeocoder();
        return map;
    }

}
