//defining new GMarker fields
GMarker.prototype.imageElem = null;
GMarker.prototype.type = null;
GMarker.prototype.spotType = null;

var centerLatitude = 0; // initial latitude
var centerLongitude = 0; // initial longitude
var startZoom = 1; // initial zoom

/*
* initialize context menu to use on google maps
*
* @param oMap googlemap
*/
function ContextMenu(oMap){ this.initialize(oMap); }

/*
*  initialize context menu
*
* @param oMap googlemap
*/
ContextMenu.prototype.initialize = function(oMap){
    this.map = oMap;
    var that=this;
    this.active = "map";
    this.marker = null;
    
    /* the fragment below contains a code which will display context menu after right mouse click
    this.onMapContextMenu = document.createElement("div");     // create div for onMap context menu
    this.onMarkerContextMenu = document.createElement("div");     // create div for onMarker context menu
    this.onMapContextMenu.style.display="none";     // hide menu untill it's clicked
    this.onMarkerContextMenu.style.display="none";    // hide menu untill it's clicked
    this.onMapContextMenu.className="contextmenu";        // choose class name for onMap context menu
    this.onMarkerContextMenu.className="contextmenu";    // choose class name for onMarker context menu
    this.onMapContextMenu.ul_container = document.createElement("ul");    // create list for onMap context menu
    this.onMapContextMenu.ul_container.id="on_map_context_menu_ul";        // create list element for onMap context menu
    this.onMarkerContextMenu.ul_container = document.createElement("ul");    // create list element for onMarker context menu
    this.onMarkerContextMenu.ul_container.id = "on_marker_context_menu_ul";    // create list element for onMarker context menu
    this.onMapContextMenu.appendChild(this.onMapContextMenu.ul_container);    
    this.onMarkerContextMenu.appendChild(this.onMarkerContextMenu.ul_container);    
    this.initLink(this.map); // context menu functionality
    this.map.getContainer().appendChild(this.onMapContextMenu);    
    this.map.getContainer().appendChild(this.onMarkerContextMenu);
    this.map.disableDoubleClickZoom();

    //Event listeners that will interact with our context menu
    GEvent.addListener(this.map,"singlerightclick",function(pixel,src,overlay) {
            that.clickedPixel = pixel;
            var x=pixel.x;
            var y=pixel.y;
            //Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
            if (x > that.map.getSize().width - 160) { x = that.map.getSize().width - 160 }
            if (y > that.map.getSize().height - 120) { y = that.map.getSize().height - 120 }
            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
        if map is active
        if(that.active == "map") {
            pos.apply(that.onMapContextMenu);
            that.onMapContextMenu.style.display = "block";         // show onMap menu
            that.onMarkerContextMenu.style.display = "none";    // hide onMarker menu
            return;
        } 
        if marker is active
        if(that.active == "spot"){
            pos.apply(that.onMarkerContextMenu);
            that.onMarkerContextMenu.style.display = "block";    // show onMarker menu
            that.onMapContextMenu.style.display = "none";        // hide onMap menu
            return;
        }
    });    
    
    /event listener to hide context menu after moving a map
    GEvent.addListener(oMap, "move", function() {
        //hide both menus
        that.onMapContextMenu.style.display="none";
        that.onMarkerContextMenu.style.display="none";
    });
    //event listener to hide context menu after clicking on a map
    GEvent.addListener(oMap, "click", function(overlay,point) {
        //hide both menus
        that.onMapContextMenu.style.display="none";
        that.onMarkerContextMenu.style.display = "none";
    });        
    //event listener to add marker after doubleclicking on a map
    GEvent.addListener(map, "dblclick", function(overlay,latlng) {
        addSpot(map, latlng, {draggable:false}); // add marker
    }); */
}

