/**
 * Copyright (c) 2010 - ShopAlive Licensing Ltd - All rights reserved
 */

/**
 * enum and classes block
 */
 var PoiMarkerImages = {
     'blankMarker':'/PanoshopEngine/images/poi/poi_blank.png',
     'peopleMarker':'/PanoshopEngine/images/poi/poi_people.png',
     'cartMarker':'/PanoshopEngine/images/poi/poi_cart.png',
     'bankMarker':'/PanoshopEngine/images/poi/poi_bank.png',
     'barMarker':'/PanoshopEngine/images/poi/poi_bar.png',
     'bookMarker':'/PanoshopEngine/images/poi/poi_book.png',
     'cafeMarker':'/PanoshopEngine/images/poi/poi_cafe.png',
     'cafeteriaMarker':'/PanoshopEngine/images/poi/poi_cafeteria.png',
     'cinemaMarker':'/PanoshopEngine/images/poi/poi_cinema.png',
     'companyMarker':'/PanoshopEngine/images/poi/poi_company.png',
     'exhibitionMarker':'/PanoshopEngine/images/poi/poi_exhibition.png',
     'fashionMarker':'/PanoshopEngine/images/poi/poi_fashion.png',
     'gasStationMarker':'/PanoshopEngine/images/poi/poi_gas_station.png',
     'groceryMarker':'/PanoshopEngine/images/poi/poi_grocery.png',
     'hotelMarker':'/PanoshopEngine/images/poi/poi_hotel.png',
     'institutionalMarker':'/PanoshopEngine/images/poi/poi_institutional.png',
     'internetCafeMarker':'/PanoshopEngine/images/poi/poi_internet_cafe.png',
     'nightClubMarker':'/PanoshopEngine/images/poi/poi_night_club.png',
     'pharmacyMarker':'/PanoshopEngine/images/poi/poi_pharmacy.png',
     'restaurantMarker':'/PanoshopEngine/images/poi/poi_restaurant.png',
     'shoppingCenterMarker':'/PanoshopEngine/images/poi/poi_shopping_center.png',
     'sportCenterMarker':'/PanoshopEngine/images/poi/poi_sport_center.png',
     'themeParkMarker':'/PanoshopEngine/images/poi/poi_theme_park.png',
     'tourismMarker':'/PanoshopEngine/images/poi/poi_camping.png',
     'infoMarker':'/PanoshopEngine/images/poi/poi_info.png',
     'panoramaMarker':'/PanoshopEngine/images/poi/poi_panorams.png',
     'photoMarker':'/PanoshopEngine/images/poi/poi_photo.png',
     'geoLocationMarker':'/PanoshopEngine/images/poi/radar.png',
     'smallDotMarker':'/PanoshopEngine/images/poi/poi_small_dot.png'
 };

var searchItemTypes = {
    'shop' : 'shop',
    'panorama' : 'panorama'
};

function shopInfoMapObject(address,phone,skypeAccount,shopLogos,enterImg,enterLink,shortDescription,infoLink,infoTitle,workingStatus,shopId,panoramaId,directLinkName) {
    this.address = address;
    this.phone = phone;
    this.skypeAccount = skypeAccount;
    this.enterLink = enterLink;
    this.enterImg = enterImg;
    this.shortDescription = shortDescription;
    this.infoLink = infoLink;
    this.infoTitle = infoTitle;
    this.workingStatus = workingStatus;
    this.shopLogos = shopLogos;
    this.shopId = shopId;
    this.panoramaId = panoramaId;
    this.directLinkName = directLinkName;
}

function panoramaInfoMapObject(address,img,imgLink,infoLink,infoTitle,panoramaId) {
    this.address = address;
    this.img = img;
    this.imgLink = imgLink;
    this.infoLink = infoLink;
    this.infoTitle = infoTitle;
    this.panoramaId = panoramaId;
}

function geoLocationInfoMapObject(){
}

