var url = "/ajax.php";
var navactive;

window.onload = init;

function init()
{
	initCalendar('departure');
	initCalendar('arrival');
	initCalendar('loading_from');
	initCalendar('loading_till');
	initCalendar('delivery_from');
	initCalendar('delivery_till');
	
	initNav();
	initSelectCountries();
	
	initCitySearch();
	
	initCapacityCalc();
}

function initNav()
{
	var nav = $('navlist');
	if (nav) {
		var items = nav.childElements();
		var links = nav.getElementsByTagName('a');
		for (i = 0; i < links.length; i++) {
			links[i].onfocus = function() { this.blur(); }
		}
		
		for (i = 0; i < items.length; i++) {
			var li = items[i];
			
			var subs = li.getElementsByTagName('ul');
			if (subs.length == 0) continue;
			
			var a = li.getElementsByTagName('a')[0];
			a.onclick = function() {
				var li = this.parentNode;
				if (li.className == 'active') {
					li.removeClassName('active');
					navactive = false;
				}
				else if (li.className == '') {
					if (navactive) {
						navactive.removeClassName('active');
						navactive = false;
					}
					li.addClassName('active');
					navactive = li;
				}
				
				return false;
			}
		}
	}
}

function initCalendar(id)
{
	var calendar = $(id);
	if (calendar) {
	    Calendar.setup({
	        inputField     :    id,      // id of the input field
	        ifFormat       :    "%d-%m-%Y",       // format of the input field
	        showsTime      :    false,            // will display a time selector
	        button         :    "calendar-" + id,   // trigger for the calendar (button ID)
	        singleClick    :    true,           // double-click mode
	        step           :    1,                // show all years in drop-down boxes (instead of every other year as default)
	        firstDay       :    1
	    });
	}
}

function initSelectCountries()
{
	var ul = $('select-countries');
	
	if (ul) {
		var items = ul.getElementsByTagName('li');
		var total = items.length;
		for (i = 0; i < total; i++) {
			items[i].onclick = selectCountry;
		}
	}
	
	var ul = $('selected-countries');
	
	if (ul) {
		var items = ul.getElementsByTagName('li');
		var total = items.length;
		for (i = 0; i < total; i++) {
			items[i].onclick = selectCountry;
		}
	}
}


function selectCountry()
{
	var parentID = this.parentNode.getAttribute('id');

	if (parentID == "select-countries") {
		var selected = $('selected-countries');
		this.parentNode.removeChild(this);
		this.getElementsByTagName('input')[0].disabled = false;
		selected.appendChild(this);
	}
	if (parentID == "selected-countries") {
		var selected = $('select-countries');
		this.parentNode.removeChild(this);
		this.getElementsByTagName('input')[0].disabled = true;
		selected.appendChild(this);
	}
	
	sortListByName(selected);
}

function sortListByName(list)
{
	var arr = new Array();
	var childs = list.getElementsByTagName('li');
	
	//console.time('loadarr');
	var total = childs.length;
	for (i = 0; i < total; i++) {
		arr.push(childs[i]);
	}
	
	//console.timeEnd('loadarr');
	
	//console.time('sort');
	arr.sort(sortByName);
	//console.timeEnd('sort');
	
	//console.time('fill');
	var newlist = document.createElement('ul');
	newlist.setAttribute('id', list.getAttribute('id'));
	
	var length = arr.length;
	for (i = 0; i < length; i++) {
		newlist.appendChild(arr[i]);
	}
	
	list.parentNode.replaceChild(newlist, list);
	
	//console.timeEnd('fill');
}

function sortByName(a, b)
{
	av = a.firstChild.nodeValue;
	bv = b.firstChild.nodeValue;
    if ( av > bv ) return 1;
	else if ( av < bv ) return -1;
	else return 0; 
}

var locateSrc;

function initCitySearch()
{
    var input = $('origin-city');
    if (input) input.onblur = function() {
        doGoogleGeolocate(this,'origin-address','origin-countrycode','origin-lng','origin-lat','origin-cityname');
    }
    var input = $('destination-city');
    if (input) input.onblur = function() {
        doGoogleGeolocate(this,'destination-address','destination-countrycode','destination-lng','destination-lat','destination-cityname');
    }
    
	if (a) a.onclick = function() { 
		//var mywindow = popitup(this.href, 400, 300); 
		locateSrc = "origin";
		initGeo();
		return false;
	}
	
	var a = $('locate-origin');
	if (a) a.onclick = function() { 
		//var mywindow = popitup(this.href, 400, 300); 
		locateSrc = "origin";
		initGeo();
		return false;
	}
	var a = $('locate-origin2');
	if (a) a.onclick = function() { 
		//var mywindow = popitup(this.href, 400, 300); 
		locateSrc = "origin";
		initGeo();
		return false;
	}
	
	var a = $('locate-destination');
	if (a) a.onclick = function() { 
		//var mywindow = popitup(this.href, 400, 300); 
		locateSrc = "destination";
		initGeo();
		return false;
	}
	var a = $('locate-destination2');
	if (a) a.onclick = function() { 
		//var mywindow = popitup(this.href, 400, 300); 
		locateSrc = "destination";
		initGeo();
		return false;
	}


}