/*
* functionality of both onMap and onMarker menus
*
* @param oMap googlemap
*/
ContextMenu.prototype.initLink = function(oMap){
    this.map = oMap;
    var that=this;

    //MARKER CONTEXT MENU FUNCTIONALITY
    //Zoom in
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0)'>Zoom in here</a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        that.map.setCenter(that.map.fromContainerPixelToLatLng(that.marker)); // set center of the map
        that.map.zoomIn(); // zoom in the map
        that.onMarkerContextMenu.style.display='none'; // hide menu
    });
    this.onMarkerContextMenu.ul_container.appendChild(a_link);
    //Zoom out
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'>  Zoom out here </a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        that.map.setCenter(that.map.fromContainerPixelToLatLng(that.marker)); // set center of the map
        that.map.zoomOut(); // zoom out the map
        that.onMarkerContextMenu.style.display='none'; // hide menu
    });
    this.onMarkerContextMenu.ul_container.appendChild(a_link);
    //Center
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'>Center Map Here  </a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);    // count the point to center the map
        that.map.panTo(point); // center map to the point
        that.onMarkerContextMenu.style.display="none"; // hide menu
    });
    this.onMarkerContextMenu.ul_container.appendChild(a_link);
    //Delete
    a_link = document.createElement("li");
    a_link.className = 'top_border';
    a_link.innerHTML="<a href='javascript:void(0);'>Delete spot </a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        if(that.marker.markerId) that.map.removeOverlay(that.marker); // remove marker
        deleteMarker(that.marker.markerId);  // remove marker from database
        that.onMarkerContextMenu.style.display="none"; // hide menu
    });
    this.onMarkerContextMenu.ul_container.appendChild(a_link);
    //END OF MARKER CONTEXT MENU FUNCTIONALITY
    
    //MAP CONTEXT MENU FUNCTIONALITY
    //Zoom in 
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0)>Zoom in here</a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        that.map.setCenter(that.map.fromContainerPixelToLatLng(that.clickedPixel)); // set center of the map
        that.map.zoomIn(); // zoom in the map
        that.onMapContextMenu.style.display='none'; // hide menu
    });
    this.onMapContextMenu.ul_container.appendChild(a_link);
    //Zoom out
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'>Zoom out here</a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        that.map.setCenter(that.map.fromContainerPixelToLatLng(that.clickedPixel)); // set center of the map
        that.map.zoomOut(); // zoomout the map
        that.onMapContextMenu.style.display='none'; // hide menu
    });
    this.onMapContextMenu.ul_container.appendChild(a_link);
    //Center
    a_link = document.createElement("li");
    a_link.innerHTML="<a href='javascript:void(0);'>Center Map Here</a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel); // count where to center the map
        that.map.panTo(point); // center map to point
        that.onMapContextMenu.style.display="none"; // hide menu
    });
    this.onMapContextMenu.ul_container.appendChild(a_link);
    //Place spot
    a_link = document.createElement("li");
    a_link.className = 'top_border';
    a_link.innerHTML="<a href='javascript:void(0);'>Place spot here</a>";
    //event triggered on click
    GEvent.addDomListener(a_link, 'click', function() {
        var point = that.map.fromContainerPixelToLatLng(that.clickedPixel); // count where to add marker
        addSpot(oMap, point, {draggable:true}); // add marker
        that.onMapContextMenu.style.display="none"; // hide menu
    });
    this.onMapContextMenu.ul_container.appendChild(a_link);
    //END OF MAP CONTEXT MENU FUNCTIONALITY
}

/*
* if on spot set active and marker to spot
*/
ContextMenu.prototype.onSpot = function(spot) {
    this.active = "spot";
    this.marker = spot;
}

/*
* if on map set active to map
*/
ContextMenu.prototype.onMap = function() {
    this.active = "map";
}

/*
* open info window over a marker
*
* @param countriesSelector list of countries
*/
GMarker.prototype.openSaveMarkerWindow = function(htmlMessage, counter, spotArray) {
    var point = this.getLatLng();
    
    var htmlMessage = '<div style="width:360px"><form name="savespot" action="javascript:saveMarker()">' +
        '<input type="hidden" id="MemberId" name="MemberId" value="'+ CURRENT_USER +'"' +
        '<dl>'+
        '<dt>'+step_two+': </dt>'+
        '<dd><select id="markerType" name="markerType">' +
        '<option value="washoday">'+ my_travel +'</option>' +
        '<option value="wouldhoday">'+ travel_aim +'</option>';
        if (!homeplaceLocation) {
            htmlMessage += '<option value="place">'+ my_place +'</option>';
        }
        htmlMessage += '</select></dd>' +
        '<dt>'+country+':</dt>'+
        '<dd>' + spotArray.lo_co_name + '</dd>';
        if (spotArray.lo_ci_name != '') {
            htmlMessage += '<dt>'+city+':</dt>'+
            '<dd>' + spotArray.lo_ci_name + '</dd>';
        }
        htmlMessage += 
        //'<dt>'+travel_type+':</dt>'+
        //'<dd>'+
        //'<input type="radio" name="markerType" value="washoday"/><img src="http://localhost/branches/communityRelaunch/httpdocs/img/icons/sun_red.png"/>'+travel_aim+'<br />'+
        //'<input type="radio" name="markerType" value="wouldhoday"/><img src="http://localhost/branches/communityRelaunch/httpdocs/img/icons/sun_blue.png"/>'+my_travel+
        //'</dd>'+
       
       '<dt>'+ desc +':</dt><dd><textarea style="width:200px; height: 50px;" name="spotDesc" id="spotDesc"></textarea></dd>' + 
       '<dd><input value="'+ save +'" type="submit" /><input value="'+ reset +'" type="button" onclick="javascript:cancelMarker('+ this.id +')"/></dd></dl>';
    htmlMessage +=  '<input type="hidden" id="counter" name="counter" value="'+ this.id + '"/>' +
           '<input type="hidden" id="lo_lat" name="lo_lat" value="'+ point.lat() +'"/>'+
           '<input type="hidden" id="lo_lng" name="lo_lng" value="'+ point.lng() +'"/>'+
           //'<input type="hidden" id="markerId" name="markerId" value="'+spotArray.markerId+'"/>'+
           '<input type="hidden" id="lo_ci_id" name="lo_ci_id" value="'+spotArray.lo_ci_id+'"/>'+
           '<input type="hidden" id="lo_co_id" name="lo_co_id" value="'+spotArray.lo_co_id+'"/>'+
           '<input type="hidden" id="CountryName" name="CountryName" value="'+spotArray.lo_co_name+'"/>'+
           '<input type="hidden" id="CityName" name="CityName" value="'+spotArray.lo_ci_name+'"/>'+
           '</form></div>';
    this.openInfoWindow(htmlMessage);
    
    if (this.type == 'spot') {
        //counter ++;
    }
}