function dynamicLoadInfoMapObject(id, itemType) {
    this.id = id;
    this.itemType = itemType;
    this.loadInfo = function () {
        for (var i in dynamicLoadedSpots) {
            if (dynamicLoadedSpots[i].id == this.id
                    && dynamicLoadedSpots[i].itemType == this.itemType)
            return;
        }
        dynamicLoadedSpots.push({
            id: id,
            itemType: itemType
        });
        var params = {
            "id": this.id,
            "itemType": this.itemType,
            "backUrl": window.location.href
        };
        jQuery.getJSON("/PanoshopEngine/show/loadMapInfoWindow.do",
                params,
                renderMapInfoWindowCallback);
    }
}

function renderMapInfoWindowCallback(data) {
    if (data != undefined && !data.error) {
        var spotId = 'searchResultItemsForm:out';
        var itemObject = null;
        var itemType = searchItemTypes.shop;
        if (data.itemType == 'Shop') {
            itemObject = new shopInfoMapObject( data.address,
                                                data.phone,
                                                data.skypeAccount,
                                                data.logos,
                                                data.shopEntryPointThumbnailUrl,
                                                data.shopEntryPointUrl,
                                                data.description,
                                                data.shopUrl,
                                                '',
                                                data.workingStatus,
                                                data.id,
                                                data.spaceEntryObjectId,
                                                data.directLinkName);
            spotId += 's';
        } else if (data.itemType == 'CommercialCandidate') {
            itemObject = new shopInfoMapObject(data.address,data.phone,'',[],'','','','','','','','','');
            spotId += 'c';
        }
        spotId += data.id;
        if (itemObject != null) {
            var spot = getSpotById(spotId);
            itemObject.latlng = spot.latlng;
            spot.infoWindow = createInfoWindow(
                                   getInfoWindowContent(data.title,
                                                        itemType,
                                                        itemObject));
            spot.onSpotOver();
        }
    }
}

/**
 * variables block
 */
    var map;
    var activeSpot;
    var spotCollection = new Array();
    var dynamicLoadedSpots = new Array();

    var initialLocation;
    var geoLocationMarker;
    var geoLocationLatLng;
    var ShopAlive = new google.maps.LatLng(46.207539, 6.146573);
    var blankLatLng = new google.maps.LatLng(30.0, 15.0);

/**
 * main map functions block
 */

function initGoogleMap(container) {
    var mapOptions = {
        zoom: 2,
        center: blankLatLng,
        scaleControl: true,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById(container), mapOptions);

    google.maps.event.addListener(map.getStreetView(), 'visible_changed', function() {
        if (activeSpot) {
            activeSpot.onSpotOut();
        }
    });
}

function createMapByCoordinateList(container, coordinates) {
    initGoogleMap(container);
    for (var i = 0; i < coordinates.length; i++) {
        var marker = new google.maps.Marker({position: coordinates[i],
                                map: map});
        google.maps.event.addListener(marker, 'click', function(){
                    map.panTo(marker.getPosition());
                    map.setZoom(16);
                });
    }
}

function showItemOnMap(lat,lng) {
    if (map != undefined) {
        map.setZoom(13);
        map.panTo(new google.maps.LatLng(lat, lng));
    }
}

function initResultOnMap(zoom,centerLat,centerLng) {
    try {

        initGoogleMap("placeForMap");

        var zoomInt = parseInt(zoom);

        if (!jQuery.resultIsEmpty) {
            createGeoLocationSpot();
            mapReady();
            placeSpots(isNaN(zoomInt));
        } else {
            var cityIdVal = jQuery('select#cityId').val();
            var cityInfo = SearchLocationCitiesConfig[cityIdVal != '' ? cityIdVal : envDomainRegion];
            zoomInt = cityInfo.zoom;
            centerLat = cityInfo.lat;
            centerLng = cityInfo.lng;
        }

        centerAndZoomMap(zoomInt, map, centerLat, centerLng);

        google.maps.event.addListener(map, 'tilesloaded', function() {
            var hide = getCookieSafe(jQuery, 'showOutPano') == 'true';
            if (hide) {
                jQuery("#togglePanoControlIdCheck").attr('checked','checked');
                showPanoramasOnMap();
            }
        });

        google.maps.event.addListener(map.getStreetView(), 'visible_changed', function() {
            if (map.getStreetView().getVisible()) {
                rotateToActiveSpot(map.getStreetView(),
                                   activeSpot ? activeSpot.marker.getPosition() : null);
            }
        });

        placeControlsToMap(map);

    } catch(error) {
    }
}

