notifyZoneColor = '#508FC4';

/**
 * Main map functions
 */
MAPUTILS  = function () {
    
    //global map object
    MAPUTILS.prototype.map;
    MAPUTILS.prototype.counter = 0;
    
    //default map settings
    MAPUTILS.prototype.currentLat =  27.463597;
    MAPUTILS.prototype.currentLng = -82.608220;
    MAPUTILS.prototype.currentZoom = 6;
    
    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(179,6)));
        
        this.map.addControl(new this.MapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(100, 6)));//add button
        this.map.addControl(new this.MapControl2(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(6, 6)));//add button
        
        //if we got more then 1 line show it on map
        if(line.linesDB.length>0) line.processLines();
        if(notifyzone.DB.length>0) notifyzone.process();

        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();
        });
        
        
        // --------- Add notify zones
        var boxStyleOpts = {
          opacity: .1,
          border: "1px solid " + notifyZoneColor,
          outlineColor: notifyZoneColor,
          outlineWidth: 4
        }

        /* second set of options is for everything else */
        var otherOpts = {
          buttonHTML: "",
          buttonZoomingHTML: "",
          buttonStartingStyle: {width: '0px', height: '0px'}
        };

        /* third set of options specifies callbacks */
        var callbacks = {
          buttonclick: function(){
            maputil.mapInfo('Click and drag to create a zone. Or click <a href="javascript:rectengaleSelect.buttonclick_();maputil.mapInfo(0)">here</a> for cancel.');
          
          },
          dragstart: function(){//GLog.write("Started to Drag . . .")
          
          },
          dragging: function(x1,y1,x2,y2){
          //GLog.write("Dragging, currently x="+x2+",y="+y2)
          },
          dragend: function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){
          //GLog.write("Zoom! NE="+ne+";SW="+sw)          
            maputil.mapInfo('Saving ...');
            maputil.ajax('notifyzone.php?todo=new&nlng='+nw.x+'&nlat='+nw.y+'&slng='+se.x+'&slat='+se.y);
          }
        };
        
        rectengaleSelect = new DragZoomControl(boxStyleOpts, otherOpts, callbacks)
        maputil.map.addControl(rectengaleSelect);
        
        this.createInfoWindow();

    }
    
    MAPUTILS.prototype.createInfoWindow = function(){
        var mapDiv = maputil.map.getContainer();
        
        var buttonContainerDiv = document.createElement("div");	
        buttonContainerDiv.id = 'infoWindow';
        
        buttonContainerDiv.style.padding = '3px';
        buttonContainerDiv.style.top = '3px';
        buttonContainerDiv.style.left = '100px';
        buttonContainerDiv.style.border = '1px solid #333';
        buttonContainerDiv.style.background = '#fff';
        buttonContainerDiv.style.position = 'absolute';
        buttonContainerDiv.style.zIndex = '101';
        
        mapDiv.appendChild(buttonContainerDiv);
        maputil.mapInfo(0);
    }
    
    MAPUTILS.prototype.mapInfo = function(str){
        document.getElementById('infoWindow').style.display = 'block';
        document.getElementById('infoWindow').innerHTML = str;
        if(parseInt(str) == 0) document.getElementById('infoWindow').style.display = 'none';
    }
    
    
    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.padding = '0';
        button.style.width = '75px';
        button.style.height = '19px';
        button.style.fontSize = '11px';
        button.style.background = '#FF5A00';        
        button.innerHTML = 'Add Runway';
        button.onclick = function(){line.startLine()}
        return button;
    }
    
    MAPUTILS.prototype.MapControl2 = function(){}
    
    try{
        MAPUTILS.prototype.MapControl2.prototype = new GControl();
    }catch(e){}
    
    MAPUTILS.prototype.MapControl2.prototype.initialize = function(map) {        
        var button =  document.createElement("button");               
        maputil.map.getContainer().appendChild(button);
        button.style.display = 'block';
        button.style.width = '90px';
        button.style.height = '19px';
        button.style.padding = '0';
        button.style.fontSize = '11px';
        button.style.background = '#FF5A00';        
        button.innerHTML = 'Add Notify Zone';
        button.onclick = function(){
            try{
                if(document.loginform.todo.value == 'login'){
                    alert('Please login!');
                    return false;
                }
            }catch(e){}
            rectengaleSelect.buttonclick_();        
        }
        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){
            //check if user entered coordinates
            var isCor = str.split(',');
            if(isCor.length == 2 && parseFloat(isCor[0]) != 'NaN' && parseFloat(isCor[1]) != 'NaN'){
                point = new GLatLng(parseFloat(isCor[0]), parseFloat(isCor[1]));
                if(maputil.map.getZoom()<14) maputil.map.setCenter(point,14);
                else maputil.map.setCenter(point);
                maputil.setSiteUrl();
                return false;
            }
            
            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]);
                    if(maputil.map.getZoom()<14) maputil.map.setCenter(point,14);
                    else maputil.map.setCenter(point);
                    //document.getElementById('latbox').value = point.lat();
                    //document.getElementById('lonbox').value = point.lng();  
                    maputil.setSiteUrl();
                }
            });  
            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;
	}
    
    MAPUTILS.prototype.ajax = function(url){
        try {
    		this.xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
    	} catch (e) { }
        
    	this.xmlhttp.onreadystatechange = this.showResults;
    	this.xmlhttp.open("GET", url, true);
    	this.xmlhttp.send(null);

    }
    
    MAPUTILS.prototype.showResults = function(){
    
        if ((maputil.xmlhttp.readyState == 4) && (maputil.xmlhttp.status == 200)) {
            maputil.mapInfo(maputil.xmlhttp.responseText);            
           
            var resp = maputil.xmlhttp.responseText;
			var ra = resp.split('\n');
			var inJs = false;
			var js = '';
			var i=0;
			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);
			}
        }
    }
}