GMarker.prototype.openEditHomeMarkerWindow = function (counter, spotArray) {
    var point = this.getLatLng();
    htmlMessage = generateHomeMarkerContent(spotArray, homeplaceLocation);
    
    this.openInfoWindow(htmlMessage);
    mySuggMarker.init('suggestMar', 'selSuggestMar', 'Location_CountryidMar', 'searchGmapMar', 'suggestErrorMar', mySuggMarker);
    if (homeplaceLocation == 'vacation')
        mySuggMarker.makeOptionSelected(spotArray.lo_co_id);
}

/*
* display home location or vacation location
*/
function switchHomeContent(location) {
    switch(location) {
        case 'vacation':
            document.getElementById('vacationContent').style.display = '';
            document.getElementById('homeContent').style.display = 'none';
            break;
        case 'home':
            document.getElementById('vacationContent').style.display = 'none';
            document.getElementById('homeContent').style.display = '';
            break;
    }
}

/*
* generate home marker message
* user home location, or user vacation location
*/
function generateHomeMarkerContent(spotArray, homeplaceLocation) {
    vacationCity = '[ ' + city + ' ]';

    if (homeplaceLocation == 'vacation') {
        markerInfo = homeplaceMarker;
    }
    else if(homeplaceLocation == 'home') {
        markerInfo = homeplaceHome;
    }
    
    if (!markerInfo.lo_co_name)
        markerInfo.lo_co_name = '';
    if (homeplaceMarker.lo_ci_name)
        vacationCity = homeplaceMarker.lo_ci_name;
    if (!markerInfo.lo_desc)
        markerInfo.lo_desc = '';
    if (!markerInfo.markerId)
        markerInfo.markerId = 0;
    if (!markerInfo.id)
        markerInfo.id = 0;
        
    var suggestion=
        '<div style="position:relative; width:177px;">' +
            '<input style="margin: 4px 0;" id="searchGmapMar" disabled="disabled" size="22" type="text" value="' + vacationCity + '" autocomplete="off" onclick="leeren(\'searchGmapMar\');" onkeyup="javascript: window.setTimeout(\'mySuggMarker.showWords(\\\'map\\\')\', 100); return false;" class="myTextInput">' +
            '<div id="suggestMar" class="suggestDiv" style="display:none;">' +
                '<div class="suggestError" id="suggestErrorMar" name="suggestErrorMar" display="none">' + suggError + '</div>' +
                '<select id="selSuggestMar" size="10" class="suggest" style="display:none;" onClick="javascript:mySuggMarker.changeText(); return false;" ></select>' +
                '<script type="text/javascript">mySuggMarker.init(\'suggestMar\', \'selSuggestMar\', \'Location_CountryidMar\', \'searchGmapMar\', \'suggestErrorMar\', mySuggMarker);</script>' +
            '</div>' +
        '</div>';

    if (homeplaceLocation == 'home') {
        var homeRadioChecked = 'checked';
        var homeDivDisplay = 'block';
        var vacationRadioChecked = '';
        var vacationDivDisplay = 'none';
    }
    else if (homeplaceLocation == 'vacation') {
        var homeRadioChecked = '';
        var homeDivDisplay = 'none';
        var vacationRadioChecked = 'checked';
        var vacationDivDisplay = 'block';
    }

    var htmlMessage = 
        '<div style="width:360px;">' +
        '<dt>'+question+'</dt>' +
        '<dd><input type="radio" name="placeType" value="home" ' + homeRadioChecked + ' onChange="switchHomeContent(\'home\')" />'+home+'&nbsp;<input type="radio" name="placeType" value="vacation" ' + vacationRadioChecked + ' onChange="switchHomeContent(\'vacation\')" />'+vacation+'</dd>' +
        '</div>'+
        '<div style="width:360px;height:150px;display:' + vacationDivDisplay +
        '" id="vacationContent"><form name="savespotVacation" action="javascript:editHomeMarkerAction(\'vacation\')">' +
        '<input type="hidden" id="MemberId" name="MemberId" value="' + CURRENT_USER + '"' +
        '<dl>' +
        '<dt>' + country + ':</dt>' +
        '<dd>' + countriesSelect + '</dd>' +
        '<dt>' + city + '</dt>' +
        '<dd>' + suggestion + '</dd>';
    htmlMessage +=
       '<dt>' + desc + ':</dt><dd><textarea style="width:200px; height: 50px;" name="spotDesc" id="spotDesc">' + markerInfo.lo_desc + '</textarea></dd>' + 
       '<dd><input value="' + save + '" type="submit" /> &nbsp;<input value="' + reset +'" type="button" onclick="javascript:cancelEditingMarker(' + counter + ')"/></dd></dl>';
    htmlMessage +=  '<input type="hidden" id="counter" name="counter" value="' + spotArray.id + '"/>' +
           '<input type="hidden" id="markerId" name="markerId" value="' +markerInfo.markerId + '"/>'+
           '</form></div>';

    htmlMessage += 
        '<div style="width:360px;height:150px;display:' + homeDivDisplay + '" id="homeContent">';
        if (homeplaceHome) {
            htmlMessage += 
                '<form name="savespotHome" action="javascript:editHomeMarkerAction(\'home\')">' +
                '<input type="hidden" id="MemberId" name="MemberId" value="' + CURRENT_USER + '">' +
                '<dl>' +
                '<dt>' + country + ':</dt>' +
                '<dd>' + homeplaceHome.lo_co_name + '</dd>';
            if (homeplaceHome.lo_ci_name != '') {
                htmlMessage += '<dt>' + city + ':</dt>' +
                '<dd>' + homeplaceHome.lo_ci_name + '</dd>';
            }
            if (homeplaceHome.lo_region_name)
                htmlMessage +=
                   '<dt>' + region + ':</dt><dd>' + homeplaceHome.lo_region_name + '</dd>';
            htmlMessage +=
                '<dd><input value="' + save + '" type="submit" /> &nbsp;<input value="' + reset + '" type="button" onclick="javascript:cancelEditingMarker(' + counter + ')"/></dd></dl>' +
                '<input type="hidden" id="counter" name="counter" value="' + spotArray.id + '"/>' +
                '</form>';
        }
        else
            htmlMessage += 'Please specify your home in settings';
    htmlMessage += '</div>';
    return htmlMessage;
}