function rotateToActiveSpot(streetView, position) {
    if (position != undefined
            && streetView != undefined
            && streetView.getPosition() != undefined) {
        var streetViewPos = streetView.getPosition();
        var activeSpotPosLat = position.lat() / 180 * Math.PI;
        var activeSpotPosLng = position.lng() / 180 * Math.PI;
        var streetViewPosLat = streetViewPos.lat() / 180 * Math.PI;
        var streetViewPosLng = streetViewPos.lng() / 180 * Math.PI;

        var y = Math.sin(activeSpotPosLng - streetViewPosLng) * Math.cos(activeSpotPosLat);
        var x = Math.cos(streetViewPosLat) * Math.sin(streetViewPosLat) -
            Math.sin(streetViewPosLat) * Math.cos(activeSpotPosLat) * Math.cos(activeSpotPosLng - streetViewPosLng);
        var angle = Math.atan2(y, x) / Math.PI * 180;
        var pov = streetView.getPov();
        pov.heading = angle;
        streetView.setPov(pov);
    }
}

    function placeControlsToMap(map) {
        var searchControlDiv = document.createElement('DIV');
        var searchControl = new SearchControl(searchControlDiv, map);
        searchControlDiv.index = 2;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(searchControlDiv);

        var mapViewControlDiv = document.createElement('DIV');
        var mapViewControl = new MapViewControl(mapViewControlDiv, map);
        mapViewControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(mapViewControlDiv);
    }

    function centerAndZoomMap(zoomInt, map, centerLat, centerLng){
        if (!isNaN(zoomInt)) {
            map.setZoom(zoomInt);
            if (centerLat != undefined
                    && centerLat != ''
                    && centerLng != undefined
                    && centerLng != '') {
                map.setCenter(new google.maps.LatLng(centerLat,centerLng));
            }
        }
    }

    function createGeoLocationSpot() {
        var position = getGeoLocationCookie(jQuery);
        if (position['lat'] != undefined && position['lon'] != undefined) {
            addspot("geoLocation",
                    position['lat'],
                    position['lon'],
                    getGeoLocationTitle(),
                    "",
                    new geoLocationInfoMapObject(),
                    "",
                    PoiMarkerImages.geoLocationMarker);
            geoLocationLatLng = new google.maps.LatLng(position['lat'], position['lon']);
        }
    }

    function gotoStreetPanorama(lat,lng,radius) {
        if (map && !isEmptyString(lat) && !isEmptyString(lng)) {
            var streetView = map.getStreetView();
            var streetViewService = new google.maps.StreetViewService();
            if (radius == undefined) radius = 200;
            streetViewService.getPanoramaByLocation(new google.maps.LatLng(lat,lng), radius, function(result,status) {
                if (status == google.maps.StreetViewStatus.OK) {
                    streetView.setPosition(result.location.latLng);
                    streetView.setVisible(true);
                } else if (status == google.maps.StreetViewStatus.ZERO_RESULTS) {
                    alert('There is no available Street Views in the radius of '+radius+'m');
                }
            })
        }
    }

    function getMapResultBounds() {
        var minLat;
        var maxLat;
        var minLng;
        var maxLng;
        for (var i in spotCollection) {
            var spotLatlng = spotCollection[i].latlng;
            if (spotLatlng != undefined) {
                if(minLat == undefined || maxLat == undefined || minLng == undefined || maxLng == undefined) {
                    minLat = maxLat = spotLatlng.lat();
                    minLng = maxLng = spotLatlng.lng();
                } else {
                    if(minLat > spotLatlng.lat()) minLat = spotLatlng.lat();
                    if(maxLat < spotLatlng.lat()) maxLat = spotLatlng.lat();
                    if(minLng > spotLatlng.lng()) minLng = spotLatlng.lng();
                    if(maxLng < spotLatlng.lng()) maxLng = spotLatlng.lng();
                }
            }
        }
        if (minLat == undefined || minLng == undefined
                || maxLat == undefined || maxLng == undefined)
        return undefined;

        var minLatLng = new google.maps.LatLng(minLat,minLng) ;
        var maxLatLng = new google.maps.LatLng(maxLat,maxLng) ;
        return new google.maps.LatLngBounds(minLatLng, maxLatLng);
    }

    function fitMapBounds() {
        if (map) {
            var bounds = getMapResultBounds();
            if (bounds == undefined) {
                centerAndZoomMap(2, map, blankLatLng.lat(), blankLatLng.lng());
            }
            else if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
                centerAndZoomMap(16, map, bounds.getNorthEast().lat(), bounds.getNorthEast().lng());
            } else {
                map.fitBounds(bounds);
            }
        }
    }

   function getSpotById(id){
       for(var i in spotCollection){
                if(spotCollection[i].id == id)
                    return spotCollection[i];
            }
            return null;
   }

   function getSpotIndexById(id){
        for(var i in spotCollection){
            if(spotCollection[i].id == id)
                return i;
        }
        return -1;
    }

   function addspot(id,lat,lng,name,itemType,itemObject,onclick,markerImg){
        var savedSpot = getSpotById(id);
        if(savedSpot)
            return savedSpot;
        var spot = new Spot(id,lat,lng,name,itemType,itemObject,onclick,markerImg);
        spotCollection.push(spot);
        return spot;
   }

   function Spot(id,lat,lng,name,itemType,itemObject,onclick,markerImg) {
        this.latlng = (lat == '' || lng == '') ? undefined : new google.maps.LatLng(lat, lng);
        if (itemObject != undefined && itemObject != "") {
            itemObject.latlng = this.latlng;
        }
        var image = new google.maps.MarkerImage(markerImg);
        this.markerImage = markerImg;
        this.id = id;
        this.name = name;
        this.itemObject = itemObject;
        this.itemType = itemType;
        this.onclick = onclick;
        this.marker = new google.maps.Marker({position:this.latlng, icon: image});
        if (this.itemObject instanceof shopInfoMapObject
                || this.itemObject instanceof panoramaInfoMapObject
                || this.itemObject instanceof geoLocationInfoMapObject) {
            this.infoWindow = createInfoWindow(
                                   getInfoWindowContent(this.name,
                                                        this.itemType,
                                                        this.itemObject));
        }

        this.setMap = function(map){
            this.marker.setMap(map);
            var marker = this.marker;
            var spot = this;
            if(map){
                google.maps.event.addListener(this.marker, 'click', function(){
                    map.panTo(marker.getPosition());
                    zoomToSpot();
                });
                google.maps.event.addListener(this.marker, 'mouseover', function(){
                    spot.onSpotOver();
                });
            }
        };

        this.onSpotOver = function(){
            if (this.infoWindow == undefined && this.itemObject instanceof dynamicLoadInfoMapObject) {
                this.itemObject.loadInfo();
            } else {
                if(activeSpot && activeSpot.id != this.id) {
                    activeSpot.onSpotOut();
                }
                openInfoWindow(this.infoWindow, this.marker, map);
                activeSpot = this;
            }
        };

        this.onSpotOut = function(){
            if (this.infoWindow) {
                this.infoWindow.close();
            }
            activeSpot = null;
        }

   }

   function createInfoWindow(content) {
       return new InfoBox
                ({alignBottom: true,
                  maxWidth: 0,
                  zIndex: 0,
                  boxClass: "infobox",
                  closeBoxMargin: "-16px 0px 0px 0px",
                  closeBoxURL: "/PanoshopEngine/images/close.png",
                  infoBoxClearance: new google.maps.Size(1, 1),
                  content: content});
   }

    function activateSpot(id, pan){
        var spot = getSpotById(id);
        if(activeSpot == spot) return;
        spot.onSpotOver();
        if (pan) {
            map.panTo(spot.latlng);
        }
    }

    function placeSpots(scale){
        for (var i = 0; i < spotCollection.length; i++) {
            try {
                var spot = spotCollection[i];
                spot.setMap(spot.latlng == undefined ? null : map);
                if (spot.id == 'geoLocation') {
//                    emptyGeoLocationMarker();
                    geoLocationMarker = spot.marker;
                }
            } catch(error){}
        }

        if (scale) {
            fitMapBounds();
        }
    }

    function zoomToSpot(){
       map.setZoom(16);
       if(activeSpot)
           map.setCenter(activeSpot.latlng);
    }

