/*******************************************************************************************
 Common Google Maps file v.2.2
 License: proprietary license product, please read license.txt before using this product.
 Author: Trofimov Alexander (kolimarfey@gmail.com)
*******************************************************************************************/
function GMK (id, lat, lon, zoom, type)
{
    this._iSaveLocationId = 0; // override this
    this._sLoadingId = '';

    this._iId = id;
    this._fLat = lat.length ? parseFloat (lat) : 0;
    this._fLon = lon.length ? parseFloat (lon) : 0;
    this._iZoom = zoom.length ? parseInt (zoom) : 1;

    this._map = null;
    this._markers = [];
    this._markerClusterer = null;
    this._PopupMarker = null;
    this._MaxContentTab = null;

    this._iMapType = type.length ? parseInt(type) : 0;
    this._iMapControl = 1;
    this._isTypeControl = true;
    this._isScaleControl = true;
    this._isOverviewControl = true;
    this._isDragable = true;
    this._sCustomType = 'all';

    this._iSaveMapType = this._iMapType;
    this._iSaveZoom = this._iZoom;
    this._fSaveLat = this._fSaveLng = 0;

    this._iClickable = 0;
    this._PlaceID = 0;

    this._Filter_Online = 0;
    this._Filter_StudiedLanguage = '';
    this._Filter_LanguageLevel = 0;
    this._Filter_AgeLevel = 0;
    this._Filter_ClassSize = '';

    this.sLangPositionSaved = 'Location has been succesfully saved';
    this.sLangPositionSaveFailed = 'Location saving failed';
    this.sLangGeocodeFailed = "Can not geocode following location:\n";
    this.sLangSelectLocation = "Please select location first";

    this.sActionsFile = 'override this';
    this.sActionShowLocations = 'override this';
}

GMK.prototype.init = function ()
{
    //google.load("maps", "2.x");

    var $this = this;

    if (undefined == this._Filter_Online) this._Filter_Online = 0;
    if (undefined == this._Filter_StudiedLanguage) this._Filter_StudiedLanguage = '';
    if (undefined == this._Filter_LanguageLevel) this._Filter_LanguageLevel = 0;
    if (undefined == this._Filter_AgeLevel) this._Filter_AgeLevel = 0;
    if (undefined == this._Filter_ClassSize) this._Filter_ClassSize = '';
    if (null != document.getElementById('filter_ClassSize'))
    {
        document.getElementById('filter_ClassSize').selectedIndex = 0;
        document.getElementById('filter_AgeLevel').selectedIndex = 0;
        document.getElementById('filter_LanguageLevel').selectedIndex = 0;
        document.getElementById('filter_StudiedLanguage').selectedIndex = 0;
        document.getElementById('filter_Online').checked = false;
    }


    var h = function ()
    {
        if (!GBrowserIsCompatible()) {
            alert ("Sorry your browser is incompatible with Google Maps");
            return;
        }

        $this.preload();

        //loadJS("./places/application/gmk/markerclusterer.js", "iMarkerClusterer");
        //loadJS("./places/application/gmk/popupmarker.js", "iPopupMarker");
        //loadJS("./places/application/gmk/tabbedmaxcontent.js", "iTabbedMaxContent");

        glGMK_MAP = new GMap2(document.getElementById($this._iId));
        $this._map = glGMK_MAP;

        $this._iMapControl = parseInt($this._iMapControl);
        switch ($this._iMapControl)
        {
            case 2: $this._map.addControl(new GLargeMapControl()); break;
            case 1: $this._map.addControl(new GSmallMapControl()); break;
        }

        if ($this._isTypeControl) $this._map.addControl(new GMapTypeControl());
        if ($this._isScaleControl) $this._map.addControl(new GScaleControl());
        if ($this._isOverviewControl) $this._map.addControl(new GOverviewMapControl ());

        $this._map.setCenter(new GLatLng($this._fLat, $this._fLon), $this._iZoom);

        if (!$this._isDragable)
            $this._map.disableDragging();


        switch ($this._iMapType)
        {
            case 1: $this._map.setMapType(G_SATELLITE_MAP); break;
            case 2: $this._map.setMapType(G_HYBRID_MAP); break;
            default: $this._map.setMapType(G_NORMAL_MAP); break;
        }

        if (0 == $this._iClickable || undefined == $this._iClickable)
            $this.showLocations ();

        $this._map._gmk = $this;

        if (0 == $this._iClickable || undefined == $this._iClickable)
        GEvent.addListener($this._map, "dragend", function() {
            this._gmk.showLocations();
        });

        if (0 == $this._iClickable || undefined == $this._iClickable)
        GEvent.addListener($this._map, "zoomend", function(oldLevel,  newLevel) {
            if (newLevel < oldLevel)
                this._gmk.showLocations();
        });

        if (1 == $this._iClickable)
            $this.initClickable();

        $this.onload();
    }

    //google.setOnLoadCallback(h);
    h();

}