/** check if city name typed in input filed is on the list with suggestions
* @param array suggestionsList - select with suggestions
* @param string cityName - city name typed in input
*/
function checkIfCorrectCity(suggestionsList, cityName) {
    for (var i=0; i<suggestionsList.length; i++) {
        if (suggestionsList[i].text == cityName){
            return suggestionsList[i].value;
        }
    }
    return false;
}

/** this function change marker position
* @param int id - index of the marker in markers array
*/
function changeMarkerPosition(id) {
    map.closeInfoWindow();
    gmarkers[id].setLatLng(new GLatLng(gmarkers[id].lo_lat, gmarkers[id].lo_lng));
    map.setCenter(gmarkers[id].getLatLng());
    generateOnClickMessage(id);
    homeplaceLocation = 'vacation';
    homeplaceMarker = gmarkers[id];
}

/** this function save (insert or update) marker with user home location (vacation)
* @param integer id - id of the marker on the list of markers
* @param array markerResponse - ajax response with location of selected city
*/
function saveHomeplaceMarker(id, markerResponse) {
    gmarkers[id].lo_lat = markerResponse.lo_lat;
    gmarkers[id].lo_lng = markerResponse.lo_lng;
    if (!gmarkers[id].markerId)
        gmarkers[id].markerId = 0;
    
    var params = 'memberId/' + gmarkers[id].MemberId + '/markerId/' + gmarkers[id].markerId + '/markerType/' + gmarkers[id].markerType + '/City_Id/'+ gmarkers[id].lo_ci_id + '/Country_Id/' + gmarkers[id].lo_co_id + '/markerDesc/' + gmarkers[id].lo_desc; // prepare parameters to save in the database
    var fullUrl = HomeUrl + 'myprofile/SaveHomeplaceMarker/' + params;

    new Ajax.Request( fullUrl, // ajax request to myprofile controller to save the data 
        {
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "0";
                gmarkers[id].markerId = response;
                changeMarkerPosition(id);
            },
            onFailure: function(){ alert('Error'); }
        }
    );
}

/** this function returns selected city location
* @param int countryId - id of selected country
* @param int cityId - id of the city from list of suggestions
* @param int id - index of the marker in markers array
*/
function findHomeplaceLocation(countryId, cityId, id) {
    var params = 'countryId/' + countryId + '/cityId/' + cityId;
    var fullUrl = HomeUrl + 'myprofile/findLocation/' + params;
    
    new Ajax.Request(fullUrl,
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || responseNoResponse;
                var responseArray= eval("("+response+")");
                saveHomeplaceMarker(id, responseArray);
            },
            onFailure: function(){ }
        }
    );
}