LINES  = function () {
    
    LINES.prototype.linesDB = new Array();
    LINES.prototype.bounds = new GLatLngBounds(); 

    LINES.prototype.startDrawing = function (poly, name, onUpdate, color) {
        maputil.map.addOverlay(poly);
        poly.enableDrawing({maxVertices: 2});
        poly.enableEditing({onEvent: "mouseover", maxVertices: 2}); 
        poly.disableEditing({onEvent: "mouseout"});
        GEvent.addListener(poly, "endline", function() {            
            popuplayer.loadBlock('newrunway','lat='+poly.getVertex(0).y+'&lng='+poly.getVertex(0).x+'&elat='+poly.getVertex(1).y+'&elng='+poly.getVertex(1).x);            
            GEvent.addListener(poly, "click", function(latlng, index) {
                popuplayer.loadBlock('newrunway','lat='+poly.getVertex(0).y+'&lng='+poly.getVertex(0).x+'&elat='+poly.getVertex(1).y+'&elng='+poly.getVertex(1).x);            
            });
        });
    }
    
    LINES.prototype.startLine = function() {
        //check if user is logged in
        try{
            if(document.loginform.todo.value == 'login'){
                alert('Please login!');
                return false;
            }
        }catch(e){}
        //start drawing line
        var line = new GPolyline([], "#ff0000");
        this.startDrawing(line, "Line1 ", function() {
            var cell = this;
            var len = line.getLength();
            cell.innerHTML = (Math.round(len / 10) / 100) + "km";
        }, "#ff0000");
    }
    
    LINES.prototype.processLines = function(){   
        
        //go through linesDb and build up a layer for the map
        for(i=0;i<this.linesDB.length;i++){        
            newline = this.linesDB[i].split(";");           
            start = newline[0].split(',');
            end = newline[1].split(',');            
            
            //extends bounds
            this.bounds.extend(new GLatLng( start[0], start[1]));
            this.bounds.extend(new GLatLng( end[0], end[1]));
            
            //create line
            this.createPolyline(
                    new GLatLng(start[0],start[1]),
                    new GLatLng(end[0],end[1])
                ,newline[2]);  
        }
        
        maputil.map.setCenter(this.bounds.getCenter(), maputil.map.getBoundsZoomLevel(this.bounds));        
    }
    
    LINES.prototype.createPolyline = function(start,end,lineid){
        var p = new GPolyline([start,end],"#ff0000",5,1);
        maputil.map.addOverlay(p);        
        GEvent.addListener(p,"click", function(){
            popuplayer.loadBlock('linedetails', 'lineid='+lineid);
        });
        
        //add a marker on the end of the line
        var marker = new GMarker(start);
        maputil.map.addOverlay(marker);
        GEvent.addListener(marker,"click", function(){
            popuplayer.loadBlock('linedetails', 'lineid='+lineid);
        });
    }    
}

NOTIFYZONES  = function () {

    NOTIFYZONES.prototype.DB = new Array();

    NOTIFYZONES.prototype.process = function(){
        
        //go through linesDb and build up a layer for the map
        for(i=0;i<this.DB.length;i++){        
            newRec = this.DB[i].split(";");           
            this.createRectangle(newRec[0],newRec[1],newRec[2],newRec[3]);
        }    
        
    }
    
    NOTIFYZONES.prototype.createRectangle  = function(nlat,nlng,slat,slng){
        var polygon = new GPolygon([
          new GLatLng(nlat, nlng),          
          new GLatLng(slat, nlng),
          new GLatLng(slat, slng),
          new GLatLng(nlat, slng),          
          new GLatLng(nlat, nlng)
		], notifyZoneColor, 5, 1, notifyZoneColor, 0.2);
		
        maputil.map.addOverlay(polygon);
    }

    
}

//create maputil class
var maputil = new MAPUTILS;
var line = new LINES;
var notifyzone = new NOTIFYZONES;

//after page has been closed try to free up memory
window.onunload = function(){
    try{
        GUnload();
    }catch(e){}
}

