﻿

window.onload = function(){
    init_default_map();
    //setInterval( loadPaging , 3000 );
    listener();
    tabs();
};

//var txtBx;
//var targetDiv;
var method = 'get';
var URL = 'WebForm2.aspx';
var params = '?cityCode=';
var loadingIcon;
var response;
//##############################################################
//send the textbox value if it exceeds 3 letters
function searchXML2( src , target ){
    
    //reset the textbox flags to 0
    //alert(src);
    $( src + '_suggest' ).value = 0;
    
    //searchBox
    var txtBx = $( src );
    //identify result div
    var targetDiv = target;
    
    //more than 3 letters
    if( txtBx.value.length > 2 ){
    
        //send request
        getAirports( src , target );
        //alert(txtBx.value);
        
    }
    
}
//##############################################################
//send the ajax request
function getAirports( src , target ){

    var code = $(src).value;
    
    loadingIcon = $( src + '_nearby_loading' );
    loadingIcon.className = 'show';
    
    http.open( method , URL + params + code , true );
    http.onreadystatechange = function (){ handleResponseGetAirports( src , target ) };
	http.send( null );

}
//##############################################################
function trimText(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
//##############################################################
function handleResponseGetAirports( src ,  target ){

    if(http.readyState == 4 && http.status == 200){
        
        //response is JSON-enabled object
        start = http.responseText;
        if( start == '' ){
            response = '';
        }else{
            response = eval('('+start+')');
        }
        
        if( response != '' ) {
            
            //hide select controls
            //selectListShowHide('none');
            
            var len = response.airports.length;
            
            //hide the loading img
            loadingIcon.className = 'hide';
            
            //empty div
            $( target ).innerHTML = '';
            //change class to green
	        $( target ).className = 'ac';
	        $( target ).style.display = 'block';
            
            for( i=0 ; i < len ; i++ ){
            
                
                _code = response.airports[i].airport.code;
                _lon = response.airports[i].airport.lon;
                _lat = response.airports[i].airport.lat;
                _city = response.airports[i].airport.city;
                _country = response.airports[i].airport.country;
                _desc = response.airports[i].airport.desc;
                _an = response.airports[i].airport.airport_name;
                
                //slicing
                //if( _an.length > 15 ){
                 //   _an = _an.slice(0,15) + "...";
                //}
                
                //more trimmimg
                longDataString = trimText(_city) + trimText(_country) + trimText(_code) + trimText(_an);
                constant = 35;
                difference = 0;
                //alert(longDataString);
                //alert(longDataString.length);
                if( longDataString.length > constant ){
                    difference = longDataString.length - constant;
                }
                
                if( src.indexOf('from')==0){//is from
                //alert('from out');
                
                    if( src.indexOf('from_ent')==0){//is ent
                    
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    //         aircraft catalog suggest with map         //
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    
                        //alert('checkairjet');//alert(src);
                        //JSON processing
                        //write new entry in the results div
	                    $( target ).innerHTML += "<div id='x"+target+i+"' onmouseover='over(this.id);' onmouseout='out(this.id);' style='width: 100%; cursor: pointer; height: 20px;' onclick=checkAirJet("+i+",'"+target+"','"+src+"','',"+_lat+","+_lon+");return false;>" + changeCase(_city) + ", " + changeCase(_country) + " <strong>[<span id='sx"+target+i+"'>" + _code + "</span>]</strong> " + ' - ' +  changeCase(_an.slice(0,_an.length-difference)) + "</div>";
	                    
	                        //$("fixedtipdiv").innerHTML = _an + '<br />' + _city + '<br />' + _country;     
	                    
                    }else{
                        //alert('setValue');
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    //                   homepage                        //
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    
                        
                        
                        //JSON processing
                        //write new entry in the results div
	                    $( target ).innerHTML += "<div id='x"+target+i+"' onmouseover='over(this.id);' onmouseout='out(this.id);' style='width: 100%; cursor: pointer; height: 20px;' onclick=setValue("+i+",'"+target+"','"+src+"','',"+_lat+","+_lon+");return false;>" + changeCase(_city) + ", " + changeCase(_country) + " <strong>[<span id='sx"+target+i+"'>" + _code + "</span>]</strong> " + ' - ' +  changeCase(_an.slice(0,_an.length-difference)) + "</div>";
	                 //alert(changeCase(_an.slice(0,_an.length-difference)));   
	                 //alert(_an.length);   
	                    //oneLeg_roundTrip.push( _lat , _lon );
	                    //$("fixedtipdiv").innerHTML = _an + '<br />' + _city + '<br />' + _country;   
	                    
                    }
                    
                }else{
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    //               catalog - to textbox                // also in airport catalog
                    ///////////////////////////////////////////////////////
                    ///////////////////////////////////////////////////////
                    //JSON processing
                    //write new entry in the results div
	                $( target ).innerHTML += "<div id='x"+target+i+"' onmouseover='over(this.id);' onmouseout='out(this.id);' style='border:0px solid red;width: 100%; cursor: pointer; height: 20px;' onclick=setValue("+i+",'"+target+"','"+src+"','',"+_lat+","+_lon+");return false;>" + changeCase(_city) + ", " + changeCase(_country) + " <strong>[<span id='sx"+target+i+"'>" + _code + "</span>]</strong> " + ' - ' +  changeCase(_an.slice(0,_an.length-difference)) + "</div>";
	             
	                //$("fixedtipdiv").innerHTML = _an + '<br />' + _city + '<br />' + _country;     
	                
                }
	            
            }
            
        }else{
            //hide the loading img
            loadingIcon.className = 'hide';
            
            //remove existing results
            $( target ).innerHTML = 'Enter city name...';
            
            alert('No airports found!');
        }
    }
    
}
//##############################################################
//Initial Caps
function changeCase(frmObj) {
    var index;
    var tmpStr;
    var tmpChar;
    var preString;
    var postString;
    var strlen;
    
    //tmpStr = frmObj.value.toLowerCase();
    tmpStr = frmObj.toLowerCase();
    strLen = tmpStr.length;
    
    if (strLen > 0)  {
        for (index = 0; index < strLen; index++)  {
            if (index == 0)  {
                tmpChar = tmpStr.substring(0,1).toUpperCase();
                postString = tmpStr.substring(1,strLen);
                tmpStr = tmpChar + postString;
            }else {
                tmpChar = tmpStr.substring(index, index+1);
                if (tmpChar == " " && index < (strLen-1))  {
                    tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
                    preString = tmpStr.substring(0, index+1);
                    postString = tmpStr.substring(index+2,strLen);
                    tmpStr = preString + tmpChar + postString;
                }
            }
        }
    }
    //frmObj.value = tmpStr;
    return tmpStr;
}
//##################################################################
function init_default_map() {
    // if browser is compatible
	if ( GBrowserIsCompatible() ) {
        // get container
        //var map = new GMap2( document.getElementById("map_canvas") );
        var map = new GMap2( document.getElementById("vmaps") );
        // set map type
        //map.addControl( new GMapTypeControl() );
        // small zoom control
        map.addControl( new GSmallZoomControl() );
        // draw map
        map.setCenter( new GLatLng( 0 , 0 ) , 1 );
	}
}
//##################################################################
/*
function loadPaging(){
    var count = document.getElementById('ctl00_content_hdn_pagesCount');
    var store = document.getElementById('store');
    
    if( count.value != store.value ){
        //alert(count.value);
        store.value = count.value;
        displayTen()  
    }
    
}
//##################################################################
function displayTen(){
    var limit = +document.getElementById('limit').value;
    var td = document.getElementById('ctl00_content_clm_Pages');
    //alert(typeof limit);
    td.innerHTML = '<br />';
    
    for( i=1 ; i<=10 ; i++ ){
        td.innerHTML += '<span class="paging"><a href="javascript:__doPostBack(\'ct100$content$page'+(limit + i)+'\',\'\');">'+ (limit + i) + '</a></span> ';
    }
    
    td.innerHTML += '<span class="paging">Next 10 ></span> ';
}*/
//##################################################################
function listener(){
    setInterval( getHiddenValue , 100 );
}
//##################################################################
function getHiddenValue(){
    var hdn = $('ctl00_content_hdn_Location');
    var r = '';
    
    if( hdn.value != '' ){
    
        //alert( hdn.value );
        //store value
        r = hdn.value;
        //reset hidden
        hdn.value = '';
        //call Google API
        renderAirport( r );
        
    }
}
//##################################################################
function renderAirport( r ){
    var coordinates = r.split('|');
    
    // if browser is compatible
	if ( GBrowserIsCompatible() ) {
	
	    point = new GLatLng( coordinates[1] , coordinates[0] );
        // get container
        var map = new GMap2( document.getElementById("vmaps") );
        // set map type
        //map.addControl( new GMapTypeControl() );
        // small zoom control
        map.addControl( new GSmallZoomControl() );
        // draw map
        map.setCenter( point , 6 );
        //add marker
        marker = new GMarker( point );
		map.addOverlay( marker );
	
	}
}
//##################################################################
//distance between 2 airports
function getDistance(){

    //var CalcCode1 = $('ctl00_content_txt_CalcCode1').value;
    //var CalcCode2 = $('ctl00_content_txt_CalcCode2').value;
    
    //if( CalcCode1 != '' && CalcCode2 != '' ){
        //init( tempIDArrayFrom[1] , tempIDArrayFrom[2] , tempIDArrayTo[1] , tempIDArrayTo[2] );
    //}else{
        //$('distance_div').style.display = 'block';
        //$('distance_div').innerHTML = '<span style="color:red;">Please enter departure and arrival values.</span>';
    //}
    
            //check if boxes values r selected from the suggest menu
        f_ = document.getElementById('ctl00_content_hdn_CalcCode1');
        t_ = document.getElementById('ctl00_content_hdn_CalcCode2');
        //alert(f_.value);
        //if( f_.value != t_.value ){
            //all empty or one of the is empty
            if( document.getElementById('ctl00_content_txt_CalcCode1').value == '' || document.getElementById('ctl00_content_txt_CalcCode2').value == '' ){
                alert('Please provide departure and arrival airports.');
            //boxes values r the same
            }else if( document.getElementById('ctl00_content_txt_CalcCode1').value == document.getElementById('ctl00_content_txt_CalcCode2').value ){
                alert('Starting and ending distinations cannot be the same.');
            //didnt click on suggest item
            }else if( document.getElementById('ctl00_content_txt_CalcCode1').value == 0 || document.getElementById('ctl00_content_txt_CalcCode2').value == 0 ){
                f_.style.border = '1px solid #FF0000';
                alert('Please provide departure and arrival airports.');
            //ok, proceed
            }else{
                f_.style.border = '1px solid #AFAFAF';
                lon1=f_.value.split('|')[1];
                lat1=f_.value.split('|')[2];
                lon2=t_.value.split('|')[1];
                lat2=t_.value.split('|')[2];
                init(lon1, lat1, lon2, lat2);
                //obsoloete
                //init( tempIDArrayFrom[1] , tempIDArrayFrom[2] , tempIDArrayTo[1] , tempIDArrayTo[2] );
            }
}
//##################################################################
function init( lon1 , lat1 , lon2 , lat2 ) {
  
  // if browser is compatible
  if ( GBrowserIsCompatible() ) {
    
    // lat , lon
	var point1 = new GLatLng( lat1 , lon1 );
	var point2 = new GLatLng( lat2 , lon2 );
	var distance_div = $('distance_div');
	
	var d = ( point1.distanceFrom( point2 ) / 1000 ) * 0.621371192;
    
    dist_in_miles_from_google = d.toFixed(0);
    dist_in_kms = dist_in_miles_from_google / 0.621371192;
    
    //add the distance in a div
    distance_div.style.display = 'block';
    distance_div.innerHTML = 'Distance between ' + $('ctl00_content_txt_CalcCode1').value + ' and ' + $('ctl00_content_txt_CalcCode2').value + ' is:<br />';
    distance_div.innerHTML += dist_in_miles_from_google + ' Miles (' + Math.round( dist_in_kms ) + ' KMs)';
    distance_div.innerHTML += '<br /><a style="font-size:10px;" href="#" onclick="initMapAirportCatalogLines('+lat1+','+lon1+','+lat2+','+lon2+');return false;">View on map</a>';
    
    //getData4( 'gM' , 'gDistance' );
    //initMapAirportCatalogLines( lat1 , lon1 , lat2 , lon2 )
	
  }
}
//##################################################################
//init map for one leg and round trip
function initMapAirportCatalogLines( lat1 , lon1 , lat2 , lon2 ) {//alert(f1);alert(t1);

  // if browser is compatible
  if ( GBrowserIsCompatible() ) {
    
		// === The basis of the arrow icon information ===
		var arrowIcon = new GIcon();
		arrowIcon.iconSize = new GSize(24,24);
		arrowIcon.shadowSize = new GSize(1,1);
		arrowIcon.iconAnchor = new GPoint(12,12);
		arrowIcon.infoWindowAnchor = new GPoint(0,0);
		  
		// === Returns the bearing in degrees between two points. ===
		// North = 0, East = 90, South = 180, West = 270.
		var degreesPerRadian = 180.0 / Math.PI;
		
		function bearing( from , to ) {
			  // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
			  // Convert to radians.
			  var lat1 = from.latRadians();
			  var lon1 = from.lngRadians();
			  var lat2 = to.latRadians();
			  var lon2 = to.lngRadians();
	
			  // Compute the angle.
			  var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
			  if ( angle < 0.0 ) angle  += Math.PI * 2.0;
	
			  // And convert result to degrees.
			  angle = angle * degreesPerRadian;
			  angle = angle.toFixed(1);
	
			  return angle;
		}
		
		// create a marker			
		function createMarker( point , html ) {
          var marker = new GMarker(point);
          //GEvent.addListener(marker, "click", function() {
            //marker.openInfoWindowHtml(html);
          //});
          return marker;
        }
        
		// get container			
		var mapOtherLegs = new GMap2( document.getElementById("vmaps") );
		mapOtherLegs.setCenter( new GLatLng( 0 , 0 ) , 0 );
					
		// ===== Start with an empty GLatLngBounds object =====
		var bounds_ = new GLatLngBounds();
		
		// set map type
		var mapControl_ = new GMapTypeControl();
		mapOtherLegs.addControl( mapControl_ );
		mapOtherLegs.addControl( new GSmallZoomControl );
			
		// === The array of points for the polyline ===
        var points_ = [];
	    point1_ = new GLatLng( lat1 , lon1 );
	    point2_ = new GLatLng( lat2 , lon2 );
	    //prepare the points array
        points_.push( point1_ , point2_ );
	    
        // add marker to the selected lon , lat
        // info Windows
        xxOtherLegs1 = createMarker( point1_ );
        mapOtherLegs.addOverlay( xxOtherLegs1 );
        xxOtherLegs2 = createMarker( point2_ );
        mapOtherLegs.addOverlay( xxOtherLegs2 );   		        

        // ==== Each time a point is found, extent the bounds to include it =====
        bounds_.extend(point1_);
        bounds_.extend(point2_);
				
		// === Create the polyline
		mapOtherLegs.addOverlay(new GPolyline(points_));//,color,line_width
		
		// ===== determine the zoom level from the bounds =====
        mapOtherLegs.setZoom(mapOtherLegs.getBoundsZoomLevel(bounds_));

        // ===== determine the centre from the bounds ======
        mapOtherLegs.setCenter(bounds_.getCenter());

	}
}
//##################################################################