/** generate message which is displayed on marker click
* @param int id - index of the marker in gmarkers array
*/
function generateOnClickMessage(id) {
    var message = '<a href="' + HomeUrl + 'countrypage/show/countrybyid/'+ gmarkers[id].lo_co_id +'">' + gmarkers[id].lo_co_name + '</a>'; // prepare info window message
    
    if(gmarkers[id].lo_ci_name) message += '<br/>' + gmarkers[id].lo_ci_name;
    if(gmarkers[id].lo_desc) message += '<br/>' + gmarkers[id].lo_desc;
    if(gmarkers[id].markerType == 'place') message += '<br/><br/><small><a href="javascript:editMarker(map, gmarkers['+ gmarkers[id].id +']);" onClick="">'+ edit_marker +'</a></small>';
    
    GEvent.addListener(gmarkers[id], "click", function() { // onclick event which open info window
          gmarkers[id].openInfoWindowHtml(message);
    });
}

/** function saves user location (home or vacation)
* @param string homeplaceLocation - 'vacation' or 'home'
*/
function editHomeMarkerAction(placeLocation) {
    var homeplaceCanBeChanged = false;

    if (placeLocation == 'vacation') {
        var homeplaceForm = document.savespotVacation;
        var id          = homeplaceForm.counter.value;
        var lo_desc     = homeplaceForm.spotDesc.value;
        var MemberId    = homeplaceForm.MemberId.value;
        var lo_co_id    = homeplaceForm.Location_CountryidMar.value;
        var lo_co_name  = homeplaceForm.Location_CountryidMar.options[homeplaceForm.Location_CountryidMar.selectedIndex].text;
        var lo_ci_name  = homeplaceForm.searchGmapMar.value;
        var lo_ci_id    = 0;
        
        
        if (lo_co_id > 0 && lo_ci_name != '') {
            if (!(lo_ci_id = checkIfCorrectCity(mySuggMarker.selectWithSuggestions, lo_ci_name)))
                lo_ci_id = 0;
            else
                homeplaceCanBeChanged = true;
        }
        else if (lo_co_id > 0) {
            lo_ci_id = 0;
            homeplaceCanBeChanged = true;
        }
        
        if (homeplaceCanBeChanged) {
            gmarkers[id].MemberId = MemberId;
            gmarkers[id].lo_desc = lo_desc;
            gmarkers[id].markerType = 'place';
            gmarkers[id].lo_co_name = lo_co_name;
            gmarkers[id].lo_co_id = lo_co_id;
            gmarkers[id].lo_ci_name = lo_ci_name;
            gmarkers[id].lo_ci_id = lo_ci_id;
            
            findHomeplaceLocation(lo_co_id, lo_ci_id, id);
        }
        
    }
    else if (placeLocation == 'home') {
        var homeplaceForm = document.savespotHome;
        var id          = homeplaceForm.counter.value;
        var MemberId    = homeplaceForm.MemberId.value;
        homeplaceLocation = 'home';

        deleteMarker(id);
        
        map.closeInfoWindow();
        gmarkers[id].setLatLng(new GLatLng(homeplaceHome.lo_lat, homeplaceHome.lo_lng));
        map.setCenter(gmarkers[id].getLatLng());
        map.addOverlay(gmarkers[id]);
        
        if (homeplaceHome.lo_desc)
            gmarkers[id].lo_desc = homeplaceHome.lo_desc;
        else
            gmarkers[id].lo_desc = '';
        if (homeplaceHome.lo_co_name)
            gmarkers[id].lo_co_name = homeplaceHome.lo_co_name;
        else
            gmarkers[id].lo_co_name = '';
        if (homeplaceHome.lo_co_id)
            gmarkers[id].lo_co_id = homeplaceHome.lo_co_id;
        else
            gmarkers[id].lo_co_id = '';
        if (homeplaceHome.lo_ci_name)
            gmarkers[id].lo_ci_name = homeplaceHome.lo_ci_name;
        else
            gmarkers[id].lo_ci_name = '';
        if (homeplaceHome.lo_ci_id)
            gmarkers[id].lo_ci_id = homeplaceHome.lo_ci_id;
        else
            gmarkers[id].lo_ci_id = '';
        if (homeplaceHome.lo_region_name)
            gmarkers[id].lo_region_name = homeplaceHome.lo_region_name;
        else
            gmarkers[id].lo_region_name = '';
        
        homeplaceMarker = Array();
        generateOnClickMessage(id);
    }
}

