﻿var MO_Icons = new Object();
MO_Icons[1] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_1.gif";
MO_Icons[2] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_2.gif";
MO_Icons[3] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_3.gif";
MO_Icons[4] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_4.gif";
MO_Icons[5] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_5.gif";
MO_Icons[6] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_6.gif";
MO_Icons[7] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_7.gif";
MO_Icons[8] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_8.gif";
MO_Icons[9] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_9.gif";
MO_Icons[10] = "http://cachefly.apartmentsapart.com/aa/img_modules/im/cat_10.gif";

var MO_ZoneColors = new Object();
MO_ZoneColors[1] = ["#F37141", "#F04608"];
MO_ZoneColors[2] = ["#6DB7FE", "#41A1FE"];
MO_ZoneColors[3] = ["#D24955", "#C41222"];
MO_ZoneColors[4] = ["#9683E1", "#765ED8"];
MO_ZoneColors[5] = ["#6A4861", "#3D1132"];
MO_ZoneColors[6] = ["#3B62B1", "#003399"];
MO_ZoneColors[7] = ["#B13BB1", "#990099"];
MO_ZoneColors[8] = ["#6CD77E", "#40CA56"];
MO_ZoneColors[9] = ["#3199C0", "#007EAC"];
MO_ZoneColors[10] = ["#0CDBD8", "#0CDBD8"];

var MapEngine = null; // do not change name of this variable!!!
var ModeFromCookie = false;
var noLatLngAlert = false;
var hideAptMap = false;
var hideCityMap = 0;
var listWith1AptAndNoFilter = false;

var im_ApartmentsOnMapTop3 = null;
var im_ApartmentsOnMap = null;
function im_Start() {
    if (typeof (apartmentsapart) == "undefined") {
        return;
    }
    if (VersionIM == 4 || VersionIM == 5) {
        Type = 'static';
        if (VersionIM == 4) {
            im_ApartmentsOnMapTop3 = apartmentsapart.Modules.AjaxApartmentList.GetFilteredApartmentsForMap(listID).value;
            if (im_ApartmentsOnMapTop3 == null) {
                return;
            }
        }
        apartmentsapart.Modules.InteractiveMap.GetAllApartmentsForMap(im_ListID, im_StartCallback);
    }
    else {
        im_StartCallback(null);
    }
}
function im_StartCallback(res) {
    if (res != null) {
        im_ApartmentsOnMap = res.value;
    }
    if (im_ApartmentsOnMap != null) {
        try {
            if (Type == 'static') { // Type-> variable from AjaxApartmentList/Search
                im_Snippet = im_Snippet_static;
            }
            if (VersionIM == 1) {
                MapEngine = new InterActiveMap('im_map', 930, 550);
            }
            else if (VersionIM == 4) {
                MapEngine = new InterActiveMap('im_map', 715, 550); 
            }

            if (Type == 'static') {
                MapEngine.CreateListButton('#im_but>td');
            }
            else if (Type == 'search') {
                MapEngine.CreateListButton('#im_but');
            }

            var mapSettings = readCookie('im_info');
            if (!MapEngine.IsCityHasOtherMarkers()) {
                ListViewMode = 0;
                mapSettings = 0;
            }
            if (VersionIM == 1) {
                try {
                    if (mapSettings) {
                        var mpM = parseInt(mapSettings);
                        if (mpM > 1) mpM = 1;
                        apartmentsapart.Modules.SearchFilter.SaveListViewModeInSession(JSMAN_VisitID, mpM, -2, mpM);
                        ModeFromCookie = true;
                    }
                    else {
                        createCookie('im_info', ListViewMode);
                        mapSettings = ListViewMode.toString();
                        apartmentsapart.Modules.SearchFilter.SaveListViewModeInSession(JSMAN_VisitID, ListViewMode, -2, -2);
                    }
                } catch (errmap) { }
                if (mapSettings && mapSettings != "0") {
                    MapEngine.ShowMap();
                    window.location.href = '#map';
                }
                else
                    window.location.href = '#list';
            }
            ModeFromCookie = false;
            if (Type != 'static') {
                MapEngine.CreateNewSearchButton();

            }

        } catch (erMap) { }
    }
    if (VersionIM != 4 && VersionIM != 5) {
        try {
            document.getElementById('PW').style.display = 'none';
        } catch (e1) { }
        try {
            document.getElementById('footer').style.visibility = 'visible';
        } catch (e2) { }
        try {
            document.getElementById('Table1').style.visibility = 'visible';
        } catch (e3) { }
    }
}
function im_StartShowOnly() {
    if (Type == 'aptdetails') {
        MapEngine.ShowMap(null, AptID);
    }
    else if (Type == 'maplanding' || Type == 'landmarklanding') {
        if (AptID == 0) {
            MapEngine.ShowMap();
        }
        else {
            MapEngine.ShowMap(null, AptID);
        }
        if (showGuideMap == '1') {
            document.getElementById('GuideMap').innerHTML = apartmentsapart.Modules.InteractiveMap.GenerateGuideMap(im_ListID).value;
            // jQuery('#GuideMap').append(apartmentsapart.Modules.InteractiveMap.GenerateLegend().value);
        }
        if (mapleft != '') {
            document.getElementById('im_mapm').style.marginLeft = mapleft + 'px';
        }
        if (maptop != '') {
            document.getElementById('im_mapm').style.marginTop = maptop + 'px';
        }
    }
    if (VersionIM == 5 && hideAptMap == true) {
        document.getElementById('im_mapm').style.display = 'none';
    }    
    
    try {
        document.getElementById('im_maph').style.display = 'none';
    } catch (e1) { }   
    try {
        document.getElementById('PW').style.display = 'none';
    } catch (e1) { }
    try {
        document.getElementById('footer').style.visibility = 'visible';
    } catch (e2) { }
    try {
        document.getElementById('Table1').style.visibility = 'visible';
    } catch (e3) { }
}
function im_Start2() {
    try {
        document.getElementById('im_maph').style.display = 'none';
        im_ApartmentsOnMap = apartmentsapart.Modules.InteractiveMap.GetAllApartmentsForMap(im_ListID).value;
        if (VersionIM == 5 && im_ApartmentsOnMap == null) {
            document.getElementById('im_maph').style.display = 'none';
        }    
        else if (Type == 'aptdetails') { // Type-> variable from AjaxApartmentList/Search/InterActiveMap
            im_Snippet = im_Snippet_aptdetails;
            MapEngine = new InterActiveMap('im_map', 288, 260); 
        }
        else if (Type == 'maplanding') {
            im_Snippet = im_Snippet_static;
            if (mapwidth != '' && mapheight != '') {
                MapEngine = new InterActiveMap('im_map', mapwidth, mapheight);
            }
            else {
                if (VersionIM == 5) {
                    MapEngine = new InterActiveMap('im_map', 700, 470);
                } else {
                    MapEngine = new InterActiveMap('im_map', 715, 500);
                }
            }
        }
        else if (Type == 'landmarklanding') {
            im_Snippet = im_Snippet_static; 
            MapEngine = new InterActiveMap('im_map', mapwidth, mapheight); //iframe 275 336
        }         
    } catch (erMap) { }
}