var googleGeoLocateResultAddressElement = null;
var googleGeoLocateCountryCodeElement = null;
var googleGeoLocateLongitudeElement = null;
var googleGeoLocateLatitudeElement = null;
var googleGeoLocateCityElement = null;


function doGoogleGeolocate(what,resultAddressElement,resultCountryCodeElement,resultLongitudeElement,resultLatitudeElement,resultCityElement){
    googleGeoLocateResultElement = resultAddressElement;
    googleGeoLocateCountryCodeElement = resultCountryCodeElement;
    googleGeoLocateLongitudeElement = resultLongitudeElement
    googleGeoLocateLatitudeElement = resultLatitudeElement;
    googleGeoLocateCityElement = resultCityElement;
    
    if (what.value=='') return false;
	var url = "/ajax.php";
	var pars = "action=googleGeolocate&adres="+encodeURIComponent(what.value);
	var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onLoading: loading, onException: err, onComplete: GoogleGeolocateResult });
     
    var resultElement = $(googleGeoLocateResultElement);
    if (resultElement) resultElement.value ='';
    var resultElement = $(googleGeoLocateCountryCodeElement);
    if (resultElement) resultElement.value ='';
    var resultElement = $(googleGeoLocateLongitudeElement);
    if (resultElement) resultElement.value ='';
    var resultElement = $(googleGeoLocateLatitudeElement);
    if (resultElement) resultElement.value ='';
    
}
function GoogleGeolocateResult(originalRequest, resultObj) {
    var jsonObj = originalRequest.responseText.evalJSON();
    var resultElement = $(googleGeoLocateResultElement);
    var countryCode = $(googleGeoLocateCountryCodeElement);
    var longitude = $(googleGeoLocateLongitudeElement);
    var latitude = $(googleGeoLocateLatitudeElement);
    var city = $(googleGeoLocateCityElement);
    if (jsonObj.Status.code==200) {
        //all's well
        if (jsonObj.Placemark.length>0) {
            if (resultElement) resultElement.value = jsonObj.Placemark[0].address;
            if (countryCode) countryCode.value = jsonObj.Placemark[0].AddressDetails.Country.CountryNameCode;
            if (longitude) longitude.value = jsonObj.Placemark[0].Point.coordinates[0];
            if (latitude) latitude.value = jsonObj.Placemark[0].Point.coordinates[1];
            if (city) {
                if (jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea) {
                    if (jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                    if (jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality!=undefined) 
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName;
                    else
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                    }
                    else {
                    if (jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality!=undefined) 
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName;
                    else
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
                        }
                }
                else if (jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea) {
                    if (jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.SubAdministrativeArea) {
                    if (jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.SubAdministrativeArea.Locality.DependentLocality!=undefined) 
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName;
                    else
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                    }
                    else {
                    if (jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.DependentLocality!=undefined) 
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName;
                    else
                        city.value = jsonObj.Placemark[0].AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
                        }
                }
            else {
                if (jsonObj.Placemark[0].AddressDetails.Country.AddressLine)
                   city.value = jsonObj.Placemark[0].AddressDetails.Country.AddressLine[0];
                if (jsonObj.Placemark[0].AddressDetails.Country.Locality)
                   city.value = jsonObj.Placemark[0].AddressDetails.Country.Locality.LocalityName;
                }
            }
        }
        else alert('google could not find the address!');
        }
    else alert('google geoLocate could not complete: error '+jsonObj.Status.code)

}


function citySearch()
{
	//var url = "http://euromove.creationpoint.nl/ajax.php";
	var url = "/ajax.php";
	
	var pars = "action=citysearch&q=" + encodeURIComponent($F('search'));
	var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onLoading: loading, onException: err, onComplete: showCitySearchResults }); 

	return false;
}

function err(e, ee)
{
	console.log(ee);
}

function loading(e, ee)
{
	var div = $('search-result');
	if (div.childNodes.length > 0) div.removeChild(div.childNodes[0]);
	var p = document.createElement('p');
	p.innerHTML = 'Searching...';
	div.appendChild(p);
}

var cities;

