/**
 * Main map functions
 */
if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length;
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++){
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  }
}
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 = 4;
    
    MAPUTILS.prototype.mapSizeW = 500;
    MAPUTILS.prototype.mapSizeH = 500;
    
    MAPUTILS.prototype.showLines = true;
    
    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 { 
                window.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 { 
                window.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"));
        
        
        //center map to home airport location
        if(airline.airportHome.length>0){
            maputil.currentLat =  airline.airportHome[2];
            maputil.currentLng =  airline.airportHome[3];
        }

        //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 GSmallMapControl());    //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.createInfoWindow();
        
        if(airline.routes.length>0){
           this.showLines = false;
            airline.processRoutes();
            airline.processAirports();
        }else{
           
           //read all airlines and add it to array
           airline.processAirlines();
            
            //if we got more then 1 airline show it on map
           // if(airline.linesDB.length>0) 
           airline.processLines();
           this.addHomeAirportMakrer();
           
        }
    /*
        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();
        });
        
  */              
        

    }
    
    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('');
    }
    
    MAPUTILS.prototype.mapInfo = function(str){
        document.getElementById('infoWindow').style.display = 'block';
        document.getElementById('infoWindow').innerHTML = str;
        if(str.length == 0) document.getElementById('infoWindow').style.display = 'none';
    }
    
    
    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;
	}
    
    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);
			}
        }
    }
    
    MAPUTILS.prototype.addHomeAirportMakrer = function(){
        //add home airport icon
        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image =  gmap_airline_url + "sun.png";
        blueIcon.shadow = "";
        blueIcon.iconSize = new GSize(16, 16);
        blueIcon.iconAnchor = new GPoint(8,8);
        marker = new GMarker(new GLatLng(airline.airportHome[2], airline.airportHome[3]), { icon: blueIcon});             
        this.map.addOverlay(marker);
    }
}

