/**
 * Main map functions
 *  Author: Peter Gyorffy
 */
MAPUTILS  = function () {
    
    //global map object
    MAPUTILS.prototype.map;
    MAPUTILS.prototype.counter = 0;
    
    //default map settings
    MAPUTILS.prototype.currentLat =  39.0;
    MAPUTILS.prototype.currentLng = -100.0;
    MAPUTILS.prototype.currentZoom = 4;
    
    MAPUTILS.prototype.mapSizeW = 500;
    MAPUTILS.prototype.mapSizeH = 500;
    
    
    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 or key is invalid!';
            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);  
        //this.map.setMapType(G_HYBRID_MAP);        
        
        //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 GLargeMapControl());    //zoom and pan       
        //this.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(60,6))); //Map/Sat/hybrid                 
        // Add the Terrain Map Type
        this.map.addMapType(G_PHYSICAL_MAP);
        // Create a Hierercical map type control
        var hierarchy = new GHierarchicalMapTypeControl();
        // make Google Satellite Hybrid be the satellite default
        hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, null, true);
        // add that control to the map
        this.map.addControl(hierarchy, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(6,6)));

        //this.map.addControl(new this.MapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(6, 6)));//add button
        
        
        var decodeUrl = window.location.hash.substring(1).split('=');
        if(decodeUrl.length>2){
             if(parseInt(decodeUrl[1])) this.currentLat = parseInt(decodeUrl[1]) / 1000000;    
             if(parseInt(decodeUrl[2])) this.currentLng = parseInt(decodeUrl[2]) / 1000000;    
             if(parseInt(decodeUrl[3])) this.currentZoom = parseInt(decodeUrl[3]);
             maputil.map.setCenter(new GLatLng(this.currentLat, this.currentLng), this.currentZoom);      
         }

        GEvent.addListener(maputil.map, "dragend", function() {                      
             maputil.setSiteUrl();
        });
    	
    	GEvent.addListener(maputil.map, "zoomend", function() {                      
            maputil.setSiteUrl();
            marker.clearMarkers();               
            marker.getMarkers(1);
        });
        
        marker.getMarkers(1);
        
        this.map.openInfoWindow(this.map.getCenter(), '<div id="infoWin"><b>Welcome to PizzaShare.com,</b><br /><br />Type in the name and location of your favorite pizza place and click ok.<br /> Now you can add comments about your favorite places using your facebook login.<br /> Sign up for the newsletter to receive the best pizza newsletter that has ever been made. <br />As always leave some feedback on ways to improve the site.<br /><br />Mike</div>');
    }
    
    MAPUTILS.prototype.MapControl = function(){}
    
    try{
        MAPUTILS.prototype.MapControl.prototype = new GControl();
    }catch(e){}
    
    MAPUTILS.prototype.MapControl.prototype.initialize = function(map) {        
        var button =  document.createElement("button");               
        maputil.map.getContainer().appendChild(button);
        button.style.display = 'block';
        button.style.width = '50px';
        button.style.height = '19px';
        button.style.fontSize = '11px';
        button.style.background = '#FF5A00';        
        button.innerHTML = 'Add';
        button.onclick = function(){}
        return button;
    }

    MAPUTILS.prototype.setMapSize = function (){
        document.getElementById("map").style.width = this.mapSizeW + 'px';
        document.getElementById("map").style.height = this.mapSizeH + 'px';
    }
    
    MAPUTILS.prototype.lookUpAddress = function(latlng){  
            geocoder = new GClientGeocoder();
            geocoder.getLocations(latlng, function(addresses) {
                if(addresses.Status.code != 200) {
                    //alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
                    //latlng.toUrlValue();
                } else { 
                    var result = addresses.Placemark[0];                
                    //var street = result.address.split(',');
                    document.getElementById("mapaddress").value=result.address ; 
                   //document.getElementById("mapcity").value=street[1] ;                   
                }
            });            
        }

       MAPUTILS.prototype.searchAddress = function(str){  
            geocoder = new GClientGeocoder();
            geocoder.getLocations(str, function(addresses) {
                if(addresses.Status.code != 200) {
                    alert("Geocoder failed to find an address for " + str);
                    //latlng.toUrlValue();
                } else { 
                    var result = addresses.Placemark[0];                
                    point = new GLatLng(result.Point.coordinates[1], result.Point.coordinates[0]);
                    maputil.map.setCenter(point);
                    //document.getElementById('latbox').value = point.lat();
                    //document.getElementById('lonbox').value = point.lng();  
                }
            });  
            return false;
        }

	MAPUTILS.prototype.setSiteUrl = function(){              
        	var center = maputil.map.getCenter(); 
        	maputil.mapLink = 'lat=' + Math.round(center.y*1000000)  + '|lng=' + Math.round(center.x*1000000) + '|zoom=' + maputil.map.getZoom();
        window.location = window.location.pathname + '#' +  maputil.mapLink;
	}

}