function InterActiveMap(mapDivID, width, height) {
    this.MapContainer = document.getElementById(mapDivID);
    this.WaitingDiv = document.getElementById(mapDivID + 'v');
    this.WaitingDiv.style.display = 'none';
    this.WaitingDiv.style.width = width + 'px';
    this.WaitingDiv.style.height = height + 'px';
    this.FullScreenVar = new Object();
    this.IsFullScreen = false;
    this.MapVisible = false;
    //this.Apartments = apartments;
    this.Width = width;
    this.Height = height;
    this.MarkersOnMap = new Array();
    this.HiddenElemets = new Array();
    this.OverlayDiv = null;
    this.LegendDiv = null;
    this.SearchFilterDivHeight = null;
    this.MapObjects = new Object();
    this.SelectedMarker = null;
    this.LandmarkPrecision = 4; //round long, lat precision
    this.CategoriesToShow = new Array();
    this.ObjectIDsToShow = new Array();
    this.InfoWindow = null;
    this.StreetViewEnabled = false;
    if (VersionIM == 5) {
        this.InfoWindow = new InfoBox(
        {
            //size: new google.maps.Size(400, 100)

            boxStyle: {
                opacity: 1.00, width: '447px',
                overflow: 'hidden'
            }
        , closeBoxMargin: "-1px 0px"
        , closeBoxURL: "http://cachefly.apartmentsapart.com/aa/img_modules/im/cross2.gif"
        , infoBoxClearance: new google.maps.Size(100, 100)
        , pane: "floatPane"
        , pixelOffset: new google.maps.Size(20, -27)
        });
    }
    else {
        this.InfoWindow = new google.maps.InfoWindow(
        {
            //size: new google.maps.Size(400, 100)
            maxWidth: 490
        });
    }
    this.GooogleMapObject = null;
    this.bounds = new google.maps.LatLngBounds();
    this.OrganizedApartments = new Object();
    this.OrganizedApartments.Count = 0;
    this.OrganizedTop3Apartments = new Array();
    this.MapObjectsMarkers = new Object();
    this.SingleAptIcon = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/icon.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 28),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
    this.SingleAptIconSelected = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/icon_sa.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 28),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
    this.SingleAptIconGray = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/icon_gray.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 28),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));      
    this.MultiAptIcon = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/multiicon.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 37),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
    this.MultiAptIconGray = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/multiicon_gray.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 37),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));      
    this.MultiAptIconSelected = new google.maps.MarkerImage('http://cachefly.apartmentsapart.com/aa/img_modules/im/multiicon_sa.gif',
    // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(28, 37),
    // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
    this.MapObjectIcons = new Object();
    this.CreateMapObjectIcons = function(imgs) {
    this.MapObjectIcons = new Object();
    for (var catKey in imgs) {
        this.MapObjectIcons[catKey] = new google.maps.MarkerImage(imgs[catKey],
        // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(22, 22),
        // The origin for this image is 0,0.
      new google.maps.Point(0, 0),
        // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
        }
    }
    this.RoundValue = function(value, precision) {
        return Math.round(parseFloat(value) * Math.pow(10, precision)) / Math.pow(10, precision);
    }

    this.OrganizeApartmentsToMarkers = function(apartments) {
        if (VersionIM == 3 && showapts == '0') {
            return;
        }
        this.OrganizedApartments = new Object();
        this.Apartments = apartments

        if (VersionIM == 3 && showapts != '') {
            var apts = showapts.split(',');
            var tmpApts = new Array();
            for (i = 0; i < this.Apartments.length; ++i) {
                for (j = 0; j < apts.length; ++j) {
                    if (this.Apartments[i].ID.toString() == apts[j]) {
                        tmpApts.push(this.Apartments[i]);
                    }
                }
            }
            this.Apartments = tmpApts
        }

        for (var a in this.Apartments) {
            if (typeof (this.Apartments[a]) == 'object') {
                var elem = this.Apartments[a];
                for (var b in elem.InfoForMap.AptDetails) {
                    if (typeof (elem.InfoForMap.AptDetails[b]) == 'object') {
                        var info = elem.InfoForMap.AptDetails[b];
                        if (info.Latitude == 'AtLeastOneAptHasNoLatLng') {
                            noLatLngAlert = true;
                            if (elem.ID == AptID) {
                                hideAptMap = true;
                            }
                            hideCityMap++;
                        }
                        var tmp = this.RoundValue(info.Latitude, this.LandmarkPrecision) + '_' + this.RoundValue(info.Longitude, this.LandmarkPrecision);
                        if (tmp.toLowerCase() != "nan_nan") {
                            if (this.OrganizedApartments[tmp] == null) {
                                this.OrganizedApartments[tmp] = new Array();
                                elem.InfoForMap.CurrentDetailsIdex = b;
                                this.OrganizedApartments[tmp].push(elem);
                                this.OrganizedApartments.Count++;
                            } else {
                                this.OrganizedApartments[tmp].push(elem);
                                elem.InfoForMap.CurrentDetailsIdex = b;

                            }
                        }
                    }
                }
            }
        } 
        if (hideCityMap == this.Apartments.length) {
            hideAptMap = true;
        }

        if (VersionIM == 4) {
            if (typeof (im_ApartmentsOnMapTop3) != 'undefined') {
                this.OrganizedTop3Apartments = new Array();
                for (var a in im_ApartmentsOnMapTop3) {
                    if (typeof (im_ApartmentsOnMapTop3[a]) == 'object') {
                        var elem = im_ApartmentsOnMapTop3[a];
                        for (var b in elem.InfoForMap.AptDetails) {
                            if (typeof (elem.InfoForMap.AptDetails[b]) == 'object') {
                                var info = elem.InfoForMap.AptDetails[b];
                                if (info.Latitude == 'AtLeastOneAptHasNoLatLng') {
                                    break;
                                }
                                var tmp = this.RoundValue(info.Latitude, this.LandmarkPrecision) + '_' + this.RoundValue(info.Longitude, this.LandmarkPrecision);
                                if (tmp.toLowerCase() != "nan_nan") {
                                    this.OrganizedTop3Apartments.push(elem.ID);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    this.OrganizeCategoriesAndObjectIDs = function() {
        MapEngine.ObjectIDsToShow = new Array();
        MapEngine.CategoriesToShow = new Array();
        if (typeof (markerCategories) != "undefined") {
            var mc = markerCategories.split(',');
            if (mc != "") {
                for (i = 0; i < mc.length; ++i) {
                    var c = parseInt(mc[i]);
                    if (MapEngine.MapObjects[c] != null) {
                        MapEngine.CategoriesToShow.push(c);
                    }
                }
            }
        }

        if (mapObjectsIDs != "") {
            var moids = mapObjectsIDs.split(',');
            for (i = 0; i < moids.length; ++i) {
                var moid = parseInt(moids[i]);
                MapEngine.ObjectIDsToShow.push(moid);
                var founded = false;
                for (var type in MapEngine.MapObjects) {
                    if (founded) {
                        break;
                    }
                    else {
                        for (j = 0; j < MapEngine.MapObjects[type].length; ++j) {
                            if (typeof (MapEngine.MapObjects[type][j]) == 'object') {
                                if (MapEngine.MapObjects[type][j].Id == moid) {
                                    MapEngine.CategoriesToShow.push(type);
                                    founded = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    this.GetAndOrganizeMapObjects = function() {
        if (Type == 'aptdetails' || Type == 'maplanding' || Type == 'landmarklanding') {
            apartmentsapart.Modules.InteractiveMap.GetMapObjects(JSMAN_CITYID, JSMAN_LANGID, im_ListID, this.OrganizeMapObjects);
        }
        else if (Type != 'static') {
            apartmentsapart.Modules.AjaxApartmentListSearch.GetMapObjects(JSMAN_CITYID, JSMAN_LANGID, this.OrganizeMapObjects);
        }
        else {
            apartmentsapart.Modules.AjaxApartmentList.GetMapObjects(JSMAN_CITYID, JSMAN_LANGID, this.OrganizeMapObjects);
        }
    }

    this.OrganizeMapObjects = function(objects) {
        MapEngine.MapObjects = new Object();

        if (!MapEngine.IsCityHasOtherMarkers()) {
            for (var a in objects.value) {
                if (typeof (objects.value[a]) == 'object') {
                    var object = objects.value[a];
                    if (object.Objecttype == 1 || object.Objecttype == 2) {
                        if (MapEngine.MapObjects[object.Objecttype] == null) {
                            MapEngine.MapObjects[object.Objecttype] = new Array();
                            MapEngine.MapObjects[object.Objecttype].push(object);
                        } else {
                            MapEngine.MapObjects[object.Objecttype].push(object);
                        }
                    }
                }
            }
        }
        else {
            for (var a in objects.value) {
                if (typeof (objects.value[a]) == 'object') {
                    var object = objects.value[a];
                    if (MapEngine.MapObjects[object.Objecttype] == null) {
                        MapEngine.MapObjects[object.Objecttype] = new Array();
                        MapEngine.MapObjects[object.Objecttype].push(object);
                    } else {
                        MapEngine.MapObjects[object.Objecttype].push(object);
                    }
                }
            }
        }

        MapEngine.OrganizeCategoriesAndObjectIDs();
        if (VersionIM == 2 && !MapEngine.IsFullScreen) {
            if (MapEngine.MapObjects[1] != null) { //dodanie biura 
                var a = new Object();
                a.checked = true;
                if (MapEngine.MapObjects[1] != null) {
                    MapEngine.MarkersCat(1, a);
                }
            }

            return;
        }
        else if (VersionIM == 3) {
            var a = new Object();
            a.checked = true;

            if (Type == 'maplanding') {
                for (i = 0; i < MapEngine.CategoriesToShow.length; ++i) {
                    var c = MapEngine.CategoriesToShow[i];
                    if (MapEngine.MapObjects[c] != null) {
                        MapEngine.MarkersCat(c, a);
                    }
                }
            }
            if ((!MapEngine.IsCityHasOtherMarkers() && Type == 'maplanding' && showapts == '') || Type == 'landmarklanding') {
                if (MapEngine.MapObjects[1] != null) {
                    MapEngine.MarkersCat("1", a);
                }
                if (MapEngine.MapObjects[2] != null) {
                    MapEngine.MarkersCat("2", a);
                }
            }
        }

        if (MapEngine.OverlayDiv != null) {
            return;
        }

        if (MapEngine.IsCityHasOtherMarkers() && Type != 'landmarklanding') {
            var controlDiv = document.createElement('DIV');
            controlDiv.setAttribute('id', 'im_controlcont');
            controlDiv.className = 'noprint';
            /// var controlswitch = document.createElement('DIV');
            //controlswitch.setAttribute('id', 'im_switch');
            //controlswitch.innerHTML = '&nbsp;';
            var controlUI = document.createElement('DIV');
            controlUI.setAttribute('id', 'im_control');
            //controlUI.style.display = 'none';
            controlUI.innerHTML = '&nbsp;';
            controlDiv.appendChild(controlUI);
            // controlDiv.appendChild(controlswitch);

            //    google.maps.event.addDomListener(controlswitch, 'click', function() {
            //        var ctrl = MapEngine.OverlayDiv;
            //        if (ctrl.style.display == 'none') {
            //            ctrl.style.display = '';
            //        } else {
            //            ctrl.style.display = 'none';
            //        }
            //    });




            var overlayBuilder = '';
            var collapsed_control = '';
            if (VersionIM == 5) {
                overlayBuilder = '<div id="im_ectrl" style="display:none"><div class="im_clc">' + im_phrases["click_to_show"] + '</div>';
                collapsed_control = '<div id="im_cctrl"><div class="im_clc">&nbsp;</div>';
                controlDiv.style.width = '92px';

            } else {
                overlayBuilder = '<div id="im_ectrl"><div class="im_clc">' + im_phrases["click_to_show"] + '</div>';
                collapsed_control = '<div id="im_cctrl" style="display:none"><div class="im_clc">&nbsp;</div>';
            }


            var moChecked = '';
            for (var type in MapEngine.MapObjects) {
                if (VersionIM == 2 && MapEngine.IsFullScreen) {
                    moChecked = 'checked = "true"';
                }
                else if (VersionIM == 3) {
                    for (i = 0; i < MapEngine.CategoriesToShow.length; ++i) {
                        var c = MapEngine.CategoriesToShow[i];
                        if (type == c) {
                            moChecked = 'checked = "true"';
                        }
                    }
                }
                if (type == 1) {
                    moChecked = 'checked = "true"';
                    var a = new Object();
                    a.checked = true;
                    MapEngine.MarkersCat(1, a);
                }
                collapsed_control += '<div onmouseover="ShowToolTip(&quot;' + MO_CatLabels[type] + '&quot;);" onmouseout="HideToolTip();" style="height:26px;"><span style="float:left;margin-left:3px;" class="imc_' + type + '">&nbsp;</span><input style="float:right;margin-right:8px;" id="inch_' + type + '" type="checkbox" ' + moChecked + ' onclick="MapEngine.MarkersCat(' + type + ',this)" /></div>';
                overlayBuilder += '<div class="im_cat"><span class="imc_' + type + '">&nbsp;</span><input id="inch_' + type + '" type="checkbox" ' + moChecked + ' onclick="MapEngine.MarkersCat(' + type + ',this)" /><label for="inch_' + type + '" class="im_cat_desc">' + MO_CatLabels[type] + '</label></div>';
                moChecked = ''
            }

            if (VersionIM == 5 && AptID > 0) {
                collapsed_control += '<div onmouseover="ShowToolTip(&quot;' + MO_CatLabels[11] + '&quot;);"  onmouseout="HideToolTip();" style="height:26px;"><span style="float:left;margin-left:3px;" class="imc_11">&nbsp;</span><input style="float:right;margin-right:8px;" id="inch_11" type="checkbox" onclick="MapEngine.HideOtherApartments(this)" /></div>';
                overlayBuilder += '<div class="im_cat"><span class="imc_11">&nbsp;</span><input id="inch_11" type="checkbox" onclick="MapEngine.HideOtherApartments(this)" /><label for="inch_11" class="im_cat_desc">' + MO_CatLabels[11] + '</label></div>';
            }
            overlayBuilder += '</div>'; //im_ectrl
            controlUI.innerHTML = overlayBuilder;
            collapsed_control += '</div>'; //im_cctrl
            controlUI.innerHTML += collapsed_control;
            if (VersionIM == 5 && AptID > 0) {
                var switchStyle = 'margin-top:30px;';
                if (navigator.userAgent.toLowerCase().indexOf('msie 6') > -1 || navigator.userAgent.toLowerCase().indexOf('msie 7') > -1) {
                    switchStyle = 'margin-top:-240px;';
                }
                controlDiv.innerHTML += '<div id="im_switch" onclick="MapEngine.CollapseControl()" style="display:none;' + switchStyle + '">&nbsp;</div>';
                controlDiv.innerHTML += '<div style="' + switchStyle + '" id="im_switch2" onclick="MapEngine.ExpandControl()">&nbsp;</div>';
            }
            else if (VersionIM == 5) {
                controlDiv.innerHTML += '<div id="im_switch" onclick="MapEngine.CollapseControl()" style="display:none">&nbsp;</div>';
                controlDiv.innerHTML += '<div id="im_switch2" onclick="MapEngine.ExpandControl()">&nbsp;</div>';
            }
            else {
                controlDiv.innerHTML += '<div id="im_switch" onclick="MapEngine.CollapseControl()">&nbsp;</div>';
                controlDiv.innerHTML += '<div id="im_switch2" onclick="MapEngine.ExpandControl()" style="display:none">&nbsp;</div>';
            }
            MapEngine.OverlayDiv = controlDiv;
            MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_CENTER].push(controlDiv);
        }
        else if (VersionIM == 1 || VersionIM == 4 || VersionIM == 5) {
            if (VersionIM == 5 && AptID > 0) {
                var controlDiv = document.createElement('DIV');
                controlDiv.setAttribute('id', 'im_controlcont');
                controlDiv.className = 'noprint';

                var controlUI = document.createElement('DIV');
                controlUI.setAttribute('id', 'im_control');

                controlUI.innerHTML = '&nbsp;';
                controlDiv.appendChild(controlUI);

                var overlayBuilder = '<div id="im_ectrl" style="display:none">';
                var collapsed_control = '<div id="im_cctrl">';
                controlDiv.style.width = '92px';

                collapsed_control += '<div onmouseover="ShowToolTip(&quot;' + MO_CatLabels[11] + '&quot;);"  onmouseout="HideToolTip();" style="height:144px;"><span style="float:left;margin-left:3px;margin-top:63px;" class="imc_11">&nbsp;</span><input style="float:right;margin-right:8px;margin-top:67px;" id="inch_11" type="checkbox" onclick="MapEngine.HideOtherApartments(this)" /></div>';
                overlayBuilder += '<div style="height:140px;" class="im_cat"><span style="margin-top:63px;" class="imc_11">&nbsp;</span><input style="margin-top:67px;" id="inch_11" type="checkbox" onclick="MapEngine.HideOtherApartments(this)" /><label style="margin-top:65px;" for="inch_11" class="im_cat_desc">' + MO_CatLabels[11] + '</label></div>';

                overlayBuilder += '</div>'; //im_ectrl
                controlUI.innerHTML = overlayBuilder;
                collapsed_control += '</div>'; //im_cctrl
                controlUI.innerHTML += collapsed_control;

                var switchStyle = 'margin-top:-51px;';
                if (navigator.userAgent.toLowerCase().indexOf('msie 6') > -1 || navigator.userAgent.toLowerCase().indexOf('msie 7') > -1) {
                    switchStyle = 'margin-top:-151px;';
                }

                controlDiv.innerHTML += '<div id="im_switch"  onclick="MapEngine.CollapseControl()" style="display:none;' + switchStyle + '">&nbsp;</div>';
                controlDiv.innerHTML += '<div id="im_switch2" onclick="MapEngine.ExpandControl()" style="' + switchStyle + '">&nbsp;</div>';

                MapEngine.OverlayDiv = controlDiv;
                MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_CENTER].push(controlDiv);
            }
            for (var type in MapEngine.MapObjects) {
                var a = new Object();
                a.checked = true;
                MapEngine.MarkersCat(type, a);
            }
        }
    }

    this.HideOtherApartments = function(e) {
        if (e.checked) {
            for (var marker in this.MarkersOnMap) {
                var apt = this.MarkersOnMap[marker];
                if (apt.icon == this.SingleAptIcon || apt.icon == this.MultiAptIcon) {
                    apt.setMap(null);
                }
            }
        }
        else {
            for (var marker in this.MarkersOnMap) {
                var apt = this.MarkersOnMap[marker];
                if (apt.icon == this.SingleAptIcon || apt.icon == this.MultiAptIcon) {
                    apt.setMap(this.GooogleMapObject);
                }
            }                     
        }
    }   
    
    this.CreateMapObject = function(zoom, centerLat, centerLng) {
        this.MapContainer.style.width = MapEngine.Width + 'px';
        this.MapContainer.style.height = MapEngine.Height + 'px';

        if (this.GooogleMapObject != null)
            return;
        //this.MapContainer.innerHtml = '';

        //this.RefreshMapElement();

        var myOptions = {
        zoom: zoom,
            scaleControl:true,
            center: new google.maps.LatLng(centerLat, centerLng),
            mapTypeControl: true,
            mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR },
            navigationControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
            //            ,navigationControlOptions: {
            //                style: google.maps.NavigationControlStyle.ZOOM_PAN, position:  google.maps.ControlPosition.TOP_LEFT 
            //            } 
        }
        this.GooogleMapObject = new google.maps.Map(this.MapContainer, myOptions);
        google.maps.event.addListener(this.GooogleMapObject, 'click', function() {
            MapEngine.InfoWindow.close();
        });

        if (VersionIM == 1 || VersionIM == 4 || VersionIM == 5 || (VersionIM == 3 && Type == 'maplanding')) {
            this.CreateFullScreenButton();
        }


    }
    /*this.ChangeCurrencyInMarkerDescription = function(oldCurr, newCurr) {
        this.BuildMarkers(undefined, "EUR");
    }*/
    this.BuildMarkres = function(apartmentid) {
        this.SelectedMarker = null;
        if (VersionIM == 1 || VersionIM == 2 || (VersionIM == 3 && typeof (apartmentid) == 'undefined') || VersionIM == 4 || VersionIM == 5) {
            for (var i = 0; i < this.MarkersOnMap.length; i++) {
                this.MarkersOnMap[i].setMap(null);
            }

            this.CreateLegend();
            this.CreateMissingAptAlert();
            if (this.LegendDiv != null) {
                this.LegendDiv.style.display = 'none';
            }
            if (this.LegendDiv != null && VersionIM == 3 && Type == 'maplanding') {
                this.LegendDiv.style.display = 'none';
            }

            if (Type == 'aptdetails' && this.IsFullScreen) { // Type-> variable from AjaxApartmentList/Search/InterActiveMap
                im_Snippet = im_Snippet_static;
            }
            else if (Type == 'aptdetails' && !this.IsFullScreen) {
                im_Snippet = im_Snippet_aptdetails;
            }
        }
        var selectedAptHasLatLng = false;
        this.MarkersOnMap = new Array();
        this.bounds = new google.maps.LatLngBounds();
        for (var p in this.OrganizedApartments) {
            var point = p.split('_');
            if (point.length != 2)
                continue;
            var myLatLng = new google.maps.LatLng(point[0], point[1]);
            var infoWBuilder = '';
            this.bounds.extend(myLatLng);
            var info = this.OrganizedApartments[p]; // info-> array of ListElement objects
            var icon = this.SingleAptIcon;
            if (info.length > 1)
                icon = this.MultiAptIcon;
            var label = '';
            var snippet = im_Snippet;
            var isSelected = false;
            var morethan1 = false;
            var AptIDsForMarker = new Array();
            var top3 = 0;
            for (var i = 0; i < info.length; i++) {
                if (this.LegendDiv != null && (VersionIM == 1 || VersionIM == 4 || VersionIM == 5 || (VersionIM == 3 && Type == 'maplanding'))) {
                    this.LegendDiv.style.display = '';
                }
                snippet = im_Snippet;
                label += info[i].InfoForMap.AptNames[info[i].InfoForMap.CurrentDetailsIdex];
                var listelem = info[i];

                var currElem = info[i].InfoForMap.CurrentDetailsIdex;
                var name = listelem.InfoForMap.AptNames[currElem];
                if (typeof (apartmentid) != "undefined" && listelem.ID.toString() == apartmentid.toString()) {
                    isSelected = true;
                    snippet = snippet.replace("class=\"iws\"", "class=\"iwse\"");
                    selectedAptHasLatLng = true;
                }
                AptIDsForMarker.push(listelem.ID);
                var img_src = listelem.InfoForMap.ImagesSRC[currElem];
                var descr = listelem.InfoForMap.Description[currElem];
                var bookurl = listelem.InfoForMap.BookUrl;
                var price = listelem.InfoForMap.Price;
                /*if (newCurrency == "EUR") {
                price = apartmentsapart.Modules.AjaxApartmentListSearch.ConvertCurrency(listelem.DiscountedPrice).value;
                }*/
                var aptdetUrl = listelem.InfoForMap.AptDetailsURL[currElem];

                snippet = snippet.replace("#aptname#", name);
                snippet = snippet.replace("#src#", img_src);
                var priceInCityCurrency = listelem.DiscountedPrice == 0 ? listelem.MinPrice : listelem.DiscountedPrice;
                if (priceInCityCurrency == 0) {
                    price = im_phrases["ask_for_price"];
                }
                if (descr == '') {
                    snippet = snippet.replace("#desc#", "<span class=\"price\"><b>" + im_phrases["price"] + ":</b>&nbsp;" + price + '<span style="display: none;">' + priceInCityCurrency + "</span></span>");
                    snippet = snippet.replace(/style=\"\"/g, "style=\"display:none\"");
                } else {
                    snippet = snippet.replace("#desc#", descr);
                    snippet = snippet.replace("#price#", price + '<span style="display: none;">' + priceInCityCurrency + '</span>');
                }
                if (Type != 'static') // variable from AjaxApartmentList/Search
                {
                    snippet = snippet.replace("#book#", bookurl);
                }
                if (Type == 'search') {
                    var convertedPrice = '';
                    if (priceInCityCurrency == 0) {
                        convertedPrice = price;
                    }
                    else {
                        convertedPrice = Math.round((priceInCityCurrency * (currrates[orgC] / currrates[als.currency]))) + ' ' + als.currency;
                    }
                    label += ' -<span class=\"price\">&nbsp;' + convertedPrice + '<span style="display: none;">' + priceInCityCurrency + '</span></span>';
                }

                snippet = snippet.replace(/#aptdetailurl#/g, aptdetUrl);
                var unit;
                if (VersionIM == 1) {
                    unit = document.sortform.unitdd.options[document.sortform.unitdd.selectedIndex].text;
                }
                if (VersionIM == 2) {
                    unit = 'm2';

                    var floor = listelem.InfoForMap.AptDetails[currElem].Floor;
                    var elevator = listelem.InfoForMap.AptDetails[currElem].Elevator;
                    if (elevator > 0)
                        elevator = im_phrases["elevator"];
                    else
                        elevator = im_phrases["no_elevator"];
                    snippet = snippet.replace("#infofloor#", floor + ". " + im_phrases["floor"] + "(" + elevator + ")");

                    if (apartmentid != info[i].Apt.ID) {
                        if (info.length == 0) {
                            icon = this.SingleAptIconGray;
                        }
                        else if (info.length > 1) {
                            icon = this.MultiAptIconGray;
                        }
                        else {
                            icon = this.SingleAptIconGray;
                        }
                    }
                }
                else if (VersionIM == 3) {
                    unit = 'm2';
                }

                if (VersionIM == 4 || VersionIM == 5) {
                    for (t = 0; t < this.OrganizedTop3Apartments.length; ++t) {
                        if (listelem.ID != this.OrganizedTop3Apartments[t]) {
                            top3++;
                        }
                    }
                    if (top3 == (3 * info.length)) {
                        if (info.length == 0) {
                            icon = this.SingleAptIconGray;
                        }
                        else if (info.length > 1) {
                            icon = this.MultiAptIconGray;
                        }
                        else {
                            icon = this.SingleAptIconGray;
                        }
                    }
                    snippet = snippet.replace("#icons#", listelem.IconsHtml);

                    var percentage = Math.round(listelem.CustomersRating);
                    var stars = '';
                    if (percentage != 0) {
                        var template = '<div class="rating" onclick="showSurveyWindow(event, #ratingwindow#)">#customers_rating#:&nbsp;<b>#rating#</b><div>';
                        template = template.replace("#ratingwindow#", "'/IndexFrame.aspx?pageid=9389&domainid=1&l=" + JSMAN_LANGID + "&a=" + listelem.ID + "&own=1'");
                        template = template.replace("#customers_rating#", im_phrases["customers_rating"]);
                        template = template.replace("#rating#", listelem.CustomersRating);
                        snippet = snippet.replace("#rating_template#", template);

                        for (s = 0; s < percentage; ++s)
                            stars += '<img src="http://cachefly.apartmentsapart.com/aa/img_modules/stara1.gif" alt="" />';
                        for (s = percentage; s < 10; ++s)
                            stars += '<img src="http://cachefly.apartmentsapart.com/aa/img_modules/stara2.gif" alt="" />';
                        snippet = snippet.replace("#stars#", stars);
                    }
                    else {
                        snippet = snippet.replace("#rating_template#", "");

                        snippet = snippet.replace("#stars#", '');
                    }
                }
                if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
                    snippet = snippet.replace("#ls#", listelem.LivingSpace + unit + '<span style="display: none;">' + listelem.LivingSpace + '</span>');
                }
                else if (VersionIM == 4) {
                    snippet = snippet.replace("#ls#", this.ConvertUnitToString(listelem.LivingSpace) + '<span style="display: none;">' + ConvertUnit(listelem.LivingSpace) + '</span>');
                }
                else if (VersionIM == 5) {
                    snippet = snippet.replace("#ls#", listelem.LivingSpace + ' m2<span style="display: none;">' + listelem.LivingSpace + '</span>');
                }
                snippet = snippet.replace("#cf#", listelem.CanSleepMax);
                snippet = snippet.replace("#apttype#", listelem.InfoForMap.Apartmenttype);


                if (info[i].InfoForMap.AptNames.Count > 1) {
                    label += ' (';
                    for (var j = 0; j < info[i].InfoForMap.AptNames.Count; j++) {
                        if (j != info[i].InfoForMap.CurrentDetailsIdex) {
                            label += info[i].InfoForMap.AptNames[j] + '+';
                        }
                    }
                    label = label.slice(0, label.length - 1);
                    label += ')';
                }
                label += '<br />';

                if ((VersionIM == 2 && !this.IsFullScreen && listelem.ID.toString() != apartmentid.toString()) || (VersionIM == 3 && Type == 'landmarklanding')) {
                    if (!morethan1 && icon != this.SingleAptIconGray) {
                        snippet = im_phrases["other_apt"] + ".<br />" + im_phrases["morethan1"] + ":";
                        snippet += '<br /><b><a href="' + aptdetUrl + '" target="_blank">' + info[i].InfoForMap.AptNames[0] + '</a></b>';
                    }
                    else if (icon == this.SingleAptIconGray) {
                        snippet = im_phrases["other_apt"] + ":";
                        snippet += '<br /><b><a href="' + aptdetUrl + '" target="_blank">' + info[i].InfoForMap.AptNames[0] + '</a></b>';
                    }
                    else {
                        snippet = '<br /><b><a href="' + aptdetUrl + '" target="_blank">' + info[i].InfoForMap.AptNames[0] + '</a></b>';
                    }
                    morethan1 = true;
                }


                if (isSelected && listelem.ID.toString() == apartmentid.toString()) {
                    infoWBuilder = snippet + infoWBuilder;
                } else {
                    infoWBuilder += snippet;
                }
            }
            infoWBuilder = '<div class="boxanchor"></div><div class="im_infow">' + infoWBuilder + '</div>';

            if (isSelected) {
                icon = this.SingleAptIconSelected;
                if (info.length > 1)
                    icon = this.MultiAptIconSelected;
            }

            //  if (myLatLng.toString().toLowerCase().indexOf("nan") == -1) {
            var marker = this.createMarker(this.GooogleMapObject, myLatLng, label, infoWBuilder, icon, AptIDsForMarker);
            this.MarkersOnMap.push(marker);
            if (isSelected) {
                this.SelectedMarker = new Object();
                this.SelectedMarker["marker"] = marker;
                this.SelectedMarker["info"] = infoWBuilder;
            }
            //    }
        }
        if (VersionIM == 1 || VersionIM == 2 || (VersionIM == 3 && (typeof (apartmentid) == 'undefined' || showapts != '')) || VersionIM == 4 || VersionIM == 5) {
            if (VersionIM == 2) { //hiding map where there is no lat/lng for aptdetails page
                if (!selectedAptHasLatLng) {
                    document.getElementById('im_mapm').style.display = 'none';
                }
            }

            if (typeof (apartmentid) == "undefined") {
                this.GooogleMapObject.fitBounds(this.bounds);
            }

            this.CreateCustomControl();
        }

    }
    this.ConvertUnitInInfoWindow = function(contentString) {
        var pat = /<b class="ls">.*?<\/b>&nbsp;(.*?)<span style="displ.*?">(\d+)<\/span>/g;
        var re = new RegExp(pat);

        var m = re.exec(contentString);

        while (m != null){ 
            if (m.length % 3 == 0) {
                for (var i = 0; i < m.length; i = i + 3) {
                    var newLS = ConvertUnit(m[2]); //apartmentsapart.Modules.AjaxApartmentListSearch.ConvertCurrency(parseFloat(m[2])).value;
                    newLS += ' ' + document.sortform.unitdd.options[document.sortform.unitdd.selectedIndex].text;
                    contentString = contentString.replace(m[1], newLS);
                }

            }
            m = re.exec(contentString);
        }
        return contentString;

    }
    
    this.ConvertUnitToString = function(value) {
        if (typeof (document.sortform) != 'undefined') {
            var newLS = ConvertUnit(value); //apartmentsapart.Modules.AjaxApartmentListSearch.ConvertCurrency(parseFloat(m[2])).value;
            newLS += ' ' + document.sortform.unitdd.options[document.sortform.unitdd.selectedIndex].text;
        }
        else if (typeof (als) != 'undefined' && als != null) {
            var newLS = ConvertUnit(value, als.unit); //apartmentsapart.Modules.AjaxApartmentListSearch.ConvertCurrency(parseFloat(m[2])).value;
            var unit;
            if (als.unit == 0) {
                unit = 'm2';
            }
            else {
                unit = 'ft2';
            }
            newLS += ' ' + unit;
        }
        return newLS;
    }      
    this.ConvertCurrencyInInfoWindow = function(contentString) {
        var pat = /<span class="price">.*?nbsp;(.*?)<span style="displ.*?">(\d+)<\/span><\/span>/g;
        var re = new RegExp(pat);

        var m = re.exec(contentString);

        while (m != null) {
            if (m.length % 3 == 0) {
                for (var i = 0; i < m.length; i = i + 3) {
                    if (m[2] == 0) {
                        continue;
                    }
                    var newPrice;
                    if (typeof (document.sortform) != 'undefined') {
                        newPrice = ConvertPrice(m[2]); //apartmentsapart.Modules.AjaxApartmentListSearch.ConvertCurrency(parseFloat(m[2])).value;                       
                        newPrice += ' ' + document.sortform.currencydd.options[document.sortform.currencydd.selectedIndex].text;
                    }
                    else if (document.getElementById('ddcurrency') != null) {
                        var curr = document.getElementById('ddcurrency').value;
                        var zlval = currrates[orgC] *  m[2];
                        newPrice = Math.round(zlval / currrates[curr]);
                        newPrice += ' ' + curr;
                    }
                    else if (typeof (als) != 'undefined' && als != null) {
                        newPrice = ConvertPrice(m[2], als.currency);
                        newPrice += ' ' + als.currency;
                    }
                    else {
                        newPrice = m[2] + ' ' + 'EUR';
                    }
                    contentString = contentString.replace(m[1], newPrice);
                }

            }
            m = re.exec(contentString);
        }
        return contentString;

    }
    this.createMarker = function(map, latlng, label, html, markerIcon, aptIDs) {
        var contentString = html;
        label += '<b>' + im_phrases["click_for_details"] + '</b>';
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            shadow: null,
            icon: markerIcon,
            shape: null,
            tooltip: label,
            apartmentIDs: null,
            //title: null,
            zIndex: Math.round(latlng.lat() * -100000) << 5
        });

        marker.attachTipTool(marker.tooltip);

        if (markerIcon == this.SingleAptIconSelected || markerIcon == this.MultiAptIconSelected) {
            marker.zIndex = 5000000;
            marker.optimized = false;
        }
        if (VersionIM == 3 || VersionIM == 5) {
            marker.apartmentIDs = aptIDs;
        }

        google.maps.event.addListener(marker, 'click', function() {
            var content = MapEngine.ConvertCurrencyInInfoWindow(contentString);
            if (VersionIM == 5) {
                if (content.length < 3500) {
                    content = content.replace('class="im_infow"', 'class="im_infow" style="height:150px;"');
                    if (content.length < 180 && content.indexOf('class="im_infow"') == -1) {
                        MapEngine.InfoWindow.boxStyle_.width = (content.length * 1.6) + "px";
                    }
                    else {
                        MapEngine.InfoWindow.boxStyle_.width = '431px';
                    }
                }
                else {
                    MapEngine.InfoWindow.boxStyle_.width = '447px';
                }

                MapEngine.LoadStreetView(marker.position);
            }
            MapEngine.InfoWindow.setContent(content);
            MapEngine.InfoWindow.open(map, marker);
        }
        );
        google.maps.event.addListener(marker, 'mouseout', function() {
            //ToolTipClass.hide();
            if (!this.FromLegend) {
                HideToolTip();
                if (marker.getAnimation() == 'disable') {
                    marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            }
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
            //ToolTipClass.show("<strong>Polygon Hovering</strong><br /><p>This is a work around I made to mimic 'mouseover' and 'mouseout' event for Polygons on Google Map Javascript API v3.</p><br>If you find this technique useful, drop me a line at: erwin.quinto@gmail.com");
            // eval('ShowToolTip("' + marker.tooltip + '")');
            if (!this.FromLegend) {
                ShowToolTip(marker.tooltip);
                if (marker.getAnimation() == google.maps.Animation.BOUNCE) {
                    marker.setAnimation('disable'); //'disable' is fake argument only for recognition on mouseout, proper value is null
                }
            }

        });
        return marker;
    }
    this.createZone = function(map, coordinates, label, info, stroke_Color, fill_Color) {
        label += '<br /><b>' + im_phrases["click_for_details"] + '</b>';
        var tmpZone = new google.maps.Polygon({
            paths: coordinates,
            strokeColor: stroke_Color,
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: fill_Color,
            fillOpacity: 0.35
        });
        tmpZone.setMap(map);
        tmpZone.attachTipTool(label);

        google.maps.event.addListener(tmpZone, 'click', function(event) {
            MapEngine.InfoWindow.setContent(info);
            //MapEngine.InfoWindow.open(map, tmpZone);
            MapEngine.InfoWindow.setPosition(event.latLng);
            MapEngine.InfoWindow.open(map);

        });
        google.maps.event.addListener(tmpZone, 'mouseout', function() {
            //ToolTipClass.hide();
            if (!this.FromLegend) {
                HideToolTip();
            }
        });
        google.maps.event.addListener(tmpZone, 'mousemove', function() {
            //ToolTipClass.show("<strong>Polygon Hovering</strong><br /><p>This is a work around I made to mimic 'mouseover' and 'mouseout' event for Polygons on Google Map Javascript API v3.</p><br>If you find this technique useful, drop me a line at: erwin.quinto@gmail.com");
            if (!this.FromLegend) {
                eval('ShowToolTip("' + label + '")');
            }
        });

        return tmpZone;
    }
    this.SetHeader = function(element) {
        var list_Header = document.getElementById('im_but');
        element.childNodes[0].nodeValue = list_Header.childNodes[0].nodeValue;
    }
    this.CreateListButton = function(elemID) {
    //var cont = document.getElementById(elemID);
        if(Type == 'search')
            this.SetHeader(document.getElementById('im_maph'));
        var newdiv = document.createElement('div');
        newdiv.setAttribute('id', 'im_but_elem');
        newdiv.innerHTML = im_phrases["map_view"];
        //cont.appendChild(newdiv);
        
        if (window.addEventListener) { // Mozilla, Netscape, Firefox
            newdiv.addEventListener('click', MapEngine.ShowMap, true);
        } else { // IE
            newdiv.attachEvent('onclick', MapEngine.ShowMap);
        }
        jQuery(elemID).append(newdiv);       
    }
    this.SetNewMapObjects = function(apartmentid) {
        MapEngine.InfoWindow.close();
        this.OrganizeApartmentsToMarkers(im_ApartmentsOnMap);
        this.BuildMarkres(apartmentid);

    }

    this.LoadStreetView = function(point) {
        if (this.StreetViewEnabled) {
            var sv = new google.maps.StreetViewService();
            sv.getPanoramaByLocation(point, 50, function(result, status) {
                if (status == google.maps.StreetViewStatus.OK) {
                    var panoramaOptions = {
                        position: point,
                        pov: {
                            heading: 34,
                            pitch: 10,
                            zoom: 1
                        }
                    };
                    var pano = document.getElementById("pano");
                    pano.style.marginLeft = '15px';
                    pano.style.width = '710px';
                    pano.style.height = '450px';
                    var panorama = new google.maps.StreetViewPanorama(pano, panoramaOptions);
                    MapEngine.GooogleMapObject.setStreetView(panorama);
                }
                else {
                    document.getElementById("pano").style.display = 'none';
                }
            })
        }
    }

    this.ShowMap = function(evt, apartmentid) {
        //mint.fx.Fade("leftPane", 0, 10, 100);
        if (VersionIM == 1) {
            var children = document.getElementById('leftPane').childNodes;
            for (var i = 0; i < children.length; i++) {
                if (children[i].style != null && children[i].style.display != 'none') {
                    MapEngine.HiddenElemets.push(children[i]);
                    children[i].style.display = 'none';

                }
            }
            children = document.getElementById('contentPane').childNodes;
            for (var i = 0; i < children.length; i++) {
                if (children[i].style != null && children[i].style.display != 'none') {
                    MapEngine.HiddenElemets.push(children[i]);
                    children[i].style.display = 'none';

                }
            }

            document.getElementById('modSearch3').style.display = '';
            document.getElementById('modSearchFilter').style.display = '';

            //document.getElementById('im_maph').style.display = '';
            //MapEngine.MapContainer.style.display = '';
            document.getElementById('im_maph').style.visibility = 'hidden';

            var filterNum = document.getElementById('sffilter').childNodes.length;
            if (AllApartments.length == 1 && (FilterRestrictions.Count == 0 || filterNum == 0 || filterNum == 1)) {
                listWith1AptAndNoFilter = true;
            }
        }
        else if (VersionIM == 4) {
            document.getElementById('modAjaxApartmentList').style.display = 'none';
            MapEngine.HiddenElemets.push(document.getElementById('modAjaxApartmentList'));

            document.getElementById('modSearch3').style.display = '';
        }
        document.getElementById('im_mapm').style.display = '';

        MapEngine.CreateMapObject(12, 0, 0);
        MapEngine.SetNewMapObjects(apartmentid);
        //MapEngine.CreatePrintButton();

        if (VersionIM == 1 || VersionIM == 4) {
            var mapSettings = readCookie('im_info');
            if (mapSettings && mapSettings != "2") {
                Slide('left');
                window.location.href = '#ch_map';
            }
        }

        MapEngine.GooogleMapObject.fitBounds(MapEngine.bounds);

        if (MapEngine.SelectedMarker != null && (VersionIM == 1 || (VersionIM == 3 && (Type == 'maplanding' && showapts == '')) || VersionIM == 4 || VersionIM == 5)) {

            //MapEngine.InfoWindow.setContent(MapEngine.SelectedMarker["info"]);
            ///MapEngine.InfoWindow.open(MapEngine.GooogleMapObject, MapEngine.SelectedMarker["marker"]);
            ///MapEngine.GooogleMapObject.setCenter(MapEngine.SelectedMarker["marker"].getPosition(), MapEngine.GooogleMapObject.getZoom());
            /// google.maps.event.trigger(MapEngine.SelectedMarker["marker"], "click");
            // timeout is needed for fixing infowindow size in firefox
            if (VersionIM == 5) {
                var point = new google.maps.LatLng(MapEngine.SelectedMarker["marker"].getPosition().lat(), MapEngine.SelectedMarker["marker"].getPosition().lng());
                MapEngine.LoadStreetView(point);
            }
            setTimeout("google.maps.event.trigger(MapEngine.SelectedMarker[\"marker\"], \"click\")", 1000);
        }

        if (VersionIM == 1) {
            var mapSettings = readCookie('im_info');
            if (mapSettings) {
                switch (mapSettings) {
                    case "2":
                        im_FullScreen();
                        break;
                    default:
                        createCookie('im_info', '1');
                        break;
                }
            } else {
                createCookie('im_info', '1');
            }
            try {
                if (!ModeFromCookie)
                    apartmentsapart.Modules.SearchFilter.SaveListViewModeInSession(JSMAN_VisitID, -2, 1, -2);
            } catch (errm) { }
        }
    }

    this.SelectMarker = function(apartmentid) {
        this.BuildMarkres(apartmentid);

        // MapEngine.GetAndOrganizeMapObjects();

//        for (var i = 0; i < this.MarkersOnMap.length; i++) {
//            for (var j = 0; j < this.MarkersOnMap[i].apartmentIDs.length; j++) {
//                if (this.MarkersOnMap[i].apartmentIDs[j] == apartmentid) {
//                    var marker = this.MarkersOnMap[i];
//                    google.maps.event.trigger(marker, "click");
//                }
//            }
//        }
        google.maps.event.trigger(MapEngine.SelectedMarker["marker"], "click");
    }

    this.HideMap = function(evt) {
        //this.bounds = this.GooogleMapObject.getBounds();
        MapEngine.InfoWindow.close();
        Slide('right');
        window.location.href = '#ch_list';
        for (var i = 0; i < this.HiddenElemets.length; i++) {
            this.HiddenElemets[i].style.display = '';
        }
        createCookie('im_info', '0');

        try {
            apartmentsapart.Modules.SearchFilter.SaveListViewModeInSession(JSMAN_VisitID, -2, 0, -2);
        } catch (errm) { }
    }
    this.CreateFullScreenButton = function() {
        var controlDiv = document.createElement('DIV');
        controlDiv.setAttribute('id', 'im_fs');
        controlDiv.className = 'noprint';
        google.maps.event.addDomListener(controlDiv, 'click', function() {
            im_FullScreen();

        });
        this.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].removeAt(0);
        this.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(controlDiv);
    }
    this.CreateNormalScreenButton = function() {
        var controlDiv = document.createElement('DIV');
        controlDiv.setAttribute('id', 'im_ns');
        google.maps.event.addDomListener(controlDiv, 'click', function() {
            im_ExitFullScreen();


        });
        if (VersionIM == 1 || (VersionIM == 3 && Type == 'maplanding') || VersionIM == 4  || VersionIM == 5) {
            this.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].removeAt(0);
            this.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(controlDiv);
        }
        else {
            this.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(controlDiv);
        }
    }
    this.CreateCustomControl = function() {
        if (Type != 'search' || this.IsCityHasOtherMarkers()) {
            this.CreateMapObjectIcons(MO_Icons);
            this.GetAndOrganizeMapObjects();
            
        }

        
    }
this.ExpandControl = function() {
    document.getElementById('im_ectrl').style.display = '';
    document.getElementById('im_switch').style.display = '';
    document.getElementById('im_cctrl').style.display = 'none';
    document.getElementById('im_switch2').style.display = 'none';
    document.getElementById('im_controlcont').style.width = '242px';
}
this.CollapseControl = function() {
    document.getElementById('im_ectrl').style.display = 'none';
    document.getElementById('im_switch').style.display = 'none';
    document.getElementById('im_cctrl').style.display = '';
    document.getElementById('im_switch2').style.display = '';
    document.getElementById('im_controlcont').style.width = '92px';
}

this.CreatePrintButton = function() {
    if (document.getElementById('im_print') != null)
        return;
    var controlDiv = document.createElement('DIV');
    controlDiv.setAttribute('id', 'im_print');
    controlDiv.className = 'noprint';
    controlDiv.innerHTML = '<div class="im_print" onclick="MapEngine.PrintContent()">Print</div>';
    this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);

}
this.PrintContent = function() {
    var DocumentContainer = document.getElementById('im_mapm');
    var WindowObject = window.open('', 'PrintWindow', 'width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
    WindowObject.document.writeln('<link rel="stylesheet" href="/styles/interactivemap.css" type="text/css" />');
    var preparedHTML = '<style type="text/css">.gmnoprint{ display:none !important;} .noprint{display:none !important;}</style>';
    preparedHTML += '<div id="im_mapm">' + DocumentContainer.innerHTML + '</div>'
    preparedHTML = preparedHTML.replace(/\/img_modules\//g, 'http://localhost:3317/img_modules/');
    WindowObject.document.writeln(preparedHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}
this.CreateLegend = function() {
    if (VersionIM == 1 || VersionIM == 4  || VersionIM == 5 || (VersionIM == 3 && Type == 'maplanding')) {
        if (this.LegendDiv != null)
            return;
        var controlDiv = document.createElement('DIV');
        controlDiv.setAttribute('id', 'im_legend');
        controlDiv.className = 'noprint';
        controlDiv.innerHTML = '<div class="bord">&nbsp;</div><div class="legend">' + im_phrases["more_than_1_same_building"] + '</div><div class="bord">&nbsp;</div>';
        this.LegendDiv = controlDiv;

        this.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
    }

}
this.CreateMissingAptAlert = function() {
    if (VersionIM == 1 && noLatLngAlert) {
        noLatLngAlert = false;

        var controlDiv = document.createElement('DIV');
        controlDiv.setAttribute('id', 'im_missingapt');
        controlDiv.className = 'noprint';
        controlDiv.innerHTML = '<div class="alert"><div onclick="javascript:document.getElementById(\'im_missingapt\').style.display=\'none\';" class="close">&nbsp;</div>' + im_phrases["missing_apt"] + '</div>';

        if (this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].getLength() > 0) {
            this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].removeAt(0);
        }
        this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].push(controlDiv);
    }
}
this.CreateFiltersSwitch = function() {
    if (this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].length == 0) {
        var filterSwitchCont = document.createElement('div');
        filterSwitchCont.className = 'filterSW';
        filterSwitchCont.innerHTML = '<div id="fil_c" onclick="MapEngine.HideFilterFS()">&nbsp;</div><div id="fil_e" onclick="MapEngine.ShowFilterFS()">&nbsp;</div>';
        this.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].push(filterSwitchCont);
    }

}
this.HideFilterFS = function() {
var mapParent = document.getElementById('im_mapm');
    var height = jQuery(window).height();
    var width = jQuery(window).width();
    jQuery('#fil_c').css('display', 'none');
    jQuery('#fil_e').css('display', 'block');
    jQuery('.newTD').css('display', 'none');
    mapParent.style.width = width + 'px';
    mapParent.style.height = height + 'px';
    mapParent.style.left = '0px';
    mapParent.style.top = '15px';
    MapEngine.MapContainer.style.width = width + 'px';
    MapEngine.MapContainer.style.height = height + 'px';
    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');

}
this.ShowFilterFS = function() {
var mapParent = document.getElementById('im_mapm');
    var height = jQuery(window).height();
    var width = jQuery(window).width();
    jQuery('#fil_e').css('display', 'none');
    jQuery('#fil_c').css('display', 'block');
    jQuery('.newTD').css('display', '');
    var paddingForFilters = jQuery('#sfcont').height();
    mapParent.style.width = width + 'px';
    mapParent.style.height = height - paddingForFilters + 'px';
    mapParent.style.left = '0px';
    mapParent.style.top = paddingForFilters + 15 + 'px';
    MapEngine.MapContainer.style.width = width + 'px';
    MapEngine.MapContainer.style.height = height - paddingForFilters + 'px';
    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');
}
this.MarkersCat = function(cat, checkbox, defineAgain) {
    var checked = checkbox.checked.toString();
    if (checked == "true") {
        if (checkbox.id != undefined) {
            document.getElementById(checkbox.id).checked = true;
            var inputs = document.getElementById('im_cctrl').getElementsByTagName('input');
            for (i = 0; i < inputs.length; ++i) {
                if (inputs[i].id == checkbox.id) {
                    inputs[i].checked = true;
                    break;
                }
            }
        }
        if (this.MapObjectsMarkers[cat] == null || typeof (defineAgain) != 'undefined') { //define new markers - defineAgain used in Krakow Tranposrt
            if (defineAgain) {
                try {
                    for (var type in this.MapObjectsMarkers) {
                        var markersToShow = this.MapObjectsMarkers[type];
                        for (var i = 0; i < markersToShow.length; i++) {
                            markersToShow[i].setMap(null);
                        }
                    }
                } catch (e) { }
            }
            var ObjectsInCat = this.MapObjects[cat];
            var tmpMark = new Array();
            for (var i = 0; i < ObjectsInCat.length; i++) {
                var mapobject = ObjectsInCat[i];
                var contentDescr = '<div style="overflow:hidden"><b>' + mapobject.TranslatedObjectName + '</b><br />' + mapobject.Text + '</div>';
                var zone = new Array();

                for (var p in mapobject.ZoneCoordinates) {
                    if (typeof (mapobject.ZoneCoordinates[p]) == 'object') {
                        var point = mapobject.ZoneCoordinates[p];
                        var myLatLng = new google.maps.LatLng(point[0], point[1]);
                        //this.bounds.extend(myLatLng);
                        zone.push(myLatLng);

                    }
                }
                if (zone.length > 0) {
                    html = '<div class="boxanchor"></div><div class="othertypes">' + contentDescr + '</div>';

                    tmpMark.push(this.createZone(this.GooogleMapObject, zone, mapobject.TranslatedObjectName, html, MO_ZoneColors[cat][0], MO_ZoneColors[cat][1]));
                } else {
                    if (mapobject.Lat != '' && mapobject.Lng != '') {
                        var myLatLng = new google.maps.LatLng(mapobject.Lat, mapobject.Lng);
                        // this.bounds.extend(myLatLng);
                        var target = '_blank';
                        if (VersionIM == 3 && Type == 'landmarklanding') {
                            target = '_parent';
                        }
                        var objectURL = '';
                        if (mapobject.URL != '') {
                            objectURL = '<br /><b><a href="' + mapobject.URL + '" target="' + target + '">' + im_phrases["click_for_details"] + '</a></b>'
                        }
                        var content = contentDescr + objectURL;
                        if (objectURL == '') {
                            html = '<div class="boxanchor"></div><div class="othertypes">' + content + '</div>';
                        }
                        else {
                            html = '<div class="boxanchor"></div><div class="othertypes" style="text-align:left;">' + content + '</div>';
                        }
                        var createdmarker = this.createMarker(this.GooogleMapObject, myLatLng, mapobject.TranslatedObjectName + '<br />', html, this.MapObjectIcons[cat], null);
                        if (showapts != '') {
                            this.bounds.extend(myLatLng);
                        }

                        for (var m = 0; m < this.ObjectIDsToShow.length; ++m) {
                            if (this.ObjectIDsToShow[m] == mapobject.Id) {
                                //createdmarker.icon = this.SingleAptIconSelected;
                                createdmarker.setAnimation(google.maps.Animation.BOUNCE);
                                this.bounds.extend(myLatLng);
                            }
                        }

                        tmpMark.push(createdmarker);
                    }
                }


            }
            this.MapObjectsMarkers[cat] = tmpMark;
        } else { //show previusly defined markers
            var markersToShow = this.MapObjectsMarkers[cat];
            for (var i = 0; i < markersToShow.length; i++) {
                var marker = markersToShow[i];
                if (marker.position == null) {
                    var zoneCoords = marker.latLngs.getArray();
                    for (var j = 0; j < zoneCoords.length; j++) {
                        var arr = zoneCoords[j];

                        var arr2 = arr.getArray();
                        //                        for (var l = 0; l < arr2.length; l++) {
                        //                            this.bounds.extend(arr2[l]);
                        //                        }


                    }
                } // else {
                //this.bounds.extend(marker.position);
                //}
                markersToShow[i].setMap(this.GooogleMapObject);
            }
        }
    } else {
        if (checkbox.id != undefined) {
            document.getElementById(checkbox.id).checked = false;
            var inputs = document.getElementById('im_cctrl').getElementsByTagName('input');
            for (i = 0; i < inputs.length; ++i) {
                if (inputs[i].id == checkbox.id) {
                    inputs[i].checked = false;
                    break;
                }
            }
        }
        var markersToShow = this.MapObjectsMarkers[cat];
        for (var i = 0; i < markersToShow.length; i++) {
            markersToShow[i].setMap(null);
        }
    }
    //this.GooogleMapObject.fitBounds(this.bounds);
}
this.CreateOverlay = function(iconurl, type, name) {

}
this.CreateNewSearchButton = function() {
    jQuery("#autocomplete").attr('disabled', true);
    jQuery("#tbDF").attr('disabled', true);
    jQuery("#tbDT").attr('disabled', true);
    jQuery(".inp>.gc").css('visibility', 'hidden');
    var dpImg = jQuery('.ui-datepicker-trigger');
    dpImg.attr('disabled', true);
    dpImg.addClass('qmark2');

    var button = jQuery('input[name="btnSearch"]')[0];
    var btnParent = jQuery(button).parent()[0];
    var newBut = document.createElement('div');
    jQuery(newBut).click(function() {
        var elemsToHide = jQuery('.tohide');
        for (var i = 0; i < elemsToHide.length; i++) {
            elemsToHide[i].style.display = 'none';
        }
        jQuery('input[name="btnSearch"]')[0].style.display = '';
        jQuery(".inp>.gc").css('visibility', 'visible');
        dpImg.removeAttr('disabled');
        dpImg.removeClass('qmark2');
        jQuery("#autocomplete").removeAttr('disabled')
        jQuery("#tbDF").removeAttr('disabled')
        jQuery("#tbDT").removeAttr('disabled')
        jQuery('input[name="tbNOP"]').removeAttr('disabled')
        jQuery('#tbDF').trigger('focus');
        jQuery('#tbDF').trigger('blur');
    });
    newBut.className = 'button button2 tohide';
    newBut.innerHTML = '<div>' + im_phrases["reset_dates"] + '</div>';
    button.style.display = 'none';
    btnParent.appendChild(newBut);
    jQuery('input[name="tbNOP"]').attr('disabled', true);
}
this.IsCityHasOtherMarkers = function() {
if (JSMAN_CITYID == 3 || JSMAN_CITYID == 24 || JSMAN_CITYID == 4 || JSMAN_CITYID == 2 || JSMAN_CITYID == 15 || JSMAN_CITYID == 9 || JSMAN_CITYID == 8) {
        return true;
    }
    else {
        return false;
    }
}
///// tooltip
this.ExtendGoogleMaps = function() {
    /**
    * @version 0.2
    * 0.2 initialize as hidden, thanks Rod
    * 0.1 first release
    */
    var TIPTOOL_VERSION = "0.2";



    /**
    * @constructor TipTool()
    * @extends OverlayView
    * @param {Map} map The map where the TipTool shall be overlayed
    * @param {LatLng} point The location where the TipTool shall be overlayed
    * @param {Object} opt_options Optional object.
    */
    function TipTool(map, point, opt_options) {
        this.opts = opt_options || {};
        this.point = point;
        this.setMap(map);
        this.map = map;
    };

    //subclass of OverlayView()
    TipTool.prototype = new google.maps.OverlayView();

    /**
    * onAdd(). Called internally by API when added on map.
    * to be called just once
    */
    TipTool.prototype.onAdd = function() {
        this.div_ = document.createElement('div');
        this.div_.style.position = "absolute";
        this.div_.style.overflow = "hidden";
        this.zIndex = this.opts.zIndex || 0;
        this.div_.className = this.opts.cssClass || this.opts.className || 'tiptool';
        this.div_.innerHTML = this.opts.html || "";
        google.maps.event.addDomListener(this.div_, "click", function(event) {
            google.maps.event.trigger(me, "click", event);
        });
        var panes = this.getPanes();
        var paneId = this.opts.pane || "floatPane";
        panes[paneId].appendChild(this.div_);
        this.opacity = this.opts.opacity * 1 || 1;
        this.div_.style.filter = 'alpha(opacity:' + this.opacity * 100 + ')';
        this.div_.style.opacity = this.opacity;
        this.div_.style.display = "none";
    }

    /**
    * called internally by API when map moves.
    */
    TipTool.prototype.draw = function() {
        var pixPoint = this.getProjection().fromLatLngToDivPixel(this.point);
        this.div_.style.left = pixPoint.x + 30 + 'px';
        this.div_.style.top = pixPoint.y - 20 + 'px';
        var SEx = pixPoint.x + this.div_.offsetWidth;
        var SEy = pixPoint.y + this.div_.offsetHeight;
        var pixSE = new google.maps.Point(SEx, SEy);
        this.opts.SE = this.getProjection().fromDivPixelToLatLng(pixSE);
        this.opts.point = this.point;
    };

    /**
    * Sets latLng position of tooltip
    * @param {LatLng} point The location where the TipTool shall be moved
    */

    TipTool.prototype.setPosition = function(pint) {
        if (!this.div_) return false;
        this.point = pint;
        this.draw();
        return true
    };
    /**
    * Removes the div from DOM
    * @returns true if success, false if the div was not found
    */
    TipTool.prototype.onRemove = function() {
        if (!this.div_) return false;
        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
        return true;
    };
    /**
    * Sets the div display:none
    * @returns true if success, false if the div was not found
    */
    TipTool.prototype.hide = function() {
        if (!this.div_) return false;
        this.div_.style.display = "none";
        return true;
    };
    /**
    * Sets the div display: block
    * @returns true if success, false if the div was not found
    */
    TipTool.prototype.show = function() {
        if (!this.div_) return false;
        this.div_.style.display = "block";
        return true;
    };

    /**
    * Sets innerHTML of the div
    * @param {String}
    * @returns true if success, false if the div was not found
    */
    TipTool.prototype.setContent = function(html) {
        if (!this.div_) return false;
        this.div_.innerHTML = html;

        return true;
    };

    /**
    * Copies properties of given options object to internal this.opts
    * @param optional object
    * @returns the updated internal this.opts object
    */
    TipTool.prototype.props = function(options) {  // needs work for more properties
        var opts = options || {};
        for (var prop in opts) {
            this.opts[prop] = opts[prop];
        }
        return this.opts;
    };
    /**
    * @returns The location of the div
    * @type LatLng object (null if the div was not found)
    */
    TipTool.prototype.getPosition = function() {
        if (!this.div_) return null;
        return this.bounds_.getCenter();
    };
    /**
    * @returns True if TipTool is in viewport
    * @type boolean
    */
    TipTool.prototype.isVisible = function() {
        var bounds = this.map.getBounds();
        var visible = (bounds.contains(this.opts.point) && bounds.contains(this.opts.SE));
        return visible;
    };
    /**
    * pans map to bring TipTool in viewport
    */
    TipTool.prototype.bringVisible = function() {
        if (this.isVisible()) {
            this.map.setCenter(this.map.getCenter());
        } else {
            this.map.panTo(this.opts.point);
        }
    };



    /**
    * attachTipTool() binds TipTool to a Marker
    * Creates an InfoWindow instance if it does not exist already
    * @extends Marker
    * @param InfoWindow options
    * @author Esa 2009
    */

    google.maps.Marker.prototype.attachTipTool = function(html, opt_options) {
        var map_ = this.getMap();
        var position = this.getPosition();
        map_.tiptool_ = map_.tiptool_ || new TipTool(map_, position, opt_options);  // todo
        google.maps.event.addListener(this, 'mouseover', function() {
            //debug(this.FromLegend);
            if (this.FromLegend) {
                map_.tiptool_.setPosition(position);
                //map_.tiptool_.setContent(html);
                map_.tiptool_.setContent(this.tooltip2);
                map_.tiptool_.show();
                clearTimeout(map_.tiptool_.timer);
            }
        });
        google.maps.event.addListener(this, 'mouseout', function() {
            //debug(this.FromLegend);
            if (this.FromLegend) {
                clearTimeout(map_.tiptool_.timer);
                map_.tiptool_.timer = setTimeout(function() {
                    map_.tiptool_.hide();
                }, 1);
            }
        });
    }

    /**
    * accessTipTool()
    * @extends Map
    * @returns {TipTool} reference to the TipTool object instance
    */
    google.maps.Marker.prototype.FromLegend = false;
    google.maps.Map.prototype.accessTipTool = function() {
        var ret = this.tiptool_ || {};
        return ret;
    }
    google.maps.Polygon.prototype.FromLegend = false;

    google.maps.Polygon.prototype.attachTipTool = function(html, opt_options) {
        var map_ = this.getMap();
        var paths = this.getPaths().getArray()[0].getArray();
        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < paths.length; i++) {
            bounds.extend(paths[i]);
        }
        var position = bounds.getCenter();
        map_.tiptool_ = map_.tiptool_ || new TipTool(map_, position, opt_options);  // todo
        google.maps.event.addListener(this, 'mouseover', function() {
            if (this.FromLegend) {
                map_.tiptool_.setPosition(position);
                map_.tiptool_.setContent(html);
                map_.tiptool_.show();
                clearTimeout(map_.tiptool_.timer);
            }
        });
        google.maps.event.addListener(this, 'mouseout', function() {
            if (this.FromLegend) {
                clearTimeout(map_.tiptool_.timer);
                map_.tiptool_.timer = setTimeout(function() {
                    map_.tiptool_.hide();
                }, 1);
            }
        });
    }
}
this.ExtendGoogleMaps();
//end of InteractiveMap class
}
function Slide(direction) {    
    var MapASCXinner = document.getElementById('im_map');
    var MapASCX = document.getElementById('im_mapm');
    var Footer = document.getElementById('modFooter');
    if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
        Footer.style.position = 'absolute';    
    }//alert(document.getElementById('sffilter').childNodes.length);
    if (direction == 'left') {
        if (listWith1AptAndNoFilter) {
            jQuery('#modSearch3').css('display', 'none'); 
            jQuery('#modSearchFilter').css('display', 'none');
            jQuery('#sfcont').css('display', 'none');
            jQuery('#search3Content').css('display', 'none');
        }
		jQuery('#SimilarApartments').css('display', 'none');
        MapASCX.style.display = '';
        MapASCX.style.visibility = 'visible'; MapASCX.style.width = ""; MapASCX.style.height = "";
        MapASCX.style.overflow = '';
        MapASCXinner.style.visibility = 'visible';
        MapASCXinner.style.width = MapEngine.Width + 'px';
        MapASCXinner.style.height = MapEngine.Height + 'px';
        var pos = GetPos(MapASCX);
        if (document.getElementById('PW').style.display != 'none') {
            pos.y = pos.y - 500;// 500px is PW div height
        }
        var footerPos = GetPos(Footer);
       // if(VersionIM != 4)
        MapASCX.style.position = 'absolute';

        if (VersionIM == 4  || VersionIM == 5) {
            var el = MapASCX.nextSibling;
            while (el) {
                if (typeof (el.id) != 'undefined' && el.id != "") {
                    document.getElementById(el.id).style.marginTop = MapEngine.Height + 60 + 'px';
                    break;
                }
                el = el.nextSibling;
            }
            document.getElementById('im_maph_but').style.visibility = 'visible';  
        }     
        
        //var PW_loading = GetPos(document.getElementById('PW');
        if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
            Footer.style.marginTop = MapEngine.Height + 60 + 'px';
        }
        MapASCX.style.left = screen.width + 'px';
        
        MapASCX.style.top = pos.y + 'px';
        document.getElementById('im_maph').style.visibility = 'visible';

        mint.fx.Move(MapASCX, pos.x, pos.y, 10, 200);
        //mint.fx.Fade(MapASCX, 100, 10, 100);
        MapEngine.MapVisible = true;


        google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');     
    } else {
        if (listWith1AptAndNoFilter) {
                jQuery('#modSearch3').css('display', 'block'); 
                jQuery('#modSearchFilter').css('display', 'none');
                jQuery('#search3Content').css('display', 'block');
            }      
        if (VersionIM == 4  || VersionIM == 5) {
            var el = MapASCX.nextSibling;
            while (el) {
                if (typeof (el.id) != 'undefined' && el.id != "") {
                    document.getElementById(el.id).style.marginTop = '0px';
                    break;
                }
                el = el.nextSibling;
            }
            document.getElementById('im_maph_but').style.visibility = 'hidden';
        } 
        if (navigator.appName.indexOf("Microsoft") != -1) {
            mint.fx.Move(MapASCX, screen.width, 590, 10, 200, null, function() { MapASCX.style.left = ''; MapASCX.style.top = ''; MapASCX.style.position = ''; MapASCXinner.style.visibility = 'hidden'; MapASCXinner.style.width = '1px'; MapASCXinner.style.height = '1px'; MapASCX.style.visibility = 'hidden'; MapASCX.style.overflow = 'hidden'; MapASCX.style.width = "1px"; MapASCX.style.height = "1px"; Footer.style.marginTop = '0px'; google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize'); });
        }
        else {
            mint.fx.Move(MapASCX, screen.width, MapASCX.style.top.replace('px', ''), 10, 200, null, function() { MapASCX.style.left = ''; MapASCX.style.top = ''; MapASCXinner.style.visibility = 'hidden'; MapASCXinner.style.width = '1px'; MapASCXinner.style.height = '1px'; MapASCX.style.position = ''; MapASCX.style.visibility = 'hidden'; MapASCX.style.overflow = 'hidden'; MapASCX.style.width = "1px"; MapASCX.style.height = "1px"; Footer.style.marginTop = '0px'; google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize'); });
        }
        jQuery('#SimilarApartments').css('display', 'block');
            
    MapEngine.MapVisible = false;
    }

}
function im_ExitFullScreen() {
    if (VersionIM == 2 || VersionIM == 3 || VersionIM == 4  || VersionIM == 5) {
        im_ExitFullScreen2();
        return;
    }
    MapEngine.GooogleMapObject.setOptions({ scrollwheel: false });
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion <= 6) {

            document.getElementById('sfcont').style.width = '';
            document.getElementById('modFooter').style.display = 'block';
            document.getElementById('modSearchFilter').style.margin = '-199px 0px 2px 0px';
            document.getElementById('modSearchFilter').style.position = 'relative';
            document.getElementById('modSearchFilter').style.left = '8px';
            document.getElementById('sffilter').style.top = '-40px';
        }
    }    
    if (MapEngine.LegendDiv != null) {
        MapEngine.LegendDiv.style.display = MapEngine.FullScreenVar["MP_legend"];
    }
    try {
    // elem from search filter, number of apts
        document.getElementById("tanb").style.display = 'none';
    } catch (excs) { }
    if (!listWith1AptAndNoFilter) {
        MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.TOP_CENTER].removeAt(0);
        jQuery('.newTD')[0].style.display = '';
        jQuery(".newTD")[0].style.visibility = 'visible';
        document.getElementById('sf_icons').className = 'fcol2';  
    }
    jQuery('#sfrbe').css('clear', 'none');

    document.body.style.overflow = 'auto';
    document.getElementById('sfcro').style.display = 'none';
    document.body.style.visibility = 'visible';
    //document.getElementById('HiddenAptsPlaceHolder').style.display = MapEngine.FullScreenVar["MP_HA"];
    jQuery('#search3Content').append(jQuery('#aaSearch'));

    var filters = document.getElementById('sfcont');
    filters.style.position = '';

    document.getElementById('tanb').className = '';
    document.getElementById('im_maph').style.display = '';
    filters.className = '';
    filters.style.backgroundColor = MapEngine.FullScreenVar["MP_BGC"];
    filters.style.height = MapEngine.FullScreenVar["MP_FH"];
    //jQuery('#modSearch3>.header')[0].style.display = '';
    //jQuery('#modSearchFilter>.header')[0].style.display = ''; 
    
    var mapParent = document.getElementById('im_mapm');
    jQuery(mapParent).css('border-top', '0');
    mapParent.style.position = 'absolute';
    mapParent.style.width = MapEngine.Width + 'px';
    mapParent.style.height = MapEngine.Height + 'px';
    mapParent.style.left = MapEngine.FullScreenVar["MP_left"];
    mapParent.style.top = MapEngine.FullScreenVar["MP_top"];
    document.getElementById('im_maph').style.visibility = 'visible';
    MapEngine.MapContainer.style.width = MapEngine.Width + 'px';
    MapEngine.MapContainer.style.height = MapEngine.Height + 'px';
    MapEngine.IsFullScreen = false;
    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');
    MapEngine.CreateFullScreenButton();
    //MapEngine.GooogleMapObject.fitBounds(MapEngine.bounds);
    createCookie('im_info', '1')

    if (!listWith1AptAndNoFilter) {
        MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_TOP].removeAt(0);
        jQuery('#im_mapm').css('marginLeft', '15px');
        jQuery('#im_mapm').css('marginTop', '0px');
    }
}
function im_FullScreen() {
    if (VersionIM == 2 || VersionIM == 3 || VersionIM == 4  || VersionIM == 5) {
        im_FullScreen2();
        return;
    }
    MapEngine.GooogleMapObject.setOptions({ scrollwheel: true });
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion <= 6) {

            document.getElementById('sfcont').style.width = document.body.offsetWidth;
            document.getElementById('modFooter').style.display = 'none';
            document.getElementById('modSearchFilter').style.margin = '-289px 0px 2px -8px';
            document.getElementById('modSearchFilter').style.position = 'absolute';
            document.getElementById('sffilter').style.top = '0px';
        }
    }    
    if (MapEngine.LegendDiv != null) {
        MapEngine.FullScreenVar["MP_legend"] = MapEngine.LegendDiv.style.display;
        MapEngine.LegendDiv.style.display = 'none';
    }
    try {
        // elem from search filter, number of apts
        document.getElementById("tanb").style.display = '';
    } catch (excs) { }
    var hiddenAptsDiv = document.getElementById('HiddenAptsPlaceHolder');
    if (hiddenAptsDiv == null || (hiddenAptsDiv.style.display == 'none')) {
        jQuery('#sfrbe').css('clear', 'left');
    }

    if (!listWith1AptAndNoFilter) {
        MapEngine.CreateFiltersSwitch();
        document.getElementById('sfcro').style.display = '';
        MapEngine.FullScreenVar["MP_HA"] = document.getElementById('HiddenAptsPlaceHolder').style.display;
    }
        
    //document.getElementById('HiddenAptsPlaceHolder').style.display = 'none';
    var mapParent = document.getElementById('im_mapm');
    mapParent.style.display = '';
    var Footer = document.getElementById('modFooter');
    var pos = GetPos(mapParent);
    jQuery(mapParent).css('border-top', '2px solid #005197');
    mapParent.style.position = 'absolute';
    Footer.style.marginTop = MapEngine.Height + 60 + 'px';
    
    //mint.fx.Fade(MapASCX, 100, 10, 100);
    MapEngine.MapVisible = true;

    MapEngine.FullScreenVar["MP_left"] = pos.x + 'px'; //mapParent.style.left;
    if (document.getElementById('PW').style.display != 'none') {
        pos.y = pos.y - 500; // 500px is PW div height
    }
    MapEngine.FullScreenVar["MP_top"] = pos.y+'px'; //mapParent.style.top;
    document.body.style.visibility = 'hidden';
    if (!listWith1AptAndNoFilter) {
        jQuery(".newTD")[0].style.visibility = 'hidden';
    }

    var filters = document.getElementById('sfcont');
    jQuery(filters).prepend(jQuery('#aaSearch'));
    filters.style.visibility = 'visible';
    filters.style.position = 'absolute';
    filters.style.top = '0px';
    filters.style.left = '0px';
    //jQuery('#modSearch3>.header')[0].style.display = 'none';
    //jQuery('#modSearchFilter>.header')[0].style.display = 'none';
    //MapEngine.FullScreenVar["MP_bg"] = jQuery(".newTD")[0].style.backgroundColor;
    //jQuery(".newTD")[0].style.backgroundColor = '#FFF';
    if (!listWith1AptAndNoFilter) {
        document.getElementById('sf_icons').className = 'fcol';
    }
    document.getElementById('tanb').className = 'tanb';
    document.getElementById('im_maph').style.display = 'none';
    var sfcont = document.getElementById('sfcont');
    sfcont.className = 'bggrad';
    MapEngine.FullScreenVar["MP_BGC"] = sfcont.style.backgroundColor;
    sfcont.style.backgroundColor = '#FFF';
    MapEngine.FullScreenVar["MP_FH"] = sfcont.style.height;
    sfcont.style.height = '';
    scroll(0, 0);
    document.body.style.overflow = 'hidden';
    var height = jQuery(window).height();
    var width = jQuery(window).width();
    mapParent.style.visibility = 'visible';
    mapParent.style.width = width + 'px';
    var paddingForFilters = jQuery('#sfcont').height();
    mapParent.style.height = height - paddingForFilters+ 'px';
    mapParent.style.left = '0px';
    mapParent.style.top = paddingForFilters + 15 + 'px';
    MapEngine.MapContainer.style.width = width + 'px';
    MapEngine.MapContainer.style.height = height - paddingForFilters + 'px';
    MapEngine.IsFullScreen = true;

    if (!listWith1AptAndNoFilter) {
        jQuery('#im_mapm').css('marginLeft', '0px');
        jQuery('#im_mapm').css('marginTop', '-15px');
    }     
       
    MapEngine.CreateNormalScreenButton();
    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');
    createCookie('im_info', '2')
    //MapEngine.GooogleMapObject.fitBounds(MapEngine.bounds);
}


function im_FullScreen2() {
    MapEngine.GooogleMapObject.setOptions({ scrollwheel: true });
    if (document.getElementById('im_controlcont') != null)
        document.getElementById('im_controlcont').style.display = 'block';

    var mapParent = document.getElementById('im_mapm');
    if (VersionIM == 3) {
        mapParent.style.marginLeft = '0px';

        if (document.getElementById('LandmListContainer') != null) {
            document.getElementById('LandmListContainer').style.display = 'none';
        }
    }
    mapParent.style.display = '';
    var Footer = document.getElementById('modFooter');
    var pos = GetPos(mapParent);
    jQuery(mapParent).css('border-top', '2px solid #005197');
    mapParent.style.position = 'absolute';
    //Footer.style.marginTop = MapEngine.Height + 60 + 'px';

    MapEngine.MapVisible = true;


    MapEngine.FullScreenVar["MP_left"] = pos.x + 'px'; //mapParent.style.left;
    if (document.getElementById('PW').style.display != 'none') {
        pos.y = pos.y - 500; // 500px is PW div height
    }
    MapEngine.FullScreenVar["MP_top"] = pos.y +'px'; //mapParent.style.top;
    document.body.style.visibility = 'hidden';

    document.getElementById('im_maph').style.display = 'none';

    scroll(0, 0);
    document.body.style.overflow = 'hidden';
    var height = jQuery(window).height();
    var width = jQuery(window).width();
    mapParent.style.visibility = 'visible';
    mapParent.style.width = width + 'px';
    var paddingForFilters = jQuery('#sfcont').height();
    paddingForFilters = 0;
    mapParent.style.height = height - paddingForFilters + 'px';
    mapParent.style.left = '0px';
    mapParent.style.top = '0px';
    MapEngine.MapContainer.style.width = width + 'px';
    MapEngine.MapContainer.style.height = height - paddingForFilters + 'px';
    MapEngine.IsFullScreen = true;
    MapEngine.CreateNormalScreenButton();

    var mapm = jQuery('#im_mapm');
    if (VersionIM == 4) {
        mapm.css('marginLeft', '0px');
    }
    else if (VersionIM == 5) {
        mapm.css('marginLeft', '-10px');
        mapm.css('marginTop', '-11px');
        jQuery('#modLandingGallery .nav').css('display', 'none');
        jQuery('#modLandingPrices').css('display', 'none');
    }

    if (mapleft != '') {
        mapm.css('marginLeft', '0px');
    }
    if (maptop != '') {
        mapm.css('marginTop', '0px');
    }  

    var controlDiv = document.createElement('DIV');
    controlDiv.setAttribute('id', 'sfcro');
    google.maps.event.addDomListener(controlDiv, 'click', function() {
        im_ExitFullScreen2();
    });    
    MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_TOP].push(controlDiv);

    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');

    if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
        MapEngine.GooogleMapObject.fitBounds(MapEngine.bounds);
    }
}
function im_ExitFullScreen2() {
    MapEngine.GooogleMapObject.setOptions({ scrollwheel: false });
    if (VersionIM == 2) {
        for (var type in MapEngine.MapObjects) {
            var a = new Object();
            a.checked = false;
            MapEngine.MarkersCat(type, a);
        }
        this.LegendDiv = null;
    }
    

    document.body.style.overflow = 'auto';
    

    document.body.style.visibility = 'visible';

    if (document.getElementById('im_controlcont') != null && VersionIM == 2)
        document.getElementById('im_controlcont').style.display = 'none';

    var mapParent = document.getElementById('im_mapm');
    if (VersionIM == 3) {
        mapParent.style.marginLeft = '15px';
    }
    jQuery(mapParent).css('border-top', '0');
    if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
        mapParent.style.position = 'static';
        document.getElementById('im_maph').style.display = 'none';
    }
    else if (VersionIM == 4) {
        jQuery(mapParent).css('marginLeft', '15px');
        document.getElementById('im_maph').style.display = 'block';       
    }
    else if (VersionIM == 5) {
        jQuery(mapParent).css('marginLeft', '10px');
        jQuery(mapParent).css('marginTop', '0px');
        jQuery(mapParent).css('borderTop', '1px solid #CCCCCC');
        document.getElementById('im_maph').style.display = 'none';
        jQuery('#modLandingGallery .nav').css('display', 'block');   
        jQuery(mapParent).css('position', 'static');
    }

    if (mapleft != '') {
        document.getElementById('im_mapm').style.marginLeft = mapleft + 'px';
    }
    if (maptop != '') {
        document.getElementById('im_mapm').style.marginTop = maptop + 'px';
    }       
         
    mapParent.style.display = 'block';
    mapParent.style.width = MapEngine.Width + 'px';
    mapParent.style.height = MapEngine.Height + 'px';
    mapParent.style.left = MapEngine.FullScreenVar["MP_left"];
    mapParent.style.top = MapEngine.FullScreenVar["MP_top"];

    MapEngine.MapContainer.style.width = MapEngine.Width + 'px';
    MapEngine.MapContainer.style.height = MapEngine.Height + 'px';
    MapEngine.IsFullScreen = false;

    if (VersionIM == 2) {
        MapEngine.BuildMarkres(AptID);
        MapEngine.GooogleMapObject.zoom = 12;
        MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.BOTTOM_LEFT].removeAt(0);
    }
    else if (VersionIM == 3 || VersionIM == 4  || VersionIM == 5) {
        MapEngine.CreateFullScreenButton();

        if (document.getElementById('LandmListContainer') != null) {
            document.getElementById('LandmListContainer').style.display = 'block';
        }
    }
        
    google.maps.event.trigger(MapEngine.GooogleMapObject, 'resize');

    MapEngine.GooogleMapObject.controls[google.maps.ControlPosition.RIGHT_TOP].removeAt(0);

    if (VersionIM == 1 || VersionIM == 2 || VersionIM == 3) {
        MapEngine.GooogleMapObject.fitBounds(MapEngine.bounds);
    }
}
function GuideMouseOver(aptid) {    
    var aptname = '';
    for (var p in MapEngine.OrganizedApartments) {
        var info = MapEngine.OrganizedApartments[p]; // info-> array of ListElement objects
        for (var i = 0; i < info.length; i++) {
            var currElem = info[i].InfoForMap.CurrentDetailsIdex;
            if (info[i].ID == aptid) {
                aptname = info[i].InfoForMap.AptNames[currElem];
                break;
            }
        } 
    }    
    for (var i = 0; i < MapEngine.MarkersOnMap.length; i++) {
        for (var j = 0; j < MapEngine.MarkersOnMap[i].apartmentIDs.length; j++) {
            if (MapEngine.MarkersOnMap[i].apartmentIDs[j] == aptid) {
                 var marker = MapEngine.MarkersOnMap[i];
                 marker.tooltip2 = aptname;
                 marker.FromLegend = true;
                 google.maps.event.trigger(marker, "mouseover");                 
                 break;      
            }
        }      
    }
}
function GuideMouseOut(aptid) {
    for (var i = 0; i < MapEngine.MarkersOnMap.length; i++) {
        for (var j = 0; j < MapEngine.MarkersOnMap[i].apartmentIDs.length; j++) {
            if (MapEngine.MarkersOnMap[i].apartmentIDs[j] == aptid) {
                var marker = MapEngine.MarkersOnMap[i];


                google.maps.event.trigger(marker, "mouseout");
                marker.FromLegend = false;
                break;
            }
        }
    }
}

