﻿//version 1.2 17/11/2009 : no timeouts to improve performance

var htdocs_url = 'http://www.newtowninstitute.org';
window.dhtmlHistory.create();
var planner_id = 0;
var country_id = 0;
var min_year= -10000;
var max_year= 10000;
var planner_name;
var country_name;
var change_country = false; // is true when a country has been changed (remove possible)
var change_planner = false; // is true when a planner has been changed (remove possible)
var change_year= false;
var list_planners;
var list_countries;


var historyChange = function(newlocation, historyObject) {
	if (newlocation != ''){
		country_id = historyObject.country_id;
		planner_id = historyObject.planner_id;
		country_name = historyObject.country_name;
		planner_name = historyObject.planner_name;
		min_year = historyObject.min_year;
		max_year = historyObject.max_year;
		change_planner = historyObject.change_planner;
		change_country = historyObject.change_country;
		refreshPage();
	}
}

window.onload = function() { 
	/// rsh
	$("#planner_remove").hide();
	$("#country_remove").hide();
	$("#year_remove").hide();
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyChange);
	var initialLocation = dhtmlHistory.getCurrentLocation();
	if (initialLocation ==''|| initialLocation== undefined){
		var historyObject = new Object();
		historyObject.country_id = 0;
		historyObject.planner_id = 0;
		historyObject.planner_name = '';
		historyObject.country_name = '';
		historyObject.min_year = -10000;
		historyObject.max_year = 10000;
   		initialLocation = "first";
   		dhtmlHistory.add(initialLocation, historyObject);
   		refreshPage();
   	}
}