/*
* open info window over a marker
* @param countriesSelector list of countries
*/
GMarker.prototype.openEditMarkerWindow = function(htmlMessage, counter, spotArray) {
    var point = this.getLatLng();
    
    var washodayChecked = '';
    if (spotArray.markerType == 'washoday')
        washodayChecked = 'selected="true"'; 
    
    var wouldhodayChecked = '';
    if (spotArray.markerType == 'wouldhoday')
        wouldhodayChecked = 'selected="true"';
    
    var htmlMessage = '<div style="width:360px"><form name="savespot" action="javascript:editMarkerAction()">' +
        '<input type="hidden" id="MemberId" name="MemberId" value="'+ CURRENT_USER +'"' +
        '<dl>'+
        '<dt>'+step_two+': </dt>'+
        '<dd><select id="markerType" name="markerType">' +
        '<option value="washoday" '+washodayChecked+'>'+ my_travel +'</option>' +
        '<option value="wouldhoday" '+wouldhodayChecked+'>'+ travel_aim +'</option>';
        if (!homeplaceLocation) {
            htmlMessage += '<option value="place">'+ my_place +'</option>';
        }
        htmlMessage += '</select></dd>' +
        '<dt>'+country+':</dt>'+
        '<dd>' + spotArray.lo_co_name + '</dd>';
        if (spotArray.lo_ci_name != '') {
            htmlMessage += '<dt>'+city+':</dt>'+
            '<dd>' + spotArray.lo_ci_name + '</dd>';
        }
        if (!spotArray.lo_desc)
            spotArray.lo_desc = '';
        htmlMessage += 
        //'<dt>'+travel_type+':</dt>'+
        //'<dd>'+
        //'<input type="radio" name="markerType" value="washoday"/><img src="http://localhost/branches/communityRelaunch/httpdocs/img/icons/sun_red.png"/>'+travel_aim+'<br />'+
        //'<input type="radio" name="markerType" value="wouldhoday"/><img src="http://localhost/branches/communityRelaunch/httpdocs/img/icons/sun_blue.png"/>'+my_travel+
        //'</dd>'+
       
       '<dt>'+ desc +':</dt><dd><textarea style="width:200px; height: 50px;" name="spotDesc" id="spotDesc">'+spotArray.lo_desc+'</textarea></dd>' + 
       '<dd><input value="'+ save +'" type="submit" /><input value="'+ reset +'" type="button" onclick="javascript:cancelEditingMarker('+ counter +')"/></dd></dl>';
    htmlMessage +=  '<input type="hidden" id="counter" name="counter" value="'+ spotArray.id + '"/>' +
           //'<input type="hidden" id="lo_lat" name="lo_lat" value="'+ point.lat() +'"/>'+
           //'<input type="hidden" id="lo_lng" name="lo_lng" value="'+ point.lng() +'"/>'+
           '<input type="hidden" id="markerId" name="markerId" value="'+spotArray.markerId+'"/>'+
           //'<input type="hidden" id="lo_ci_id" name="lo_ci_id" value="'+spotArray.lo_ci_id+'"/>'+
           //'<input type="hidden" id="lo_co_id" name="lo_co_id" value="'+spotArray.lo_co_id+'"/>'+
           //'<input type="hidden" id="CountryName" name="CountryName" value="'+spotArray.lo_co_name+'"/>'+
           //'<input type="hidden" id="CityName" name="CityName" value="'+spotArray.lo_ci_name+'"/>'+
           '</form></div>';
    this.openInfoWindow(htmlMessage);
}


function editMarkerAction() {
     var id = document.savespot.counter.value;
     var lo_desc = document.savespot.spotDesc.value;
     var markerType = document.savespot.markerType.value;
     var MemberId = document.savespot.MemberId.value;
     gmarkers[id].lo_desc = lo_desc;
     gmarkers[id].markerType = markerType;

    if (markerType == 'wouldhoday')
        gmarkers[id].setImage(HomeUrl + "img/icons/sun_red.png"); // set color for toVisit place
    else if (markerType == 'washoday')
        gmarkers[id].setImage(HomeUrl + "img/icons/sun_blue.png"); // set color for visited place
    else if (markerType == 'place') {
        gmarkers[id].setImage(HomeUrl + "img/icons/sun.png"); // set color for home place
     }
     map.closeInfoWindow();
     
     var params = 'memberId/' + MemberId + '/markerId/' + gmarkers[id].markerId + '/markerType/' + gmarkers[id].markerType + '/markerDesc/' + gmarkers[id].lo_desc; // prepare parameters to save in the database
     var fullUrl = HomeUrl + 'myprofile/updateMarker/' + params;
     new Ajax.Request( fullUrl, // ajax request to myprofile controller to save the data 
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "0";
            },
            onFailure: function(){ }
        }
    );
        
    message = '<a href="' + HomeUrl + 'countrypage/show/countrybyid/'+ gmarkers[id].lo_co_id +'">' + gmarkers[id].lo_co_name + '</a>'; // prepare info window message
    if(gmarkers[id].lo_ci_name) message += '<br/>' + gmarkers[id].lo_ci_name;
    if(gmarkers[id].lo_desc) message += '<br/>' + gmarkers[id].lo_desc;
    if(id) message += '<br/><br/><small><a href="javascript:deleteMarker('+ id +');">'+ delete_marker +'</a>&nbsp;<a href="javascript:editMarker(map, gmarkers['+ id +']);">'+ edit_marker +'</a></small>';
        
    GEvent.addListener(gmarkers[id], "click", function() { // onclick event which open info window
         gmarkers[id].openInfoWindowHtml(message);
    });
    if (markerType == 'place') {
        homeplaceLocation = 'vacation';
        homeplaceMarker = gmarkers[id];
    }
}

function cancelMarker(markerId) {
    map.removeOverlay(gmarkers[markerId]); // remove temporary marker
}