jQuery(document).ready(function() {
    jQuery(".infoBox").live("mouseenter", function() {
        if (MapEngine.IsFullScreen) {
            MapEngine.GooogleMapObject.setOptions({ scrollwheel: false });
        }
    })
    jQuery(".infoBox").live("mouseleave", function() {
        if (MapEngine.IsFullScreen) {
            MapEngine.GooogleMapObject.setOptions({ scrollwheel: true });
        }
    });
});

//--InfoBox

function InfoBox(opt_opts) {

    opt_opts = opt_opts || {};

    google.maps.OverlayView.apply(this, arguments);

    // Standard options (in common with google.maps.InfoWindow):
    //
    this.content_ = opt_opts.content || "";
    this.disableAutoPan_ = opt_opts.disableAutoPan || false;
    this.maxWidth_ = opt_opts.maxWidth || 0;
    this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
    this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
    this.zIndex_ = opt_opts.zIndex || null;

    // Additional options (unique to InfoBox):
    //
    this.boxClass_ = opt_opts.boxClass || "infoBox";
    this.boxStyle_ = opt_opts.boxStyle || {};
    this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
    this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
    if (opt_opts.closeBoxURL === "") {
        this.closeBoxURL_ = "";
    }
    this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
    this.isHidden_ = opt_opts.isHidden || false;
    this.alignBottom_ = opt_opts.alignBottom || false;
    this.pane_ = opt_opts.pane || "floatPane";
    this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;

    this.div_ = null;
    this.closeListener_ = null;
    this.eventListener1_ = null;
    this.eventListener2_ = null;
    this.eventListener3_ = null;
    this.moveListener_ = null;
    this.contextListener_ = null;
    this.fixedWidthSet_ = null;
}