function createXMLHttpRequest( ) {
	var request = false;
	/* Does this browser support the XMLHttpRequest object? */
	if (window.XMLHttpRequest) {
		if (typeof XMLHttpRequest != 'undefined')
			/* Try to create a new XMLHttpRequest object */
			try {
				request = new XMLHttpRequest( );
			} catch (e) {
				request = false;
			}
	/* Does this browser support ActiveX objects? */
	} else if (window.ActiveXObject) {
		/* Try to create a new ActiveX XMLHTTP object */
		try {
			request = new ActiveXObject('Msxml2.XMLHTTP');
		} catch(e) {
			try {
				request = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {
				request = false;
			}
		}
	}
	return request;
};

//-- requestData will trigger load_selectors.cgi, parse the response,
//-- make an array of it

function requestData(request, p_URL, p_data, p_divname) {
	var resultsArray = new Array();
	var resp = new Object();
	var allResults=''
	/* Does the XMLHttpRequest object exist? */
	if (request) {
		request.open('GET', p_URL+'?'+p_data, true);
		request.onreadystatechange = function(){
			if (request.readyState == 4) {
				//alert('ready state 4');
				if (request.status == 200) {
					//alert('ready state 200');
					var response = request.responseText;
					// here is where the parsing would begin.	
					var jsonString = request.responseText;
					// use this to debug cgi
					//document.getElementById('debug').innerHTML += jsonString;
					var response = eval('(' + jsonString + ')');
					for (i = 0, il = response.results.length; i < il; i++) {
						var resp = response.results[i];	
						if (isEmpty(resp)) resultsArray.push({name:resp.result_name, id:resp.result_id});
					}
					if (p_divname == 'planners'){
						listAlwaysShow('planners',resultsArray);			
					}
					else if (p_divname == 'countries'){
						list_countries = listAlwaysShow('countries',resultsArray);
					}
					else if (p_divname == 'cities'){
						autocomplete('cities',resultsArray);
					}
					else{
						displayTowns(resultsArray);
					}
				} else
					alert('There was a problem retrieving the data: \n' + request.statusText+'request.status='+request.status);
				request = null;
			}			
		}
		request.send(null);
	}
}

function isEmpty(object) {
	for(var i in object) { return true; }
	return false;
}

function listAlwaysShow(itemName,resultsArray) {
    // Use a LocalDataSource
    var oDS = new YAHOO.util.LocalDataSource(resultsArray);
  	oDS.responseSchema = {fields : ["name", "id"]}; 

    // Instantiate the AutoComplete
    var oAC = new YAHOO.widget.AutoComplete("search-"+itemName, itemName+"_container", oDS);
  	oAC.resultTypeList = false;
    oAC.minQueryLength = 0; // Can be 0, which will return all results
    oAC.maxResultsDisplayed = 100; // Show more results, scrolling is enabled via CSS
    oAC.animVert = false;
    oAC.highlightClassName = "itemHighlightClass"; 
    oAC.prehighlightClassName = "itemPrehighlightClass";
    oAC.autoHighlight = true;
    oAC.forceSelection = true;
    //oAC.typeAhead = true; 
   	oAC.getInputEl().focus();
	oAC.alwaysShowContainer = true;
	setTimeout(function() { // For IE
   		oAC._bFocused = null;   	
		oAC.sendQuery("");
	},0);
 
    // Populate list to start a new interaction

	oAC.itemSelectEvent.subscribe(function(sType, aArgs) {
      setTimeout(function() { // For IE
     // alert("in 1st subcription");
   		oAC.getInputEl().focus();
  		oAC._bFocused = null; 
		oAC.sendQuery("");
     },0);
    });

    // Define an event handler to populate a hidden form field
    // when an item gets selected
    var myHandler = function(sType, aArgs) {
	    oAC.getInputEl().focus();
        var myAC = aArgs[0]; // reference back to the AC instance
        var elLI = aArgs[1]; // reference to the selected LI element
        var oData = aArgs[2]; // object literal of selected item's result data
       
        if (itemName == 'countries') { 
            country_id = oData.id;
        	country_name = oData.name;
        	change_country = true;
        }
        else if (itemName == 'planners') {
        	planner_id = oData.id;
        	planner_name = oData.name;
        	change_planner = true;
        }
        else{
        	alert("itemname is unknown");
        }
      	refreshPage();    
    };
    oAC.itemSelectEvent.subscribe(myHandler);
    return {
        oDS: oDS,
        oAC: oAC
    };
};

function autocomplete(itemName,resultsArray) {
    var oDS = new YAHOO.util.LocalDataSource(resultsArray);
  	oDS.responseSchema = {fields : ["name", "id"]}; 

    // Instantiate the AutoComplete
    var oAC = new YAHOO.widget.AutoComplete("search-"+itemName, itemName+"_container", oDS);
    //oAC.prehighlightClassName = "yui-ac-prehighlight";
    oAC.alwaysShowContainer = false;
    oAC.useShadow = true;
    oAC.resultTypeList = false;
    //oAC.maxResultsDisplayed = 100; // Show more results, scrolling is enabled via CSS
    oAC.forceSelection = true; 
    oAC.sendQuery("");

	
    // Populate list to start a new interaction
    oAC.itemSelectEvent.subscribe(function(sType, aArgs) {
      setTimeout(function() { // For IE
		oAC.sendQuery("");
      },100);
    });

    // Define an event handler to populate a hidden form field
    // when an item gets selected
    var myHiddenField = YAHOO.util.Dom.get("hidden_"+itemName);
    var myHandler = function(sType, aArgs) {
    	var selectedTown;
        var myAC = aArgs[0]; // reference back to the AC instance
        var elLI = aArgs[1]; // reference to the selected LI element
        var oData = aArgs[2]; // object literal of selected item's result data
    // update hidden form field with the selected item's ID
        myHiddenField.id = oData.id;
        myHiddenField.name = oData.name;
       	selectedTown = myHiddenField.id;
        town_name = myHiddenField.name;
        window.open("http://www.newtowninstitute.org/cgi-bin/long_info_new.cgi?id="+selectedTown, "_self");

    };
    oAC.itemSelectEvent.subscribe(myHandler);
    return {
        oDS: oDS,
        oAC: oAC
    };
};
function submitTimeForm(obj){
	for (i=0; i<obj.childNodes.length; i++) {
		if (obj.childNodes[i].tagName == "INPUT") {
			if (obj.childNodes[i].type == "text") {
			   if (obj.childNodes[i].name =='yearFrom') min_year = obj.childNodes[i].value;
			   else if (obj.childNodes[i].name =='yearTo') max_year = obj.childNodes[i].value;
			}
		}   
	}
	refreshPage();
}



function refreshPage(){
// 	 displays search results inside the towns div
//   updates country div: 
//   - if a planner already has been selected displays only
//   the countries related to the planner
//   - if a country has been selected shows the possibility to remove the country
//   updates planner div (same as country)

//	document.getElementById('debug').innerHTML = "Change_planner="+change_planner+" | change_country= "+change_country +", planner_name= "+planner_name+", country_name= "+country_name;

	var countries = new Array();
	var planners = new Array();
	var towns = new Array();
	
	//	prepare history object
	var historyObject = new Object();
	historyObject.country_id = country_id;
	historyObject.planner_id = planner_id;
	historyObject.planner_name = planner_name;
	historyObject.country_name = country_name;
	historyObject.min_year = min_year;
	historyObject.max_year = max_year;
	historyObject.change_planner = change_planner;
	historyObject.change_country = change_country;

	//preparing url	
	var location ='';
	if (country_id > 0) {
		country_url = country_name.replace(/ /g,'_');
		country_url = country_url.replace(/\(|\)|\'/g,'');
		country_url = country_url.replace('ô','o');
		location += country_url+'/';
	}
		
	if (planner_id > 0) {
		planner_url = planner_name.replace(/ /g,'_');
		planner_url = planner_url.replace(/,|\./g,'');
		location += planner_url+'/';
	}
	if (location =='') location='first'
	if (min_year > -10000 || max_year < 10000) location += min_year+'-'+max_year

	//requesting and loading towns
	var request3 = createXMLHttpRequest( );
	requestData(request3, htdocs_url+'/cgi-bin/search_towns.cgi','country_id='+country_id+'&planner_id='+planner_id+'&min_year='+min_year+'&max_year='+max_year, 'towns');

	dhtmlHistory.add(location,historyObject);
	//requesting and loading countries and planners
	if (location =="first"){ //first time loading and other times when nothing is selected
		//planners
		if (typeof list_planners != "undefined") {
			list_planners.oAC.itemSelectEvent.unsubscribeAll();
		};
		var request2 = createXMLHttpRequest( );
		$("#planners_container").empty();
		requestData(request2, htdocs_url+'/cgi-bin/load_selectors.cgi','show=planners&country_id='+country_id+'&planner_id='+planner_id+'&min_year='+min_year+'&max_year='+max_year, 'planners');
		//countries
		var request1 = createXMLHttpRequest();
		if (typeof list_countries != "undefined") {
			list_countries.oAC.itemSelectEvent.unsubscribeAll(); 
		};
		requestData(request1, htdocs_url+'/cgi-bin/load_selectors.cgi','show=countries&country_id='+country_id+'&planner_id='+planner_id+'&min_year='+min_year+'&max_year='+max_year, 'countries');
	// for back button in case something had been selected
		$("#AC_countries").show(); 
		$("#country_remove").hide();
		$("#AC_planners").show(); 
		$("#planners_remove").hide();
	}
	if (change_country){ // a country has been selected
		var country_remove = country_name +"<span style='cursor: pointer' onclick='removeCountry();' ><img src='http://www.newtowninstitute.org/database/images/INTIremove.gif'/> </span>";
		document.getElementById('country_remove').innerHTML = country_remove;
		$("#country_remove").show();
		$("#AC_countries").hide();
		//change_country = false;
		if (planner_id == 0){
			resetPlannerList();
		}
	}
	if (change_planner){
		var planner_remove= planner_name +"<span style='cursor: pointer' onclick='removePlanner();' ><img src='http://www.newtowninstitute.org/database/images/INTIremove.gif'/> </span>";
		document.getElementById('planner_remove').innerHTML = planner_remove;
		$("#AC_planners").hide();
		$("#planner_remove").show();
		//change_planner = false;
		if (country_id == 0){
			resetCountryList();
		}
	}
	//handling years
	if (min_year > -10000 || max_year < 10000){
		$("#input_years").hide();
		$("#year_remove").show();
		year_remove= min_year+' to '+max_year +"<span style='cursor: pointer' onclick='removeYears();' ><img src='http://www.newtowninstitute.org/database/images/INTIremove.gif'/> <\/span>";
		document.getElementById('year_remove').innerHTML = year_remove;
	};
};

function displayTowns(towns){
	var townsHtml = ''
	/* Loop through the towns */
	if (towns.length > 0){
		for (i = 0, il = towns.length; i < il; i++) {
			townsHtml += towns[i].name;
		}
		document.getElementById('towns').innerHTML = townsHtml;
	}
	else document.getElementById('towns').innerHTML = "no towns available";	
	
};
function removeCountry(){
	country_name ='';
	country_id = 0; 
	change_country = false;
	//change_planner = true;
	//refreshPage();
	if (planner_id > 0) {
		resetCountryList();
	}
	else {
		$("#AC_countries").show(); 
		$("#country_remove").hide();
	}
	refreshPage();
}
function removePlanner(){
	planner_name ='';
	planner_id = 0; 
	change_planner = false;
	//change_planner = true;
	//refreshPage(); 
	if (country_id >0){
		resetPlannerList();
	}
	else{
		$("#AC_planners").show(); 
		$("#planner_remove").hide();
	}
	refreshPage();
}
function removeYears(){
	min_year = -10000;
	max_year = 10000;
	refreshPage();
	$("#input_years").show();
	$("#year_remove").hide();
}
function resetCountryList(){
	$("#AC_countries").show();
	$("#country_remove").hide();
	var request1 = createXMLHttpRequest();
	$("#countries_container").empty();
	//list_countries.oAC.itemSelectEvent.unsubscribeAll(); //important: unsubscribing old list
	if (typeof list_countries != "undefined") {
		list_countries.oAC.itemSelectEvent.unsubscribeAll(); 
	};
	requestData(request1, htdocs_url+'/cgi-bin/load_selectors.cgi','show=countries&country_id='+country_id+'&planner_id='+planner_id+'&min_year='+min_year+'&max_year='+max_year, 'countries');	
}
function resetPlannerList(){
	$("#AC_planners").show();
	$("#planner_remove").hide();
	var request2 = createXMLHttpRequest( );
	$("#planners_container").empty();
	//list_planners.oAC.itemSelectEvent.unsubscribeAll(); //important: unsubscribing old list
	if (typeof list_planners != "undefined") {
		list_planners.oAC.itemSelectEvent.unsubscribeAll();
	};
	requestData(request2, htdocs_url+'/cgi-bin/load_selectors.cgi','show=planners&country_id='+country_id+'&planner_id='+planner_id+'&min_year='+min_year+'&max_year='+max_year, 'planners');
}
function loadSearchTowns(){
	var request4 = createXMLHttpRequest( );
	requestData(request4, htdocs_url+'/cgi-bin/load_selectors.cgi','show=towns', 'cities');
}

