/**
 * Main map functions
 */
MAPUTILS  = function () {
    
    //global map object
    MAPUTILS.prototype.map;
    MAPUTILS.prototype.counter = 0; 
    
    //default map settings
    MAPUTILS.prototype.currentLat = 45.383;
    MAPUTILS.prototype.currentLng = -75.677;
    MAPUTILS.prototype.currentZoom = 0;
  
    MAPUTILS.prototype.initMap = function() {
        
        //check if map object has been loaded or created
        try{
            document.getElementById('map').innerHTML;
        }catch(e){
            if (this.counter > 60) { 
                alert('Can\'t load map! Can\'t find map object!');
            } else { 
                setTimeout("maputil.initMap()", 1000);                 
            } 
            return false; 
        }
           
        //If gmaps main.js didn't load try to call init again after 60 tries we give up
        if (typeof GMap != "function") { 
            if (this.counter > 60) { 
                document.getElementById('map').innerHTML = 'Can\'t load map! Gmap server timeout! ';
            } else { 
                setTimeout("maputil.initMap()", 1000); 
            } 
            this.counter++; 
            return false; 
        }
        
        //if browser not compatible update map tag with error msg
        if (!GBrowserIsCompatible()) { 
            document.getElementById('map').innerHTML = 'Can\'t load map because your browser is too old!';
            return false;
        }
    
        //init gmaps object
        this.map = new GMap2(document.getElementById("map"));
        
                    
        //set center of the map
        this.map.setCenter(new GLatLng(this.currentLat, this.currentLng), this.currentZoom);      
        
        //add controls and mouse functions
        this.map.enableDoubleClickZoom();
        this.map.enableContinuousZoom();
        this.map.enableScrollWheelZoom();
        //this.map.addControl(new GOverviewMapControl (/*new GSize(200,180)*/));                        
        
        this.map.addControl(new GMenuMapTypeControl());
        this.map.addControl(new GLargeMapControl3D());
        
        
        //add zoomend event
        GEvent.addListener(maputil.map, "zoomend", function() {  
            marker.clearMarkers();               
            marker.processMarkeres();        
            marker.hidePointLabelElement();              
            marker.hideBubble();
        });
                
        GEvent.addListener(maputil.map, "drag", function() {  
            marker.hidePointLabelElement();    
            marker.hideBubble();
        });
        
        GEvent.addListener(maputil.map, "click", function() {              
            marker.hideBubble();
        });
                
        //call markers processMarkeres method which will show the markes on the map
        marker.processMarkeres();
        
        //if zoom is 0 try marker bounds
        if(this.currentZoom == 0) maputil.map.setCenter(marker.getMarkerCenter(),marker.getZoomLevel());
        var decodeUrl = window.location.hash.substring(1).split('=');
        if(parseInt(decodeUrl[1])) marker.infoWindow(maputil.map.getCenter().y, maputil.map.getCenter().x,parseInt(decodeUrl[1]));
        
    }
   
}

/**
  * Marker class. Handle markers and lables
 */