GMK.prototype.saveLocation = function ()
{
    var oPos = this._map.getCenter();
    this.saveLocationFull ('save_location', "&id=" + this.getLocationId(), oPos.lat(), oPos.lng());
}

GMK.prototype.saveLocationFull = function (sAction, sParams, fLat, fLng)
{
    var $this = this;
    var request = GXmlHttp.create();
    var iMapType = 0;
    var fZoom = this._map.getZoom();
    switch (this._map.getCurrentMapType())
    {
        case G_SATELLITE_MAP: iMapType = 1; break;
        case G_HYBRID_MAP: iMapType = 2; break;
    };

    if (undefined == sParams) sParams = '';

    if (undefined == fLat) fLat = this._fSaveLat;
    if (undefined == fLng) fLng = this._fSaveLng;

    if ('save_location' != sAction && ((undefined == fLat || undefined == fLng) || (0 == fLat && 0 == fLng)))
    {
        alert (this.sLangSelectLocation);
        return;
    }

    if (!this.onsavelocation (fLat, fLng, fZoom, iMapType, sParams)) return false;

    request.open("GET", this.sActionsFile + "?action=" + sAction + "&lat=" + fLat + "&lng=" + fLng + "&zoom=" + fZoom + "&type=" + iMapType + sParams, true);

    request.onreadystatechange = function()
    {
        if (request.readyState == 4)
        {
            if (request.responseText == '<ret>1</ret>')
            {
                alert ($this.sLangPositionSaved);
                $this.onsavelocationsuccess (fLat, fLng, fZoom, iMapType, sParams);
            }
            else
            {
                alert ($this.sLangPositionSaveFailed);
                $this.onsavelocationfailed (fLat, fLng, fZoom, iMapType, sParams);
            }
        }
    }

    request.send(null);
}

GMK.prototype.min = function (x, y)
{
    return x < y ? x : y;
}

GMK.prototype.max = function (x, y)
{
    return x > y ? x : y;
}

GMK.prototype.showLocations = function ()
{
    var bounds = this._map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var span = bounds.toSpan();
    var request = GXmlHttp.create();
    var $this = this;

    if (!this.onshowlocationsbegin(southWest, northEast, span)) return;

    this._map.clearOverlays();

    var minLat = southWest.lat() <  northEast.lat() ? southWest.lat() : northEast.lat();
    var maxLat = minLat + ( southWest.lat() <  northEast.lat() ? span.lat() : -span.lat() );

    var minLng = southWest.lng() <  northEast.lng() || minLat < 0 ? southWest.lng() : northEast.lng();
    var maxLng = minLng + ( southWest.lng() <  northEast.lng() || minLat < 0 ? span.lng() : -span.lng() );
    request.open("GET", this.sActionsFile + "?action=" + this.sActionShowLocations + "&type="+this._sCustomType+"&minLat=" + this.min(minLat,maxLat) + "&maxLat=" + this.max(minLat,maxLat) + "&minLng=" + this.min(minLng,maxLng) + "&maxLng=" + this.max(minLng,maxLng) +
            "&fOnline=" + this._Filter_Online + "&fStudiedLang=" + this._Filter_StudiedLanguage + "&fLangLevel=" + this._Filter_LanguageLevel + "&fAgeLevel=" + this._Filter_AgeLevel + "&fClassSize=" + this._Filter_ClassSize, true);

    request.onreadystatechange = function()
    {
        if (request.readyState == 4)
        {
            var markers = [];

            var xml = GXml.parse(request.responseText);
            var aProfiles = xml.documentElement.getElementsByTagName("loc");
            //alert(dump(xml));
            var icount = aProfiles.length;
            for (var i = 0; i < icount; i++)
            {
                var point = new GLatLng(parseFloat(aProfiles[i].getAttribute("lat")), parseFloat(aProfiles[i].getAttribute("lng")));
                var pid = parseInt(aProfiles[i].getAttribute("pid"));
                var tabs = [];
                var tabindex = 0;

                var x = aProfiles[i].childNodes.length;
                var f_child = aProfiles[i].firstChild;
                for (var j=0; j < x;j++)
                {
                    if (f_child.nodeType==1)
                    {
                        switch (f_child.nodeName)
                        {
                            case "groups":
                                var y = f_child.childNodes.length;
                                var s_child = f_child.firstChild;
                                for (var l=0; l < y;l++)
                                {
                                    if (s_child.nodeType==1)
                                    {
                                        var cData = s_child.textContent ? s_child.textContent : s_child.nodeValue;
                                        if (null == cData) cData = s_child.firstChild.nodeValue;
                                        var tab_title = tabindex + 1;
                                        tabs.push(new MaxContentTab("Class " + tab_title, cData));
                                        tabindex++;
                                    }
                                    s_child = s_child.nextSibling;
                                }

                            break;
                            case "info":
                                var sData = f_child.textContent ? f_child.textContent : f_child.nodeValue;
                                if (null == sData) sData = f_child.firstChild.nodeValue;
                            break;
                        }
                    }
                    f_child = f_child.nextSibling;
                }
                markers.push($this.createMarker2(point, sData, tabs));
            }
            $this._markers = markers;
            $this.refreshMap();
            $this.loading(0);
            $this.onshowlocations(aProfiles);
        }
    }
    this.loading(1);
    request.send(null);
}

