var IP2Location = {
    isResolved: false,
    provider: null,
    data:[],    
    iata:"BER",
    convertDecDeg: function(v,tipo) {
	    if (!tipo) tipo='N';
	    var deg;
	    deg = v;
	    if (!deg){
		    return "";
	    } else if (deg > 180 || deg < 0){
		    // convert coordinate from north to south or east to west if wrong tipo
		    return convertDecDeg(-v,(tipo=='N'?'S': (tipo=='E'?'W':tipo) ));
	    } else {
		    var gpsdeg = parseInt(deg);
		    var remainder = deg - (gpsdeg * 1.0);
		    var gpsmin = remainder * 60.0;
		    var D = gpsdeg;
		    var M = parseInt(gpsmin);
		    var remainder2 = gpsmin - (parseInt(gpsmin)*1.0);
		    var S = parseInt(remainder2*60.0);
		    return D+"&deg; "+M+"' "+S+"'' "+tipo;
	    }
    },
    distance: function(lat1,lon1,lat2,lon2) {
	    var R = 6371; // km (change this constant to get miles)
	    var dLat = (lat2-lat1) * Math.PI / 180;
	    var dLon = (lon2-lon1) * Math.PI / 180;
	    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
		    Math.sin(dLon/2) * Math.sin(dLon/2);
	    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	    var d = R * c;
        return Math.round(d);
    },
    getValidProviders: function(p, v, n) {
        if (!isNaN(parseFloat(p.latitude)) && !isNaN(parseFloat(p.longitude))) {
            var x = []; x['json'] = p; x['name'] = n; v[v.length] = x;
        }
    },
    checkRating: function(c) {
        if (c) {
            if (c.from === "ipinfodb" || c.to === "ipinfodb") return "ipinfodb";
            else if (c.from === "google" || c.to === "google") return "google";
            else if (c.from === "WIPlocation" || c.to === "WIPlocation") return "WIPlocation";
            else if (c.from === "hostip" || c.to === "hostip") return "hostip";
        }
        
        return false;
    },
    getProvider: function() {
        //ipinfodb, google.loader.ClientLocation, WIPlocation, hostip
        var providers = [];
        if (typeof (ipinfodb) != 'undefined') this.getValidProviders(ipinfodb, providers, 'ipinfodb');        
        if (google && google.loader && google.loader.ClientLocation) {
            this.getValidProviders(google.loader.ClientLocation, providers, 'google'); 
        }
        
        if (typeof (WIPlocation) != 'undefined') this.getValidProviders(WIPlocation, providers, 'WIPlocation');
        //var hostip = {"country":"Cambodia","city":"Siem Reap (REP)","latitude":"13.410666","longitude":"103.81284"};
        if (typeof (hostip) != 'undefined') this.getValidProviders(hostip, providers, 'hostip');

        if (providers.length > 1) {
            var city_distances = [];
            var matches = [];
            for (var i=0; i<providers.length; i++) {
                for (var j=0; j<providers.length; j++) {
                    if (i != j) {
                        var pi = providers[i]['name'];
                        var pj = providers[j]['name'];
                        
                        if (matches[pi] && matches[pi][pj]) {
                            continue;
                        } else {
                            var distance = this.distance(
                                providers[i]['json'].latitude, providers[i]['json'].longitude,
                                providers[j]['json'].latitude, providers[j]['json'].longitude);

                            var d = {};                                
                            d.distance = distance;
                            d.from = providers[i]['name'];
                            d.to = providers[j]['name'];
                            
                            city_distances[city_distances.length] = d;                            
                            
                            if (!matches[pi]) matches[pi] = [];
                            matches[pi][pj] = true;
                            
                            if (!matches[pj]) matches[pj] = [];
                            matches[pj][pi] = true;
                        }
                    }
                }
            }
            
            // Choose the shortest path
            var shortest = 0;
            for (var i=0; i<city_distances.length-1; i++) {
                for (var j=i+1; j<city_distances.length; j++) {
                    if (city_distances[j] < city_distances[i]) shortest = j;
                }
            }
            
            var chosen = this.checkRating(city_distances[shortest]);
            if (chosen) {
                switch (chosen) {
                    case "ipinfodb": return ipinfodb;
                    case "google": return google.loader.ClientLocation;
                    case "WIPlocation": return WIPlocation;
                }
            }
        } else if (providers.length > 0) return providers[0].json;
        
        return null;
    },
    resolve: function(cb) {
        this.provider = this.getProvider();
        if (this.provider) {
            var dataString = "latitude=" + this.provider.latitude + "&longitude=" + this.provider.longitude;
            var url = window.location.protocol + '//' + window.location.host + '/service/info/getcoordinates.php';
            $.getJSON(url, dataString,
                function(data) {
				    this.data = data;
					
				    for(var x=0; x < data.length; x++) {
					    if (typeof(data[x].iata)!=='undefined' && data[x].iata.length > 0) {
						    this.iata = data[x].iata;
						    this.isResolved = true;
						    break;
					    }
				    }
				    
				    if (cb && typeof(cb) === "function") cb(this.iata);
                }
            );
        } else {
            if (cb && typeof(cb) === "function") cb(this.iata);
        }
    }
};