/**
 * info window functions block
 */

    function getInfoWindowContent(title, objType, object) {
        return  '<div id="iw_wrap">' +
                    '<div id="iw_header">' + title + '</div>' +
                    '<div id="iw_content">' +
                        '<table id="iw_content_table" border="0" cellpadding="0" cellspacing="0">' +
                        '<tbody>' +
                                (objType == searchItemTypes.shop ? getCenterShopInfoWindow(object)
                                : objType == searchItemTypes.panorama ? getCenterPanoramaInfoWindow(object) : "") +
                            '<tr><td colspan="2">&nbsp;</td></tr>' +
                        '</tbody>' +
                        '</table>' +
                    '</div>' +
                    '<div id="iw_footer">' +
                        (objType == searchItemTypes.shop || objType == searchItemTypes.panorama
                                ? getRouteButtons(object.latlng) : "") +
                        getInformationButton(objType, object) +
                        ((objType == searchItemTypes.panorama || objType == searchItemTypes.shop) && object.latlng != undefined
                               ? '<a href="#" onclick="gotoStreetPanoramaLinkClick(this.event, ' + object.latlng.lat() + ',' + object.latlng.lng() + ');" class="button rounded right">' +
                                    '<img src="/PanoshopEngine/images/pegman.png" alt="Street View" />' +
                                 '</a>'
                               : '') +
                        getEnterButtonCode(objType, object) +
                    '</div>' +
                '</div>';
    }