GMK.prototype.refreshMap = function () {
    var $this = this;

    if ($this._markerClusterer != null) {
        $this._markerClusterer.clearMarkers();
    //} else {
        //loadJS("./places/application/gmk/markerclusterer.js", "iMarkerClusterer");
    }
    var mcOptions = { gridSize: 40};

    markerClusterer = new MarkerClusterer($this._map, $this._markers, mcOptions);
    $this._markerClusterer = markerClusterer;
}

GMK.prototype.createMarker = function (point, html)
{
    var $this = this;
    var marker = new GMarker(point);
    if (html.length)
    GEvent.addListener(marker, "click", function() { if (!$this.onshowinfowindow(marker, html)) return; marker.openInfoWindowHtml(html); });
    return marker;
}

GMK.prototype.createMarker2 = function (point, html, tabs)
{
    var $this = this;
    var marker = new GMarker(point);

    if (html.length)
    GEvent.addListener(marker, "click", function()
    {
        var regular = html + '<a href="javascript:void(0)" onclick="javascript:window.glGMKPlaces.getMap().getInfoWindow().maximize()">more info.. </a>'
        var summary = html + '<a href="javascript:void(0)" onclick="javascript:window.glGMKPlaces.getMap().getInfoWindow().restore()">less info.. </a>';
        marker.openMaxContentTabsHtml($this._map, regular, summary, tabs, {
            maximized: false,
            maxTitle: "More Info",
            selectedTab: 0,
            style: {
                tabOff: {
                      backgroundColor: '#CCCCFF'
                }
            }
        });
    });
    return marker;
}

GMK.prototype.setMapType = function (iMapType)
{
    this._iMapType = iMapType;
}

GMK.prototype.setMapControl = function (iMapControl)
{
    this._iMapControl = iMapControl;
}

GMK.prototype.setTypeControl = function (isTypeControl)
{
    this._isTypeControl = isTypeControl == 'on' ? true : false;
}

GMK.prototype.setScaleControl = function (isScaleControl)
{
    this._isScaleControl = isScaleControl == 'on' ? true : false;
}

GMK.prototype.setOverviewControl = function (isOverviewControl)
{
    this._isOverviewControl = isOverviewControl == 'on' ? true : false;
}

GMK.prototype.setDragable = function (isDragable)
{
    this._isDragable = isDragable == 'on' ? true : false;
}

GMK.prototype.setCustomType = function (s)
{
    this._sCustomType = s;
}

GMK.prototype.setLocationId = function (i)
{
    this._iSaveLocationId = i;
}

GMK.prototype.getLocationId = function ()
{
    return this._iSaveLocationId;
}

GMK.prototype.setLoadingId = function (sId)
{
    this._sLoadingId = sId;
}

GMK.prototype.loading = function (bShow)
{
    var e = document.getElementById(this._sLoadingId);
    if (!e) return;
    e.style.display = bShow ? 'block' : 'none';
}

function gmk_move_prev (id)
{
    var iCurrent = parseInt(document.getElementById(id).innerHTML);
    if (!document.getElementById(id+(iCurrent-1))) return;
    document.getElementById(id+iCurrent).style.display = 'none';
    --iCurrent;
    document.getElementById(id+iCurrent).style.display = 'block';
    document.getElementById(id).innerHTML = iCurrent;
}

function gmk_move_next (id)
{
    var iCurrent = parseInt(document.getElementById(id).innerHTML);
    if (!document.getElementById(id+(iCurrent+1))) return;
    document.getElementById(id+iCurrent).style.display = 'none';
    ++iCurrent;
    document.getElementById(id+iCurrent).style.display = 'block';
    document.getElementById(id).innerHTML = iCurrent;
}

GMK.prototype.setClickable = function ()
{
    this._iClickable = 1;
}