AIRLINES  = function () {
    
    AIRLINES.prototype.linesDB = new Array();
    AIRLINES.prototype.airports = new Array();
    AIRLINES.prototype.airportHome = new Array();
    AIRLINES.prototype.routes = new Array();
    AIRLINES.prototype.bounds = new GLatLngBounds();     
        
    AIRLINES.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];           
            
            
            //extends bounds
            //this.bounds.extend(new GLatLng( start[0], start[1]));
            //this.bounds.extend(new GLatLng( end[0], end[1]));
            
            //create airline
            this.createPolyline(
                    new GLatLng(newline[0],newline[1]),
                    new GLatLng(newline[2],newline[3])
                ,i);  
            
        }
        document.getElementById('airlineNav').innerHTML = airline.airlineNav;
       // maputil.map.setCenter(this.bounds.getCenter(), maputil.map.getBoundsZoomLevel(this.bounds));        
        maputil.mapInfo('');
    }
    
    AIRLINES.prototype.airLineRoute1 = false;
    AIRLINES.prototype.createAirport = function(code,text,point,pos){
    
              
        var labelIcon = new GIcon(G_DEFAULT_ICON);
        labelIcon.image = gmap_airline_url + "marker.png";
        
        /*labelIcon.shadow = "";
        labelIcon.iconSize = new GSize(37, 26);
        labelIcon.iconAnchor = new GPoint(0,26);
        labelIcon.shadowSize = new GSize(36, 34);
        labelIcon.imageMap=[0,0,100,0,0,100,100,100];
        */
        
        labelIcon.iconSize = new GSize(20, 34);
        //labelIcon.iconAnchor = new GPoint(0,26);
        //labelIcon.shadowSize = new GSize(36, 34);
        
        var marker = new GMarker(point)//, { icon: labelIcon});
        marker.infoText = text;
        marker.airportLat = airline.airports[i][0];
        marker.airportLng = airline.airports[i][1];      
              
        maputil.map.addOverlay(marker);
        this.markersDb.push(marker);
        GEvent.addListener(marker,"click", function(){            
            
            //on airline view show airline
            if(!maputil.showLines){
                
               //if(airline.airLineRoute1) maputil.map.removeOverlay(airline.airLineRoute1);
                //console.log(marker.airportLng);
               //airline.airLineRoute1 = new GPolyline([marker.getLatLng(),new GLatLng(airline.airportHome[2], airline.airportHome[3])],"#FD9700",1,1,{geodesic:true});
                //maputil.map.addOverlay(airline.airLineRoute1);
                
                //set marker back to red background and hide all
                for(ii in airline.markersDb){
                    if(ii != 'indexOf'){ 
                        airline.markersDb[ii].setImage(gmap_airline_url + "marker.png");
                        airline.markersDb[ii].hide();
                    }
                }
                
                //remove privous lines 
                if(airline.airLineRoute1){
                    for(ii in airline.airLineRoute1){ 
                        maputil.map.removeOverlay(airline.airLineRoute1[ii]);
                    }
                }
                
                //add lines
                airline.airLineRoute1 = new Array()
                for(ii in airline.routes){ 
                    if(airline.routes[ii][0] == marker.airportLat){
                        //console.log(airline.routes[ii]) 
                        var p = new GPolyline([marker.getLatLng(),new GLatLng(airline.routes[ii][2], airline.routes[ii][3])],"#FD9700",1,1,{geodesic:true});
                        maputil.map.addOverlay(p);
                        airline.airLineRoute1.push(p);
                        
                        //find destination marker and set it to orange
                        for(iii in airline.markersDb){
                            if(airline.markersDb[iii].airportLat == airline.routes[ii][2]){
                                //airline.markersDb[iii].setImage(gmap_airline_url + "marker_over.png");
                                airline.markersDb[iii].show();
                            }
                        }
                    }
                }
                
                //color clicked marker          
                marker.setImage(gmap_airline_url + "marker_over.png");
                marker.show();
                maputil.mapInfo('<a href="javascript:airline.showAllAirports()">Show all</a>');
                
            }
            
            marker.openInfoWindow(marker.infoText);
        });
        //var label=new ELabel(point, code, null, new GSize(9,-10), 100, pos);
        
        /*if(maputil.showLines){    
            var label=new ELabel(point, code, null, new GSize(-13,-20), 100, pos);
            maputil.map.addOverlay(label);
        }*/
    }
    
    AIRLINES.prototype.showAllAirports = function(){
        maputil.mapInfo('');
        for(ii in airline.markersDb){
            if(ii != 'indexOf'){ 
                airline.markersDb[ii].setImage(gmap_airline_url + "marker.png");
                airline.markersDb[ii].show();
            }
        }
        
        //remove privous lines 
        if(airline.airLineRoute1){
            for(ii in airline.airLineRoute1){ 
                maputil.map.removeOverlay(airline.airLineRoute1[ii]);
            }
        }
    }
    
    AIRLINES.prototype.markersDb = new Array();
    AIRLINES.prototype.createPolyline = function(start,end,lineid){
        if(maputil.showLines){
            var p = new GPolyline([start,end],"#FD9700",1,1,{geodesic:true});
            maputil.map.addOverlay(p);
               
            GEvent.addListener(p,"click", function(){
            //User clicks on airline
            });        
        } 
        //build first line in bubble
        var a = '';
        if(airline.airports[lineid][7].length>2) a =  '<a class= "fresh-list" href="'+airline.airports[lineid][7]+'">' + airline.airports[lineid][4] + '</a> ' 
        else a = airline.airports[lineid][4];
        a += ' (<a class= "fresh-list" href="airports.php?airport='+airline.airports[lineid][0]+'">' + airline.airports[lineid][0] +'</a>)';
        //add a marker on the end of the airline  
        this.createAirport(airline.airports[lineid][0], a + '<br /> <a href="http://www.icheapairfares.com/'+airline.airports[lineid][6]+'.htm" class= "fresh-list">' + airline.airports[lineid][1] + '</a><br /><a href="'+airline.airports[lineid][5] +'" target="_blank" class= "fresh-list">Go!</a>', end, lineid); 
    }
    
    AIRLINES.prototype.showAirline = function(id){
        this.bounds = new GLatLngBounds(); 
        maputil.map.clearOverlays();
        
        maputil.addHomeAirportMakrer();
        for(i in airline.airlineRoutes[id]) if(i != 'indexOf'){
            newline = this.linesDB[airline.airlineRoutes[id][i]];           
        
            //extends bounds
            this.bounds.extend(new GLatLng( newline[0],newline[1]));
            this.bounds.extend(new GLatLng( newline[2],newline[3]));
        
            //create airline
            this.createPolyline(
                new GLatLng(newline[0],newline[1]),
                new GLatLng(newline[2],newline[3])
            ,airline.airlineRoutes[id][i]);
        }  
        maputil.map.setCenter(this.bounds.getCenter(), maputil.map.getBoundsZoomLevel(this.bounds));  
        maputil.mapInfo('<a href="javascript:airline.processLines()">Show all</a>');
    }
    
    

    AIRLINES.prototype.airlineList = new Array();
    AIRLINES.prototype.airlineListUrl = new Array();
    AIRLINES.prototype.airlineRoutes = new Array();

    AIRLINES.prototype.airlineNav = '';
    
    AIRLINES.prototype.processAirlines = function(){
        //add it to db and create navigation
        for(i in this.airports){
            if(i != 'indexOf'){
                this.linesDB.push(new Array(this.airportHome[2],this.airportHome[3],this.airports[i][2],this.airports[i][3]));
               // airlineNav += '<a href="javascript:airline.showAirline('+i+')"><b>' + this.airports[i][1] + '</b> '+ this.airportHome[0] + ' to ' + this.airports[i][0] +'</a><br />';
                if(this.airlineList.indexOf(this.airports[i][1]) == -1){
                    this.airlineList.push(this.airports[i][1]);
                    this.airlineListUrl.push(this.airports[i][6]);
                    this.airlineRoutes[this.airlineList.indexOf(this.airports[i][1])] = new Array();
                }
                this.airlineRoutes[this.airlineList.indexOf(this.airports[i][1])].push(i);
            }
        } 

        for(i in this.airlineRoutes){
            if(i != 'indexOf'){
                if(this.airlineListUrl[i].length>1) go = ' <a class= "fresh-list" href="http://www.icheapairfares.com/'+this.airlineListUrl[i]+'.htm">Go!</a>';
                else go = '';
                this.airlineNav += '<a class= "category-map-anchor" href="javascript:airline.showAirline('+i+')">' + this.airlineList[i] +'</a>'+go+'<br />';
            }
        }
    }    
    
    AIRLINES.prototype.processRoutes = function(){
        //add it to db and create navigation
        for(i in this.routes){
            if(i != 'indexOf'){
                this.bounds.extend(new GLatLng(this.routes[i][0]+5,this.routes[i][1]));
                this.bounds.extend(new GLatLng(this.routes[i][2],this.routes[i][3]));
                if(maputil.showLines){    
                    var p = new GPolyline([new GLatLng(this.routes[i][0],this.routes[i][1]),new GLatLng(this.routes[i][2],this.routes[i][3])],"#FD9700",1,1,{geodesic:true});
                    maputil.map.addOverlay(p);        
                }
            }
        } 
        
        maputil.map.setCenter(this.bounds.getCenter(), maputil.map.getBoundsZoomLevel(this.bounds));
        
    }

    AIRLINES.prototype.processAirports = function(){
        //add it to db and create navigation
        for(i in this.airports){
            if(i != 'indexOf'){
                 if(airline.airports[i][4].length>2) a =  '<a class="category-map-anchor" href="'+airline.airports[i][4]+'">' + airline.airports[i][2] + '</a> '; 
                    else a = airline.airports[i][2];
                
                this.createAirport(this.airports[i][3],a + ' (<a class="category-map-anchor" href="airports.php?airport='+this.airports[i][3]+'">' + this.airports[i][3] +'</a>) <br /> <a class="fresh-list" href="'+airline.airlineurl+'" target="_blank">Go!</a>',new GLatLng(this.airports[i][0],this.airports[i][1]),i)
            }
        } 
        
        
    }    
}