function getEnterButtonCode(objType, object) {
    if (objType == searchItemTypes.shop) {
        if (window.enterShopJSfunc != undefined) {
            return (!isEmptyString(object.shopId) && !isEmptyString(object.panoramaId))
                    ?   '<a href="#" onclick="enterShopJSfunc(event,'+object.shopId+','+object.panoramaId+');" class="button rounded right">' +
                            '<img src="/PanoshopEngine/images/icon_opendoor.png" alt="Enter" />' +
                        '</a>'
                    :   '';
        } else {
            return (!isEmptyString(object.enterLink))
                    ?   '<a href="'+object.enterLink+'" class="button rounded right">' +
                            '<img src="/PanoshopEngine/images/icon_opendoor.png" alt="Enter" />' +
                        '</a>'
                    :   '';
        }
    }
    return '';
}

function getInformationButton(objType,object) {
    if (window.gotoShopInfoJSfunc == undefined && window.gotoPanoramaInfoJSfunc == undefined) {
        return (objType == searchItemTypes.shop || objType == searchItemTypes.panorama)
                ? ('<a href="'+object.infoLink+'" class="button rounded right">' +
                      '<img src="/PanoshopEngine/images/icon_info_sm.png" title="'+object.infoTitle+'" alt="Information" />' +
                   '</a>')
                : '';
    }
    var clickFunc = '';
    if (objType == searchItemTypes.shop) {
        clickFunc = object.directLinkName != undefined && object.directLinkName != '' ? "gotoShopInfoJSfunc(event,'"+object.directLinkName+"')" : '';
    } else if (objType == searchItemTypes.panorama) {
        clickFunc = object.panoramaId != undefined && object.panoramaId != '' ? 'gotoPanoramaInfoJSfunc(event,'+object.panoramaId+');' : '';
    } else {
        return '';
    }
    return '<a href="#" onclick="'+clickFunc+'" class="button rounded right">' +
              '<img src="/PanoshopEngine/images/icon_info_sm.png" title="'+object.infoTitle+'" alt="Information" />' +
           '</a>';
}