/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();

/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function() {

    var bw;
    var me = this;

    // This handler prevents an event in the InfoBox from being passed on to the map.
    //
    var cancelHandler = function(e) {
        e.cancelBubble = true;

        if (e.stopPropagation) {

            e.stopPropagation();
        }
    };

    // This handler ignores the current event in the InfoBox and conditionally prevents
    // the event from being passed on to the map. It is used for the contextmenu event.
    //
    var ignoreHandler = function(e) {

        e.returnValue = false;

        if (e.preventDefault) {

            e.preventDefault();
        }

        if (!me.enableEventPropagation_) {

            cancelHandler(e);
        }
    };

    if (!this.div_) {

        this.div_ = document.createElement("div");

        this.setBoxStyle_();

        if (typeof this.content_.nodeType === "undefined") {
            this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
        } else {
            this.div_.innerHTML = this.getCloseBoxImg_();
            this.div_.appendChild(this.content_);
        }

        // Add the InfoBox DIV to the DOM
        this.getPanes()[this.pane_].appendChild(this.div_);

        this.addClickHandler_();

        if (this.div_.style.width) {

            this.fixedWidthSet_ = true;

        } else {

            if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {

                this.div_.style.width = this.maxWidth_;
                this.div_.style.overflow = "auto";
                this.fixedWidthSet_ = true;

            } else { // The following code is needed to overcome problems with MSIE

                bw = this.getBoxWidths_();

                this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
                this.fixedWidthSet_ = false;
            }
        }

        this.panBox_(this.disableAutoPan_);

        if (!this.enableEventPropagation_) {

            // Cancel event propagation.
            //
            this.eventListener1_ = google.maps.event.addDomListener(this.div_, "mousedown", cancelHandler);
            this.eventListener2_ = google.maps.event.addDomListener(this.div_, "click", cancelHandler);
            this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", cancelHandler);
        }

        this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);

        /**
        * This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
        * @name InfoBox#domready
        * @event
        */
        google.maps.event.trigger(this, "domready");
    }
};