//create maputil class
var maputil = new MAPUTILS;
var airline = new AIRLINES;

window.onunload = function(){
    GUnload();
}


// ELabel.js
//
//   This Javascript is provided by Mike Williams
//   Blackpool Community Church Javascript Team
//   http://www.commchurch.freeserve.co.uk/
//   http://econym.googlepages.com/index.htm
//
//   This work is licenced under a Creative Commons Licence
//   http://creativecommons.org/licenses/by/2.0/uk/
//
// Version 0.2      the .copy() parameters were wrong
// version 1.0      added .show() .hide() .setContents() .setPoint() .setOpacity() .overlap
// version 1.1      Works with GMarkerManager in v2.67, v2.68, v2.69, v2.70 and v2.71
// version 1.2      Works with GMarkerManager in v2.72, v2.73, v2.74 and v2.75
// version 1.3      add .isHidden()
// version 1.4      permit .hide and .show to be used before addOverlay()
// version 1.5      fix positioning bug while label is hidden
// version 1.6      added .supportsHide()
// version 1.7      fix .supportsHide()


      function ELabel(point, html, classname, pixelOffset, percentOpacity, overlap) {
        // Mandatory parameters
        this.point = point;
        this.html = html;

        // Optional parameters
        this.classname = classname||"";
        this.pixelOffset = pixelOffset||new GSize(0,0);
        if (percentOpacity) {
          if(percentOpacity<0){percentOpacity=0;}
          if(percentOpacity>100){percentOpacity=100;}
        }
        this.percentOpacity = percentOpacity;
        this.overlap=overlap||false;
        this.hidden = false;
      }

      ELabel.prototype = new GOverlay();

      ELabel.prototype.initialize = function(map) {
        var div = document.createElement("div");
        div.style.position = "absolute";
        //div.innerHTML = '<div class="' + this.classname + '" style="background:#003399;color:#FD9700;font-size:11px;text-align:center;width:28px;font-weight:bold;">' + this.html + '</div>' ;
        div.innerHTML = '<div class="' + this.classname + '" style="color:#000;font-size:7px;text-align:center;width:28px;font-weight:normal;">' + this.html + '</div>' ;
        
        map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div);
        this.map_ = map;
        this.div_ = div;
        if (this.percentOpacity) {
          if(typeof(div.style.filter)=='string'){div.style.filter='alpha(opacity:'+this.percentOpacity+')';}
          if(typeof(div.style.KHTMLOpacity)=='string'){div.style.KHTMLOpacity=this.percentOpacity/100;}
          if(typeof(div.style.MozOpacity)=='string'){div.style.MozOpacity=this.percentOpacity/100;}
          if(typeof(div.style.opacity)=='string'){div.style.opacity=this.percentOpacity/100;}
        }
        if (this.overlap) {
          var z = GOverlay.getZIndex(this.point.lat());
          this.div_.style.zIndex = z;
        }
        if (this.hidden) {
          this.hide();
        }
      }

      ELabel.prototype.remove = function() {
        this.div_.parentNode.removeChild(this.div_);
      }

      ELabel.prototype.copy = function() {
        return new ELabel(this.point, this.html, this.classname, this.pixelOffset, this.percentOpacity, this.overlap);
      }

      ELabel.prototype.redraw = function(force) {
        var p = this.map_.fromLatLngToDivPixel(this.point);
        var h = parseInt(this.div_.clientHeight);
        this.div_.style.left = (p.x + this.pixelOffset.width) + "px";
        this.div_.style.top = (p.y +this.pixelOffset.height - h) + "px";
      }

      ELabel.prototype.show = function() {
        if (this.div_) {
          this.div_.style.display="";
          this.redraw();
        }
        this.hidden = false;
      }

      ELabel.prototype.hide = function() {
        if (this.div_) {
          this.div_.style.display="none";
        }
        this.hidden = true;
      }

      ELabel.prototype.isHidden = function() {
        return this.hidden;
      }

      ELabel.prototype.supportsHide = function() {
        return true;
      }

      ELabel.prototype.setContents = function(html) {
        this.html = html;
        this.div_.innerHTML = '<div class="' + this.classname + '">' + this.html + '</div>' ;
        this.redraw(true);
      }

      ELabel.prototype.setPoint = function(point) {
        this.point = point;
        if (this.overlap) {
          var z = GOverlay.getZIndex(this.point.lat());
          this.div_.style.zIndex = z;
        }
        this.redraw(true);
      }

      ELabel.prototype.setOpacity = function(percentOpacity) {
        if (percentOpacity) {
          if(percentOpacity<0){percentOpacity=0;}
          if(percentOpacity>100){percentOpacity=100;}
        }
        this.percentOpacity = percentOpacity;
        if (this.percentOpacity) {
          if(typeof(this.div_.style.filter)=='string'){this.div_.style.filter='alpha(opacity:'+this.percentOpacity+')';}
          if(typeof(this.div_.style.KHTMLOpacity)=='string'){this.div_.style.KHTMLOpacity=this.percentOpacity/100;}
          if(typeof(this.div_.style.MozOpacity)=='string'){this.div_.style.MozOpacity=this.percentOpacity/100;}
          if(typeof(this.div_.style.opacity)=='string'){this.div_.style.opacity=this.percentOpacity/100;}
        }
      }

      ELabel.prototype.getPoint = function() {
        return this.point;
      }
      ELabel.prototype.U = function() {
        return this.point;
      }
      ELabel.prototype.V = function() {
        return this.point;
      }
      ELabel.prototype.W = function() {
        return this.point;
      }
      ELabel.prototype.X = function() {
        return this.point;
      }
      ELabel.prototype.Y = function() {
        return this.point;
      }
      ELabel.prototype.Z = function() {
        return this.point;
      }