function cancelEditingMarker(markerId) {
    map.closeInfoWindow();
}

/*
* zoom to a place which was entered by user in search box
*
* @param search search query
*/
function showAddress(countryId, cityId) {
    var params = 'countryId/' + countryId + '/cityId/' + cityId;
    var fullUrl = HomeUrl + 'myprofile/findLocation/' + params;
    
    new Ajax.Request(fullUrl,
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || responseNoResponse; // on success display response
                var responseArray= eval("("+response+")");
                if(response != '') addSpot(map, responseArray);
            },
            onFailure: function(){ }
        }
    )
}

/*
* zoom to a homeplace
*
* @param search search query
*/
function showHomeplace(search) {
    var params = 'query/' + search;
    new Ajax.Request(HomeUrl + 'myprofile/findLocation/' + params, // request to deleteMarker action from myprofile controller
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || responseNoResponse; // on success display response
                var responseArray= eval("("+response+")");
                //if(response != '') addMarker(responseArray, map, 'place');
            },
            onFailure: function(){ }
        }
    )
}
    
/*
* perform ajax request to delete marker given as a parameter
*
* @param marker marker object
*/
function deleteMarker(marker) {
    map.removeOverlay(gmarkers[marker]);
    var params = 'markerId/' + gmarkers[marker]['markerId']; // params needed to delete right marker
    new Ajax.Request(HomeUrl + 'myprofile/deleteMarker/' + params, // request to deleteMarker action from myprofile controller
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || responseNoResponse; // on success display response
            },
            onFailure: function(){ }
        }
    )
}

/* 
* perform ajax request to save marker with all information taken from the "savespot" form
*/
function saveMarker() {
    var id = document.savespot.counter.value;
    gmarkers[id].MemberId = document.savespot.MemberId.value;
    gmarkers[id].markerType = document.savespot.markerType.value;
    gmarkers[id].lo_ci_id = document.savespot.lo_ci_id.value;
    gmarkers[id].lo_co_id = document.savespot.lo_co_id.value;
    gmarkers[id].lo_ci_name = document.savespot.CityName.value;
    gmarkers[id].lo_co_name = document.savespot.CountryName.value;
    gmarkers[id].lo_desc = document.savespot.spotDesc.value;
     
    map.closeInfoWindow(); // close info window with a form
    
    var params = 'memberId/' + gmarkers[id].MemberId + '/markerType/' + gmarkers[id].markerType + '/City_Id/'+ gmarkers[id].lo_ci_id + '/Country_Id/' + gmarkers[id].lo_co_id + '/markerDesc/' + gmarkers[id].lo_desc; // prepare parameters to save in the database
    var fullUrl = HomeUrl + 'myprofile/saveNewMarker/' + params;
    new Ajax.Request( fullUrl, // ajax request to myprofile controller to save the data 
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "0";
                //marker.markerId = response; // save markerId from database
                gmarkers[id]['markerId'] = response;
            },
            onFailure: function(){ }
        }
    )
    
    message = '<a href="' + HomeUrl + 'countrypage/show/countrybyid/'+ gmarkers[id].lo_co_id +'">' + gmarkers[id].lo_co_name + '</a>'; // prepare info window message
    if(gmarkers[id].lo_ci_name) message += '<br/>' + gmarkers[id].lo_ci_name;
    if(gmarkers[id].lo_desc) message += '<br/>' + gmarkers[id].lo_desc;
    if(id && gmarkers[id].markerType != 'place') message += '<br/><br/><small><a href="javascript:deleteMarker('+ id +');">'+ delete_marker +'</a>&nbsp;<a href="javascript:editMarker(map, gmarkers['+ id +']);">'+ edit_marker +'</a></small>';
    else if (gmarkers[id].markerType == 'place') message += '<br/><br/><small><a href="javascript:editHomeMarkerAction(\'vacation\');">'+ edit_marker +'</a></small>';

    if (gmarkers[id].markerType == 'wouldhoday')
        gmarkers[id].setImage(HomeUrl + "img/icons/sun_red.png"); // set color for toVisit place
    else if (gmarkers[id].markerType == 'washoday'  )
        gmarkers[id].setImage(HomeUrl + "img/icons/sun_blue.png"); // set color for visited place
    else if (gmarkers[id].markerType == 'place')
        gmarkers[id].setImage(HomeUrl + "img/icons/sun.png"); // set color for visited place    
        
    GEvent.addListener(gmarkers[id], "click", function() { // onclick event which open info window
         gmarkers[id].openInfoWindowHtml(message);
    });
}