/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function() {

    var img = "";

    if (this.closeBoxURL_ !== "") {
        var cwidth = parseInt(this.div_.style.width.substring(0, this.div_.style.width.indexOf("px"))) - 9;
        img = '<div style="width:' + cwidth + 'px; background:white; height:15px;margin-left:9px;border-right:solid 1px black;border-top:solid 1px black;">';
        img += "<img";
        img += " src='" + this.closeBoxURL_ + "'";
        img += " align=right"; // Do this because Opera chokes on style='float: right;'
        img += " style='";
        img += " position: relative;"; // Required by MSIE
        img += " cursor: pointer;";
        img += " margin: " + this.closeBoxMargin_ + ";";
        img += "'>";
        img += "</div>";
    }

    return img;
};

/**
* Adds the click handler to the InfoBox close box.
* @private
*/

InfoBox.prototype.addClickHandler_ = function() {

    var closeBox;

    if (this.closeBoxURL_ !== "") {

        closeBox = this.div_.firstChild;
        this.closeListener_ = google.maps.event.addDomListener(closeBox, 'click', this.getCloseClickHandler_());

    } else {

        this.closeListener_ = null;
    }
};

/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function() {

    var me = this;

    return function(e) {

        // 1.0.3 fix: Always prevent propagation of a close box click to the map:
        e.cancelBubble = true;

        if (e.stopPropagation) {

            e.stopPropagation();
        }

        me.close();

        /**
        * This event is fired when the InfoBox's close box is clicked.
        * @name InfoBox#closeclick
        * @event
        */
        google.maps.event.trigger(me, "closeclick");
    };
};