function showCitySearchResults(originalRequest, jsonObj)
{
	var jsonObj = eval('(' + originalRequest.responseText + ')');
	if (jsonObj != null) {
	
		cities = jsonObj.geonames;

	
		var table = document.createElement('table');
		table.className = 'overzicht';
		var thead = document.createElement('thead');
		
		var tr = document.createElement('tr');
		
		var th = document.createElement('th');
		th.appendChild(document.createTextNode("City"));
		tr.appendChild(th);
		
		var th = document.createElement('th');
		th.appendChild(document.createTextNode("State"));
		tr.appendChild(th);
		
		var th = document.createElement('th');
		th.appendChild(document.createTextNode("Country"));
		tr.appendChild(th);
		
		var th = document.createElement('th');
		th.appendChild(document.createTextNode(""));
		tr.appendChild(th);
		
		thead.appendChild(tr);
		table.appendChild(thead);
		
		var tbody = document.createElement('tbody');
		
		var j = 0;

		
		for (i = 0; i < cities.length; i++) {
			if (cities[i].fcl != 'P') continue;
			j++;
			var tr = document.createElement('tr');
			if (j % 2 == 0) tr.className = 'even';
			var td = document.createElement('td');
			
			var a = document.createElement('a');
			a.city = cities[i].name;
			a.countryCode = cities[i].countryCode;
			a.lng = cities[i].lng;
			a.lat = cities[i].lat;
			a.geonameId = cities[i].geonameId;
			a.adminName1 = cities[i].adminName1;
			a.appendChild(document.createTextNode(cities[i].name));
			a.onclick = function() {
				var lsrc = window.locateSrc;
				document.getElementById(lsrc + '-city').value = this.city;
				document.getElementById(lsrc + '-countrycode').value = this.countryCode;
				document.getElementById(lsrc + '-lng').value = this.lng;
				document.getElementById(lsrc + '-lat').value = this.lat;
				document.getElementById(lsrc + '-geonameId').value = this.geonameId;
				document.getElementById(lsrc + '-adminName1').value = this.adminName1;
				
				var a = $('close-geo-locate');
				a.onclick();
				return false;
			}
      
      			
			td.appendChild(a);
			tr.appendChild(td);
			
			var td = document.createElement('td');
			td.appendChild(document.createTextNode(cities[i].adminName1));
			tr.appendChild(td);
			
			var td = document.createElement('td');
			td.appendChild(document.createTextNode(cities[i].countryName));
			tr.appendChild(td);
 			
			tbody.appendChild(tr);
		}
		
		table.appendChild(tbody);
		var div = $('search-result');
		if (div.childNodes.length > 0) div.removeChild(div.childNodes[0]);
		div.appendChild(table);
	}
}


function popitup(url, w, h, scrolling)
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	
	newwindow=window.open(url, 'Euromove','height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scrolling);
	if (window.focus) {newwindow.focus()}
 	return newwindow;
}

function initGeo()
{
	div = document.createElement('div');
	div.setAttribute('id', 'geo-locate');
	
	var a = document.createElement('a');
	a.setAttribute('id', 'close-geo-locate');
	a.innerHTML = 'close';
	a.onclick = function() {
		var container = this.parentNode;
		container.parentNode.removeChild(container);
	}
	
	div.appendChild(a);
	
	var form = document.createElement('form');
	form.onsubmit = citySearch;
	form.setAttribute('id', 'form-searchcity');
	
	var label = document.createElement('label');
	label.innerHTML = 'Locate city: ';
	
	var inputT = document.createElement('input');
	inputT.setAttribute('type', 'text');
	inputT.setAttribute('id', 'search');
	inputT.setAttribute('name', 'search');
	
	var inputS = document.createElement('input');
	inputS.setAttribute('type', 'submit');
	inputS.setAttribute('value', 'Search');
	
	form.appendChild(label);
	form.appendChild(inputT);
	form.appendChild(inputS);
	div.appendChild(form);
	
	sdiv = document.createElement('div');
	sdiv.setAttribute('id', 'search-result');
	div.appendChild(sdiv);
	document.body.appendChild(div);
//	setTimeout("document.forms[1].search.focus()",300);
	setTimeout("try{document.forms['form-searchcity'].search.focus();}catch(err){void(0);}",300);
	

}


function initCapacityCalc() {
    var reportCapacityForm = $('report-capacity');
    if (reportCapacityForm) {
        var capacity = $('capacity');
        var capacityUsed = $('capacity_used');
        var capacityAvailable = $('capacity_available');
	    if (capacity && capacityUsed && capacityAvailable) {
	       capacity.observe('change',calcAvailable);
	       capacityUsed.observe('change',calcAvailable);
	       capacityAvailable.readOnly = true;
	    }
	}
}

function calcAvailable() {
   var capacity = $('capacity');
   var capacityUsed = $('capacity_used');
   var capacityAvailable = $('capacity_available');
   capacityAvailable.value = capacity.value - capacityUsed.value;
}