MARKERS  = function () {
    //this will store the markers
    MARKERS.prototype.markersDb = new Array();        
    
    //store circles
    MARKERS.prototype.markersDb2 = new Array();        
    
    //define icons path
    MARKERS.prototype.markerIconsPath = 'imgs/';  
    
    //store bounds
    //MARKERS.prototype.bounds = new GLatLngBounds();      

    MARKERS.prototype.showPointLabel = function (anchor){
        marker.showLabel(anchor.id);
        anchor.style.zIndex=4;                    
        return false;
    }
    
    MARKERS.prototype.hidePointLabel = function (anchor){
        anchor.style.zIndex=1;         
        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++) if(this.markersDb[i].length>5){        
            p = this.markersDb[i].split("\|");
            //console.log(p[1] +' '+p[2]);
            //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) - 8;
            var y = parseInt(pos.y) - 25;                           
            
            //create a ne marker achor
            pointsHtml += '<a href="javascript:void(0)" '; 
            
            //set style  and icon
            pointsHtml += 'style="height:26px;width:20px;position:absolute;z-index:1;';                         
            pointsHtml += "background:url('" + this.markerIconsPath + 'marker.png' + "') no-repeat;";              
            pointsHtml += 'top:' + y + 'px;left:' + x + 'px;" ';
            pointsHtml += 'id="marker_' + p[0] + '" ';
            
            //hover text
            pointsHtml += "rel='" + p[3] + ' ' + p[4] + "' ";
                            
            //add events to markers
            pointsHtml += 'onmouseover="marker.showPointLabel(this)" ';
            pointsHtml += 'onmouseout="marker.hidePointLabel(this)" ';
           // pointsHtml += 'onclick="marker.showBubble(this)"';            
            pointsHtml += 'onclick="marker.infoWindow('+p[1]+','+p[2]+',\''+escape(p[3])+'\')"'; 
            pointsHtml += '></a>';            
            
        }  
        
        for(i=0;i<this.markersDb2.length;i++) if(this.markersDb2[i].length>5){        
            p = this.markersDb2[i].split("\|");
            //console.log(p[1] +' '+p[2]);
            //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) - (5*p[3])-3;
            var y = parseInt(pos.y) - (5*p[3])-3;                           
            
            //create a ne marker achor
            pointsHtml += '<a href="javascript:void(0)"'; 
            
            //set style  and icon
            pointsHtml += 'style="height:'+((10*p[3])/2+15)+'px;width:'+((10*p[3])/2+15)+'px;position:absolute;z-index:0;';                          
            pointsHtml += "background:url('" + this.markerIconsPath + 'markers/' + p[3]+ '.png' + "') no-repeat center;";              
            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.infoWindow('+p[1]+','+p[2]+',\''+escape(p[4])+'\')"';            
            pointsHtml += '></a>';            
            
        }  
        
        
        
        //insert marker html to mappane
        //maputil.map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).innerHTML = pointsHtml;
        
        //var pointsHtml = '';
       
        
        
        //insert marker html to mappane
        maputil.map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).innerHTML = pointsHtml;
        //console.log(pointsHtml);
    }
    
    MARKERS.prototype.infoWindow = function(lat,lng,info){ 
        maputil.map.openInfoWindow(new GLatLng(lat,lng), '<div id="infoWin">Please wait...</div>');
        googSearch.ajax('ajx/glocalsearchdetails.php?q='+info+'&lat='+lat+'&lng='+lng, marker.showResults);        
        googSearch.loading('Loading');
    }
    
    MARKERS.prototype.showResults = function(){ 
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {           
            if(xmlhttp.responseText.length>0){    			
                document.getElementById('infoWin').innerHTML = xmlhttp.responseText;    
                googSearch.loading('');                
    			var ra = xmlhttp.responseText.split('\n');
    			var inJs = false;
    			var js = '';			
    			for(i=0; i<ra.length; i++) {
    				if(ra[i].match(/<\/script/i)) inJs = false;
    				if(inJs) js += ra[i]+"\n";
    				if(ra[i].match(/<script/i)) inJs = true;
    			}

    			try {
    				eval(js);
    			} catch(e) {
    				console.log(e);
    			}
            }
        }    
    }
    
    MARKERS.prototype.shareData = '';
    MARKERS.prototype.shareIt = function(){
        document.getElementById('infoWin').innerHTML = 'Please wait...';     
        googSearch.ajax('/ajx/shareit.php?'+this.shareData, marker.showResults);        
        googSearch.loading('Loading');
    }

    
    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.hideBubble = function (){ 
        try{
            document.getElementById('map_bubble').style.display = 'none';             
        }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();
    }    
    
    var maxx = 0, maxy = 0, minx = 0, miny = 0;
    
    MARKERS.prototype.getMarkers = function (force){
       
        var bounds = maputil.map.getBounds();
         yt = bounds.getNorthEast().y.toFixed(3);
         xt = bounds.getNorthEast().x.toFixed(3);
         yb = bounds.getSouthWest().y.toFixed(3);
         xb = bounds.getSouthWest().x.toFixed(3);         
        //console.log('yt:'  + yt + ' yb:'  + yb + ' xt:'  + xt + ' xb:'  + xb);
        if(xt>maxx || yt>maxy || xb<minx || yb<miny || force > 0){
            var detx = 0;//xt - xb; 
            var dety = 0;//yt - yb;    
            
            maxx = (xt*1 + detx).toFixed(3)*1;            
            maxy = (yt*1 + dety).toFixed(3)*1;
            minx = (xb*1 - detx).toFixed(3)*1;            
            miny = (yb*1 - dety).toFixed(3)*1;  
           
            if(maputil.map.getZoom()>16){maxy += 0.01;maxx += 0.01;miny -= 0.01;minx -= 0.01;  } 
            
            var getUrl = "ajx/getpoints.php?yt=" + maxy.toFixed(3) + "&xt=" + maxx.toFixed(3) + "&xb=" + minx.toFixed(3) + "&yb=" + miny.toFixed(3) +"&zoom=" +  maputil.map.getZoom();
            if(force>1) getUrl += '&nocache=1'
           
        	xmlhttp2 = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");     		
        	
            xmlhttp2.onreadystatechange =  this.downloadMarkeres;
            xmlhttp2.open("GET", getUrl, true); 		    	
            xmlhttp2.send(null);
            googSearch.loading('Loading');            
            
        }
            
    }    
    
    MARKERS.prototype.downloadMarkeres = function(){
        if ((xmlhttp2.readyState == 4) && (xmlhttp2.status == 200)) { 	
            var rows = xmlhttp2.responseText.split("\n");
            marker.markersDb2 = rows;
            marker.processMarkeres();
            var tmp = '';
            for(i=0;i<rows.length-1;i++){
                var row = rows[i].split("\|");
                tmp += '<li ';
                tmp += 'onmouseover="marker.showPointLabel(document.getElementById(\'marker_'+row[0]+'\'))" ';
                tmp += 'onmouseout="marker.hidePointLabel(document.getElementById(\'marker_'+row[0]+'\'))" ';
                tmp += 'onclick="marker.infoWindow('+row[1]+','+row[2]+',\''+escape(row[4])+'\')" ';
                tmp += '>' + row[4]+ ' <span>' + row[5] +'</span></li>';
            }
            document.getElementById('mostShared').innerHTML = tmp;
            googSearch.loading('');
        }
    }
   
}