/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function(disablePan) {

    var map;
    var bounds;
    var xOffset = 0, yOffset = 0;

    if (!disablePan) {

        map = this.getMap();

        if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama

            if (!map.getBounds().contains(this.position_)) {
                // Marker not in visible area of map, so set center
                // of map to the marker position first.
                map.setCenter(this.position_);
            }

            bounds = map.getBounds();

            var mapDiv = map.getDiv();
            var mapWidth = mapDiv.offsetWidth;
            var mapHeight = mapDiv.offsetHeight;
            var iwOffsetX = this.pixelOffset_.width;
            var iwOffsetY = this.pixelOffset_.height;
            var iwWidth = this.div_.offsetWidth;
            var iwHeight = this.div_.offsetHeight;
            var padX = this.infoBoxClearance_.width;
            var padY = this.infoBoxClearance_.height;
            var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);

            if (pixPosition.x < (-iwOffsetX + padX)) {
                xOffset = pixPosition.x + iwOffsetX - padX;
            } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
                xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
            }
            if (this.alignBottom_) {
                if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
                    yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
                } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
                    yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
                }
            } else {
                if (pixPosition.y < (-iwOffsetY + padY)) {
                    yOffset = pixPosition.y + iwOffsetY - padY;
                } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
                    yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
                }
            }

            if (!(xOffset === 0 && yOffset === 0)) {

                // Move the map to the shifted center.
                //
                var c = map.getCenter();
                map.panBy(xOffset, yOffset);
            }
        }
    }
};