function getRouteButtons(end) {
    if (geoLocationLatLng == undefined || end == undefined) return '';

    var endLatLng = 'new google.maps.LatLng('+end.lat()+', '+end.lng()+')';
    return '<div class="direction_bar rounded left">' +
               '<div class="first"><img src="/PanoshopEngine/images/icon_car.png" onclick="openRouteMapPopup(\'driving\', geoLocationLatLng, '+endLatLng+')" class="left" /></div>' +
               '<div><img src="/PanoshopEngine/images/icon_walk.png" onclick="openRouteMapPopup(\'walking\', geoLocationLatLng, '+endLatLng+')" class="left" /></div>' +
               '<div class="last"><img src="/PanoshopEngine/images/icon_bicycle.png" onclick="openRouteMapPopup(\'bicycling\', geoLocationLatLng, '+endLatLng+')" class="left" /></div>' +
           '</div>';
}

function getCenterShopInfoWindow(shopObject) {
    return  '<tr>' +
                '<td colspan=2>' +
                    (shopObject.enterLink == "" ? "" : "<a href='" + shopObject.enterLink + "'>") +
                    (shopObject.enterImg != "" ? '<img src="' + shopObject.enterImg + '" width="295px" height="70px" alt="ShopLogo">' : "") +
                    (shopObject.enterLink == "" ? "" : "</a>") +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td width="100px">' +
                    '<div style="margin:5px;">' +
                         getShopLogosHtml(shopObject.shopLogos) +
                         (shopObject.workingStatus == "Closed" ? '<a href="#" class="rounded shadow shop_status_close" >Closed</a>'
                               : shopObject.workingStatus == "Opened" ? '<a href="#" class="rounded shadow shop_status_open" >Open</a>' : '') +
                    '</div>' +
                '</td>' +
                '<td width="175px">' +
                    '<div>' +
                        shopObject.address +
                        '<br/>' + shopObject.phone + (shopObject.skypeAccount != "" ? '<a class="skype_call" href="skype:' + shopObject.skypeAccount + '?call"></a>' : "") +
                    '</div>' +
                    '<div style="margin-top:5px;">' +
                        shopObject.shortDescription +
                    '</div>' +
                '</td>' +
            '</tr>';
}

function getShopLogosHtml(shopLogos) {
    var logosHtml = "";
    if (shopLogos != undefined && shopLogos.length > 0) {
        for (var i = 0; i < shopLogos.length; i++) {
            logosHtml += '<img width="100px" alt="shopLogo" src="' + shopLogos[i] + '"/><br/>';
        }
    }
    return logosHtml;
}

function getCenterPanoramaInfoWindow(panoramaObject) {
    return '<tr><td colspan="2">&nbsp;</td></tr>' +
           '<tr>' +
               '<td align="center">' +
                   '<div style="margin-right:5px;">' +
                        (panoramaObject.imgLink == "" ? "" : "<a href='" + panoramaObject.imgLink + "'>") +
                        (panoramaObject.img != "" ? '<img class="border" src="' + panoramaObject.img + '" width="249px" height="56px" alt="panoImg">' : "") +
                        (panoramaObject.imgLink == "" ? "" : "</a>") +
                    '</div>' +
                   '<div>' +
                       '<b>'+panoramaObject.address+'</b>' +
                   '</div>' +
               '</td>' +
           '</tr>'
}

/**
 * map controls block
 */

function codeAddress(address, isGeolocation) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (isGeolocation) {
                initialLocation = results[0].geometry.location;
                insertGeoLocationToMap(map,getGeoLocationTitle());
            } else {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    animation: google.maps.Animation.BOUNCE
                });
                map.setZoom(7);
                map.setCenter(results[0].geometry.location);
            }
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