function manageCookies(iata) {    
	// Check if there are parameters on URL
	var link = window.location.href;
	link = (link.indexOf('?') !== -1) ? link.substring(link.indexOf('?') + 1) : "";
	
	if (typeof (Cookies) != 'undefined') {
		var params = ['from', 'to','date', 'rdate', 'airline_restrict', 'pax', 'mp_direct_fdfn',
						'mode', 'tarif_klasse', 'pt', 'pax_chd1', 'pax_chd2', 'pax_chd3', 'chd_count', 'dep', 'dest', 'hotel'];
		var jsn = {};
		
		if (typeof (Validator) != 'undefined' && Validator) {
			Validator.params = params;
			Cookies.validator = Validator;
			
			if (link.length > 0) {
				if ('get_url_parameter' in Validator) {
					// url parameters were supplied by IBE search automatically, so only "from" and "pt" have to be checked.
					var prms = ['from', 'pt'];
					for (var i=0; i<prms.length; i++) {
						var pm = Validator.get_url_parameter(prms[i], window.location.href);
						if (pm.length > 0) jsn[prms[i]] = pm;
					}
					
					// Save all url parameters in Cookies
					//Cookies.saveURL(window.location.href);
				}
				
				if ('conditionalFilter' in Validator) {
					jsn = Validator.conditionalFilter(jsn);
					// Only "pt" has to be saved in Cookies.
					var pt = Validator.readJSONProperty(jsn, ["info"]);
					if (pt != undefined) {
						Cookies.save("pt", jsn["pt"]);
					} else {
						if (Cookies.exist("pt")) {
							jsn["pt"] = Cookies.read("pt", "x");
							jsn = Validator.conditionalFilter(jsn);
						}
					}
				}
			} else {
				jsn = Cookies.getAsJSON();
			}
		} else {
			if (link.length == 0) jsn = Cookies.getAsJSON();
		}
		
		//Check availability of "from".
		if (typeof(jsn["from"]) === "undefined") {
			jsn["from"] = iata;
		} else {
			// Protect app.unlock() by supplying at least one property
			//if (link.length > 0) { delete jsn["from"]; }
		}
		
		// Call Flight interface
		var r=false,w;
		
		if('parent' in this)w=this.parent;
		if(w&&('iataFind' in w)&&(typeof(w.iataFind)==='object')&&
		    ('containerWindow' in w.iataFind)&&(w.iataFind.containerWindow===w)){
			r=w.iataFind;
			var res = false;
			if(r!==false) {
				res=r.setParameters(jsn);
			}
		}
	    
	} // if typeof (Cookies)
}

addLoadEvent (function() {
    window.setTimeout(function() {
        IP2Location.resolve(manageCookies);
    });
});