MARKERS  = function () {
    //this will store the markers
    MARKERS.prototype.markersDb = new Array();        
    
    //define icons path
    MARKERS.prototype.markerIconsPath = '/imgs/icons/';  
    
    //store bounds
    MARKERS.prototype.bounds = new GLatLngBounds();  
    
        
    MARKERS.prototype.showPointLabel = function (anchor){
        marker.showLabel(anchor.id);
        anchor.style.zIndex=4;            
        anchor.style.color = '#ecf73a';
        return false;
    }
    
    MARKERS.prototype.hidePointLabel = function (anchor){
        anchor.style.zIndex=1; 
        anchor.style.color = '#fff';
        this.hidePointLabelElement();
        return false;
    }
    
    MARKERS.prototype.hidePointLabelElement = function (){
        try{
            document.getElementById("infoLabel").style.display = 'none'; 
        }catch(e){}
    }
    
    MARKERS.prototype.processMarkeres = function(){   
        var pointsHtml = '';
        //go through markersDb and build up a layer for the map
        for(i=0;i<this.markersDb.length;i++){        
             p = this.markersDb[i];
            //calculate marker positions in pixel
            var pos = maputil.map.fromLatLngToDivPixel(new GLatLng( p[1],  p[2]));
            //extends bounds
            this.bounds.extend(new GLatLng( p[1], p[2]));
            
            //set offset params to center marker to position
            var x = parseInt(pos.x) - 14;
            var y = parseInt(pos.y) - 39;                           
            
            //create a ne marker achor
            pointsHtml += '<a href="./check-in-deal/'+p[0]+'/" class="marker" ';
           // pointsHtml += 'onclick="marker.infoWindow('+p[1]+','+p[2]+','+p[0]+')" ';  
            
            //set style  and icon
            pointsHtml += 'style="';                          
            pointsHtml += "background:url('" + this.markerIconsPath + p[3] + '.png' + "') no-repeat;"; 
            
            pointsHtml += 'top:' + y + 'px;left:' + x + 'px;" ';
            pointsHtml += 'id="marker_' + p[0] + '" ';
            
            //hover text
            pointsHtml += "rel='" + p[4] + "' ";
                            
            //add events to markers
            pointsHtml += 'onmouseover="marker.showPointLabel(this)" ';
            pointsHtml += 'onmouseout="marker.hidePointLabel(this)" ';
            pointsHtml += 'onclick="marker.showBubble(this)"';            
            pointsHtml += '></a>';            
            
        }  
        
        //insert marker html to mappane
        maputil.map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).innerHTML = pointsHtml;
        //console.log(pointsHtml);
    }

    
    MARKERS.prototype.clearMarkers = function(){           
        var element = maputil.map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE);  
        while (element.firstChild) {
            element.removeChild(element.firstChild);        
        }                  
    }
    
    MARKERS.prototype.showLabel = function (markerObj){              
        //try to get label element if not in the body add it
        try{
            document.getElementById('infoLabel').innerHTML;
            var label = document.getElementById('infoLabel');        
        }catch(e){
            var label = document.createElement('div');
            label.setAttribute('id','infoLabel');             
            label.onclick = function(){marker.hidePointLabelElement()}
            document.body.appendChild(label);            
        }
                
        //calculate absolute postion of the label
        var m = document.getElementById(markerObj); 
        var mapPos = this.findPos(document.getElementById('map'));
        var lY = (maputil.map.getSize().height - (maputil.map.getSize().height/2 + maputil.map.fromLatLngToDivPixel(maputil.map.getCenter()).y - parseInt(m.style.top))) + mapPos[1] ;
        var lX = (maputil.map.getSize().width - (maputil.map.getSize().width/2 + maputil.map.fromLatLngToDivPixel(maputil.map.getCenter()).x - parseInt(m.style.left))) + mapPos[0] ;
        
               
        //check if label in map
        if(lY<mapPos[1]+20) return false;
        if(lX<mapPos[0]+20) return false;        
        if(lY>(document.getElementById('map').offsetHeight+mapPos[1])) return false;
        if(lX>(document.getElementById('map').offsetWidth+mapPos[0])) return false;
        
        
        //show label
        label.style.display='block';
        
        //set attributes
        //if you need to move the label offset you can change it here
        label.style.top = (lY - 16)  + 'px';
        label.style.left = (lX + 22) + 'px';    
        label.innerHTML = '<span class="mapBubbleTxt">' + m.rel + '</span><span class="mapBubbleEnd"></span>';         
    }
    
    MARKERS.prototype.showBubble = function (m){     
         
        var label = document.getElementById('map_bubble');        
        //show label
        label.style.display='block';        
        
        //calculate absolute postion of the label
        //var m = document.getElementById(markerObj); 
        var mapPos = this.findPos(document.getElementById('map'));
        var lY = (maputil.map.getSize().height - (maputil.map.getSize().height/2 + maputil.map.fromLatLngToDivPixel(maputil.map.getCenter()).y - parseInt(m.style.top))) + mapPos[1] ;
        var lX = (maputil.map.getSize().width - (maputil.map.getSize().width/2 + maputil.map.fromLatLngToDivPixel(maputil.map.getCenter()).x - parseInt(m.style.left))) + mapPos[0] ;
        
        
        //set attributes
        //if you need to move the label offset you can change it here
        label.style.top = (lY - 145)  + 'px';
        label.style.left = (lX - 115) + 'px';    
        label.innerHTML = document.getElementById("details_" + m.id ).innerHTML;       
    }
    
    MARKERS.prototype.hideBubble = function (){ 
        try{
            document.getElementById('map_bubble').style.display = 'none'; 
            marker.currentProperty = 0;
        }catch(e){}
    }

    MARKERS.prototype.findPos = function(obj) {        
        if (obj.offsetParent) {
            var curleft = obj.offsetLeft
            var curtop = obj.offsetTop
            while (obj = obj.offsetParent) {                    
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }
            return [curleft,curtop];
        }    
    }
    
    MARKERS.prototype.getZoomLevel = function() {
        return maputil.map.getBoundsZoomLevel(marker.bounds);
    }
    
    MARKERS.prototype.getMarkerCenter = function() {
        return marker.bounds.getCenter();
    }    
    
    MARKERS.prototype.infoWindow = function(lat,lng,pid){ 
            maputil.map.openInfoWindow(new GLatLng(lat,lng), '<div id="infoWin">'+document.getElementById("storeitem_"+pid).innerHTML+'</div>');
    }
    

}

//create markers class
var marker = new MARKERS;
//create maputil class
var maputil = new MAPUTILS;