function showPanoramasOnMap() {
    if (map) {
        var topRight = map.getBounds().getNorthEast();
        var bottomLeft = map.getBounds().getSouthWest();
        var params = {
            "zoom": map.getZoom(),
            "lat1": bottomLeft.lat(),
            "lng1": bottomLeft.lng(),
            "lat2": topRight.lat(),
            "lng2": topRight.lng(),
            "cLat": map.getCenter().lat(),
            "cLng": map.getCenter().lng()
        };
        jQuery.getJSON("/PanoshopEngine/show/getNearestPanoramas.do",
                params,
                renderPanoramasOnMapCallback);
    }
}

function deletePoiByMarkerImage(image) {
    var tmpCollection = new Array();
    for (var i = 0; i < spotCollection.length; i++) {
        if (spotCollection[i].markerImage == image) {
            spotCollection[i].marker.setMap(null);
        } else {
            tmpCollection.push(spotCollection[i]);
        }
    }
    spotCollection = tmpCollection;
}

function renderPanoramasOnMapCallback(data) {
    if (data && !data.error) {
        for (var i = 0; i < data.items.length; i++) {
            var item = data.items[i];
            addspot('searchResultItemsForm:hsp'+item.id,
                    item.latitude,
                    item.longitude,
                    item.streetName,
                    searchItemTypes.panorama,
                    new panoramaInfoMapObject(
                            item.addressLine1,
                            item.thumbnailUrl,
                            "/PanoshopEngine/show/panorama/"+item.id,
                            "/PanoshopEngine/flow/displayPanorama?panoramaId="+item.id,
                            "",
                            item.id),
                    '',
                    PoiMarkerImages.photoMarker).setMap(map);
        }
    }
}

function SearchControl(controlDiv, map) {
  controlDiv.style.padding = '7px';
  var controlUI = document.createElement('DIV');
  controlUI.style.display = 'inline-block';
  controlUI.innerHTML = '<div class="gm_custom_search_wrap rounded border box_shadow">'+
                            '<span class="gm_custom_search_input_wrap rounded border left">'+
                                '<input class="" id="map_address" type="textbox" value="Geneva" onclick="this.value=\'\';" />'+
                            '</span>'+
                            '<input class="button border left" type="button" value="" onclick="codeAddress(jQuery(\'#map_address\').val(), false)" />'+
                            '<input class="left" type="checkbox" onchange="togglePanoramasControl()" ' + (getPanoramasAreShown() ? 'checked="checked"' : '') + '/>'+
                            '<span class="gm_custom_search_sap left">Show All <br/> Panoramas</span>'+
						'</div>';
  controlDiv.appendChild(controlUI);

}

function MapViewControl(controlDiv, map) {
    controlDiv.style.padding = '7px';
    var controlUI = document.createElement('DIV');
    controlUI.style.display = 'inline-block';
    controlUI.innerHTML =   '<div class="gm_custom_mapview rounded border box_shadow" style="margin-top:-1px;" >' +
                                '<div id="gm_custom_mapview_block" class="rounded inline_block">' +
                                    '<span class="mapView_wrap active" onclick="gm_custom_mapView_click(this);">' +
                                        '<input id="Map" type="button" class="mapView_input" value="Map" onclick="gm_custom_mapView(\'roadmap\');" />' +
                                    '</span>' +
                                    '<span class="mapView_wrap" onclick="gm_custom_mapView_click(this);">' +
                                        '<input id="Satellite" type="button" class="mapView_input" value="" onclick="gm_custom_mapView(\'satellite\');" />' +
                                    '</span>' +
                                    '<span class="mapView_wrap" onclick="gm_custom_mapView_click(this);">' +
                                        '<input id="Hybrid" type="button" class="mapView_input" value="" onclick="gm_custom_mapView(\'hybrid\');" />' +
                                    '</span>' +
                                    '<span class="mapView_wrap" onclick="gm_custom_mapView_click(this);">' +
                                        '<input id="Terrain" type="button" class="mapView_input" value="" onclick="gm_custom_mapView(\'terrain\');" />' +
                                    '</span>' +
                                '</div>' +
                            '</div>';
    controlDiv.appendChild(controlUI);
}