/*
* add marker to the map
*
* @param countryArray information about the country
* @map Gmap object
* @type type of a marker
*/
function addMarker (countryArray,map,type)
{
    var Icon = new GIcon();
    if (type=='toVisit' || countryArray['markertype'] == 'wouldhoday')  Icon.image = HomeUrl + "img/icons/sun_red.png"; // set color for toVisit place
    if (type=='visited' || countryArray['markertype'] == 'washoday'     )  Icon.image = HomeUrl + "img/icons/sun_blue.png"; // set color for visited place
    if (type=='place'     || countryArray['markertype'] == 'homeplace' )  Icon.image = HomeUrl + "img/icons/sun.png"; // set color for homeplace
    Icon.shadow = HomeUrl + "img/icons/sun_shadow.png"; // set shadow
    Icon.iconSize = new GSize(21, 20);  // set icon size
    Icon.shadowSize = new GSize(22, 22);  // set shadow size
    Icon.iconAnchor = new GPoint(12, 12);  // set icon anchor
    Icon.infoWindowAnchor = new GPoint(15, 5); // set info window anchor
    Icon.sunType = type; // set type of a marker
        
    var location = new GLatLng(countryArray['lo_lat'],countryArray['lo_lng']); // get location from array
    var marker = new GMarker(location,Icon); // create a marker
    marker.id = counter; // set marker id
    if (countryArray['markerid'])
        marker.markerId     = countryArray['markerid']; // set marker's database id
    marker.lo_lat       = countryArray['lo_lat'];
    marker.lo_lng       = countryArray['lo_lng'];
    marker.lo_co_id     = countryArray['lo_co_id'];
    marker.lo_co_name   = countryArray['lo_co_name'];
    marker.lo_ci_id     = countryArray['lo_ci_id'];
    marker.lo_ci_name   = countryArray['lo_ci_name'];
    if (countryArray['lo_desc'])
        marker.lo_desc      = countryArray['lo_desc'];
    marker.markerType   = countryArray['markertype'];
    
    gmarkers[counter] = marker; // add marker object into the gmarkers array
    
    htmls[counter] = '<a href="' + HomeUrl + 'countrypage/show/countrybyid/'+ marker.lo_co_id +'">' + marker.lo_co_name + '</a>'; // prepare info window message
    //htmls[counter] = countryArray['countryname']; // prepare info window message
    
    if(countryArray['lo_ci_name']) htmls[counter] += '<br/>' + countryArray['lo_ci_name'];
    if(countryArray['lo_desc']) htmls[counter] += '<br/>' + countryArray['lo_desc'];
    if(marker.markerId && type != 'place') htmls[counter] += '<br/><br/><small><a href="javascript:deleteMarker('+ marker.id +');">'+ delete_marker +'</a>&nbsp;<a href="javascript:editMarker(map, gmarkers['+ marker.id +']);">'+ edit_marker +'</a></small>';
    if(type == 'place') htmls[counter] += '<br/><br/><small><a href="javascript:editMarker(map, gmarkers['+ marker.id +']);" onClick="">'+ edit_marker +'</a></small>';
    
    GEvent.addListener(marker, "click", function() { // onclick event which open info window
          marker.openInfoWindowHtml(htmls[marker.id]);
    });
    counter++;
    
    map.addOverlay(marker); // add marker to the map
}

/* 
* edit marker infos
*
* @param map map object
* @param spotArray info about the marker
*/
function editMarker(map, spotArray) {
    if (spotArray.markerType == 'place')
        spotArray.openEditHomeMarkerWindow(counter, spotArray);
    else
        spotArray.openEditMarkerWindow('', counter, spotArray); // open message with a form
}

/* 
* add temporary marker to the map
*
* @param map map object
* @param spotArray info about a temporary marker
*/
function addSpot (map, spotArray) {
    var Icon = new GIcon();
    Icon.image = HomeUrl + "img/icons/sun_green.png"; // set icon image
    Icon.shadow = HomeUrl + "img/icons/sun_shadow.png"; // set shadow
    Icon.iconSize = new GSize(21, 20);  // set icon size
    Icon.shadowSize = new GSize(22, 22);  // set shadow size
    Icon.iconAnchor = new GPoint(10, 10);  // set icon anchor
    Icon.infoWindowAnchor = new GPoint(15, 5); // set info window anchor
    
    var location = new GLatLng(spotArray.lo_lat, spotArray.lo_lng);
    var marker= new GMarker(location, Icon); // create marker
    marker.type = "spot"; // set marker type
    marker.id = counter;
    gmarkers[counter] = marker; // add marker object into the gmarkers array
    counter++;
    
    map.addOverlay(marker); // add marker to the map
    if(marker.type =="spot") { // if marker is temporary
        marker.openSaveMarkerWindow('', counter, spotArray); // open message with a form
    }        
    GEvent.addListener(marker, "click", function() { // onclick event which open info window
          marker.openSaveMarkerWindow('', counter, spotArray);
    });
}


/*
* perform ajax request to remove information from interests
*/
function removeInterest (name, type, markerId) {
    map.removeOverlay(gmarkers[markerId]);
    var params = 'name/' + name + '/type/' + type ; // prepare parameters to remove from the database
    new Ajax.Request(HomeUrl + 'myprofile/deleteInterest/' + params, // ajax request to myprofile controller to remove the data 
        { 
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText || "0";
            },
            onFailure: function(){ }
        }
    )
}