/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function() {

    var i, boxStyle;

    if (this.div_) {

        // Apply style values from the style sheet defined in the boxClass parameter:
        this.div_.className = this.boxClass_;

        // Clear existing inline style values:
        this.div_.style.cssText = "";

        // Apply style values defined in the boxStyle parameter:
        boxStyle = this.boxStyle_;
        for (i in boxStyle) {

            if (boxStyle.hasOwnProperty(i)) {

                this.div_.style[i] = boxStyle[i];
            }
        }

        // Fix up opacity style for benefit of MSIE:
        //
        if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {

            this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
        }

        // Apply required styles:
        //
        this.div_.style.position = "absolute";
        this.div_.style.visibility = 'hidden';
        if (this.zIndex_ !== null) {

            this.div_.style.zIndex = this.zIndex_;
        }
    }
};

/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function() {

    var computedStyle;
    var bw = { top: 0, bottom: 0, left: 0, right: 0 };
    var box = this.div_;

    if (document.defaultView && document.defaultView.getComputedStyle) {

        computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");

        if (computedStyle) {

            // The computed styles are always in pixel units (good!)
            bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
            bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
            bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
            bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
        }

    } else if (document.documentElement.currentStyle) { // MSIE

        if (box.currentStyle) {

            // The current styles may not be in pixel units, but assume they are (bad!)
            bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
            bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
            bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
            bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
        }
    }

    return bw;
};