//Google local search
GSEARCH  = function () {
    
    GSEARCH.prototype.getResults = function(query){
        googSearch.ajax('ajx/glocalsearch.php?q='+query, googSearch.showResults);
        this.loading('Loading');
        return false;
    }
    
    GSEARCH.prototype.showResults = function(){
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {           
            if(xmlhttp.responseText.length>0){    			
                var results = xmlhttp.responseText.split("\n");
                if(results.length>1){
                    marker.bounds = new GLatLngBounds(); 
                    marker.markersDb = results;    
                    marker.processMarkeres();    
                    maputil.map.setCenter(marker.getMarkerCenter(),marker.getZoomLevel()-1);                                    
                }else{
                    var cor = xmlhttp.responseText.split(",");
                    maputil.map.setCenter(new GLatLng(cor[1], cor[0]), 12); 
                    marker.clearMarkers();               
                    marker.getMarkers(1);                    
                }
                googSearch.loading('');
            }
        }
    }
    
    GSEARCH.prototype.loading = function(text) {
        if(text.length>0){
            document.getElementById('loading').style.display = 'block';
        }else{
            document.getElementById('loading').style.display = 'none';
        }
    }    
    
    GSEARCH.prototype.ajax = function(url,action) {    
        try {
    		xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); 
    	} catch (e) { } 		
    	xmlhttp.onreadystatechange = action; 		
    	xmlhttp.open("GET", url, true); 		
    	xmlhttp.send(null);          
    }
}
    

//create maputil class
var maputil = new MAPUTILS;
//create markers class
var marker = new MARKERS;
//search 
var googSearch = new GSEARCH;

//after page has been closed try to free up memory
window.onunload = function(){
    try{
        GUnload();
    }catch(e){}
}