GMK.prototype.initClickable = function ()
{
        var $this = this;

        var hh = function(marker, point)
        {
            var iMapType = 0;
            switch ($this._map.getCurrentMapType())
            {
                case G_SATELLITE_MAP: iMapType = 1; break;
                case G_HYBRID_MAP: iMapType = 2; break;
            };
            if (!$this.onsavemaptypezoombefore (iMapType, $this._map.getZoom())) return;
            $this._iSaveMapType = iMapType;
            $this._iSaveZoom = $this._map.getZoom();
            $this.onsavemaptypezoomafter (iMapType, $this._map.getZoom());
        };

        var h = function(marker, point)
        {
            if (!point) return;
            if (!$this.onclickbefore(marker, point)) return;
            $this._fSaveLat = point.lat();
            $this._fSaveLng = point.lng();
            $this._map.clearOverlays();
            $this._map.addOverlay($this.createMarker(point, ''));
            $this.onclickafter(marker, point);
        };

        GEvent.addListener(this._map, "click", h);
        GEvent.addListener(this._map, "zoomend", hh);
        GEvent.addListener(this._map, "maptypechanged", hh);


        if (this._fLat != 0 && this._fLon != 0)
        {
            var point = new GLatLng(this._fLat, this._fLon);
            this._map.clearOverlays();
            this._map.addOverlay(this.createMarker(point, ''));
            this._fSaveLat = this._fLat;
            this._fSaveLng = this._fLng;
        }
}

GMK.prototype.findLocation = function (sAddress)
{
    if (undefined == this._geocoder)
        this._geocoder = new GClientGeocoder();

    this.onfindlocation (sAddress);

    $this = this;
    var h = function (response)
    {
        if (!response || 200 != response.Status.code)
        {
            //alert ($this.sLangGeocodeFailed + sAddress);
            $this.onfindlocationfailed (response, sAddress);
            return;
        }

        if (!$this.onfindlocationsuccess (response, sAddress)) return;

          var place = response.Placemark[0];
          var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

          $this._map.setCenter(point, 6);
        $this._map.clearOverlays();
        $this._map.addOverlay($this.createMarker(point, ''));

        $this._fSaveLat = point.lat();
        $this._fSaveLng = point.lng();
        $this._iSaveMapType = 6;

        $this.onfindlocationsuccesscomplete (response, sAddress);
    }

    this._geocoder.getLocations(sAddress, h);
}

GMK.prototype.preload = function ()
{

}

GMK.prototype.onload = function ()
{

}

GMK.prototype.onshowlocations = function (aProfiles)
{

}

GMK.prototype.onshowlocationsbegin = function (southWest, northEast, span)
{
    return true;
}

GMK.prototype.onshowinfowindow = function (marker, html)
{
    return true;
}

GMK.prototype.onclickbefore = function (market, point)
{
    return true;
}

GMK.prototype.onclickafter = function (market, point)
{

//alert('palce id is  '+this._PlaceID);
     document.getElementById('gmk_lat').value = this._fSaveLat;
    document.getElementById('gmk_lng').value = this._fSaveLng;
     new Ajax.Request("saveGMap.php", {
                        method: "post",

                        parameters: { gmk_lat: this._fSaveLat,gmk_lng: this._fSaveLng, place_ID: this._PlaceID}
                    });

}

GMK.prototype.onsavemaptypezoombefore = function (iMapType, fZoom)
{
    return true;
}

GMK.prototype.onsavemaptypezoomafter = function (iMapType, fZoom)
{

}

GMK.prototype.onsavelocation = function (fLat, fLng, fZoom, iMapType, sParams)
{
    return true;
}

GMK.prototype.onsavelocationsuccess = function (fLat, fLng, fZoom, iMapType, sParams)
{

}

GMK.prototype.onsavelocationfailed = function (fLat, fLng, fZoom, iMapType, sParams)
{

}

GMK.prototype.onfindlocation = function (sAddress)
{

}

GMK.prototype.onfindlocationfailed = function (response, sAddress)
{

}

GMK.prototype.onfindlocationsuccess = function (response, sAddress)
{
    return true;
}

GMK.prototype.onfindlocationsuccesscomplete = function (response, sAddress)
{
    alert(document.getElementById('gmk_lat').value);
     document.getElementById('gmk_lat').value = this._fSaveLat;
    document.getElementById('gmk_lng').value = this._fSaveLng;
}

GMK.prototype.getMap = function ()
{
    return this._map;
}

GMK.prototype.setFilterClassSize = function (value)
{
    this._Filter_ClassSize = value;
    this.showLocations ();
}

GMK.prototype.setFilterAgeLevel = function (value)
{
    this._Filter_AgeLevel = value;
    this.showLocations ();
}

GMK.prototype.setFilterLanguageLevel = function (value)
{
    this._Filter_LanguageLevel = value;
    this.showLocations ();
}

GMK.prototype.setFilterStudiedLanguage = function (value)
{
    this._Filter_StudiedLanguage = value;
    this.showLocations ();
}

GMK.prototype.setFilterOnline = function (value)
{
    this._Filter_Online = value;
    this.showLocations ();
}

function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];

  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