/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function() {

    if (this.div_) {

        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
    }
};

/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function() {

    this.createInfoBoxDiv_();

    var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);

    this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";

    if (this.alignBottom_) {
        this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
    } else {
        this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
    }

    if (this.isHidden_) {

        this.div_.style.visibility = 'hidden';

    } else {

        this.div_.style.visibility = "visible";
    }
};

/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
*  <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
*  properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
*  is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function(opt_opts) {
    if (typeof opt_opts.boxClass !== "undefined") { // Must be first

        this.boxClass_ = opt_opts.boxClass;
        this.setBoxStyle_();
    }
    if (typeof opt_opts.boxStyle !== "undefined") { // Must be second

        this.boxStyle_ = opt_opts.boxStyle;
        this.setBoxStyle_();
    }
    if (typeof opt_opts.content !== "undefined") {

        this.setContent(opt_opts.content);
    }
    if (typeof opt_opts.disableAutoPan !== "undefined") {

        this.disableAutoPan_ = opt_opts.disableAutoPan;
    }
    if (typeof opt_opts.maxWidth !== "undefined") {

        this.maxWidth_ = opt_opts.maxWidth;
    }
    if (typeof opt_opts.pixelOffset !== "undefined") {

        this.pixelOffset_ = opt_opts.pixelOffset;
    }
    if (typeof opt_opts.position !== "undefined") {

        this.setPosition(opt_opts.position);
    }
    if (typeof opt_opts.zIndex !== "undefined") {

        this.setZIndex(opt_opts.zIndex);
    }
    if (typeof opt_opts.closeBoxMargin !== "undefined") {

        this.closeBoxMargin_ = opt_opts.closeBoxMargin;
    }
    if (typeof opt_opts.closeBoxURL !== "undefined") {

        this.closeBoxURL_ = opt_opts.closeBoxURL;
    }
    if (typeof opt_opts.infoBoxClearance !== "undefined") {

        this.infoBoxClearance_ = opt_opts.infoBoxClearance;
    }
    if (typeof opt_opts.isHidden !== "undefined") {

        this.isHidden_ = opt_opts.isHidden;
    }
    if (typeof opt_opts.enableEventPropagation !== "undefined") {

        this.enableEventPropagation_ = opt_opts.enableEventPropagation;
    }

    if (this.div_) {

        this.draw();
    }
};

/**
* Sets the content of the InfoBox.
*  The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function(content) {
    this.content_ = content;

    if (this.div_) {

        if (this.closeListener_) {

            google.maps.event.removeListener(this.closeListener_);
            this.closeListener_ = null;
        }

        // Odd code required to make things work with MSIE.
        //
        if (!this.fixedWidthSet_) {

            this.div_.style.width = "";
        }

        if (typeof content.nodeType === "undefined") {
            this.div_.innerHTML = this.getCloseBoxImg_() + content;
        } else {
            this.div_.innerHTML = this.getCloseBoxImg_();
            this.div_.appendChild(content);
        }

        // Perverse code required to make things work with MSIE.
        // (Ensures the close box does, in fact, float to the right.)
        //
        if (!this.fixedWidthSet_) {

            this.div_.style.width = this.div_.offsetWidth + "px";
            this.div_.innerHTML = this.getCloseBoxImg_() + content;
        }

        this.addClickHandler_();
    }

    /**
    * This event is fired when the content of the InfoBox changes.
    * @name InfoBox#content_changed
    * @event
    */
    google.maps.event.trigger(this, "content_changed");
};

/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function(latlng) {

    this.position_ = latlng;

    if (this.div_) {

        this.draw();
    }

    /**
    * This event is fired when the position of the InfoBox changes.
    * @name InfoBox#position_changed
    * @event
    */
    google.maps.event.trigger(this, "position_changed");
};

/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function(index) {

    this.zIndex_ = index;

    if (this.div_) {

        this.div_.style.zIndex = index;
    }

    /**
    * This event is fired when the zIndex of the InfoBox changes.
    * @name InfoBox#zindex_changed
    * @event
    */
    google.maps.event.trigger(this, "zindex_changed");
};

/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function() {

    return this.content_;
};

/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function() {

    return this.position_;
};

/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function() {

    return this.zIndex_;
};

/**
* Shows the InfoBox.
*/
InfoBox.prototype.show = function() {

    this.isHidden_ = false;
    if (this.div_) {
        this.div_.style.visibility = "visible";
    }
};

/**
* Hides the InfoBox.
*/
InfoBox.prototype.hide = function() {

    this.isHidden_ = true;
    if (this.div_) {
        this.div_.style.visibility = "hidden";
    }
};

/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
*  (usually a <tt>google.maps.Marker</tt>) is specified, the position
*  of the InfoBox is set to the position of the <tt>anchor</tt>. If the
*  anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function(map, anchor) {

    var me = this;

    if (anchor) {

        this.position_ = anchor.getPosition();
        this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function() {
            me.setPosition(this.getPosition());
        });
    }

    this.setMap(map);

    if (this.div_) {

        this.panBox_();
    }
};

/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function() {

    if (this.closeListener_) {

        google.maps.event.removeListener(this.closeListener_);
        this.closeListener_ = null;
    }

    if (this.eventListener1_) {

        google.maps.event.removeListener(this.eventListener1_);
        google.maps.event.removeListener(this.eventListener2_);
        google.maps.event.removeListener(this.eventListener3_);
        this.eventListener1_ = null;
        this.eventListener2_ = null;
        this.eventListener3_ = null;
    }

    if (this.moveListener_) {

        google.maps.event.removeListener(this.moveListener_);
        this.moveListener_ = null;
    }

    if (this.contextListener_) {

        google.maps.event.removeListener(this.contextListener_);
        this.contextListener_ = null;
    }

    this.setMap(null);
};









 