function gm_custom_mapView(mapview) {
    if (mapview == "satellite") {
        map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
    } else if (mapview == "roadmap") {
        map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    } else if (mapview == "hybrid") {
        map.setMapTypeId(google.maps.MapTypeId.HYBRID);
    } else if (mapview == "terrain") {
        map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
    }
}

function gm_custom_mapView_click(mapview_wrap) {
    var wraps = getElementsForParentByClassName(document.getElementById('gm_custom_mapview_block'),'mapView_wrap');
    for (var i = 0; i < wraps.length; i++) {
        wraps[i].className = "mapView_wrap";
    }
    var inputs = getElementsForParentByClassName(document.getElementById('gm_custom_mapview_block'),'mapView_input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].value = "";
    }
    mapview_wrap.childNodes[0].value=mapview_wrap.childNodes[0].id;
    mapview_wrap.className="mapView_wrap active";
}

function getPanoramasAreShown() {
    return getCookieSafe(jQuery, 'showOutPano') == 'true';
}

function togglePanoramasControl() {
    if (!getPanoramasAreShown()) {
        setCookieSafe(jQuery,'showOutPano','true',{});
        showPanoramasOnMap();
    } else {
        setCookieSafe(jQuery,'showOutPano','false',{});
        deletePoiByMarkerImage(PoiMarkerImages.photoMarker);
    }
}

/**
 * geoLocation functions block
 */

function getGeoLocation(map){
    getBrowserGeoLocation(
        function(lat,lng){
            initialLocation = new google.maps.LatLng(lat,lng);
            insertGeoLocationToMap(map, getGeoLocationTitle());
        },
        function() {
            handleNoGeolocation(map);
        }
    );
}

function insertGeoLocationToMap(map, contentString) {

    setGeoPositionCookie(jQuery,initialLocation.lat(),initialLocation.lng());

    emptyGeoLocationMarker();

    var infoWindow = createInfoWindow(getInfoWindowContent(contentString));

    geoLocationMarker = new google.maps.Marker({
        position: initialLocation,
        icon: PoiMarkerImages.geoLocationMarker
    });
    geoLocationLatLng = initialLocation;

    map.setCenter(initialLocation);
    map.setZoom(15);

    geoLocationMarker.setMap(map);
    marker_listener(infoWindow, geoLocationMarker, map);
}

function handleNoGeolocation(map) {

    // Getting position
    var position = getGeoLocationCookie(jQuery);
    if (position['lat'] != undefined && position['lon'] != undefined) {
        initialLocation = new google.maps.LatLng(position['lat'], position['lon']);
    } else {
        initialLocation = ShopAlive;
    }
    insertGeoLocationToMap(map, getGeoLocationTitle());
    findMeFunction = jQuery.findMeFunction;
    jQuery.findMeFunction();
}

function openInfoWindow(infoWindow, marker, map) {
    if (infoWindow && !infoWindow.isOpened) {
        var streetView = map.getStreetView();
        infoWindow.open(streetView.getVisible() ? streetView : map, marker);
    }
}

function marker_listener(infoWindow, marker, map) {
    google.maps.event.addListener(marker, 'mouseover', function() {
        openInfoWindow(infoWindow, marker, map);
    });

	google.maps.event.addListener(marker, 'click', function() {
        map.setZoom(16);
        map.setCenter(initialLocation);
    });
}

function emptyGeoLocationMarker() {
    if (geoLocationMarker) {
        geoLocationMarker.setMap(null);
    }
}

function getGeoLocationTitle() {
    return panoshopJSLabels.getLabel('yourGeoLocation',jQuery("select#lang").val());
}

function getBrowserGeoLocation(successHandler, noGeoLocationHandler) {
    // Try W3C Geolocation method (Preferred)
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            successHandler(position.coords.latitude, position.coords.longitude);
        }, function() {
            noGeoLocationHandler();
        });
    } else if (google.gears) {
        // Try Google Gears Geolocation
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function(position) {
            successHandler(position.latitude, position.longitude);
        }, function() {
            noGeoLocationHandler();
        });
    } else {
        // Browser doesn't support Geolocation
        noGeoLocationHandler();
    }
}
