// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// add history event
function addHistoryEvent(pageName, historyString) {
	dhtmlHistory.add(historyString.replace(/\"/g, '_1_').replace(/\'/g, '_2_').replace(/-/g, '_3_'), "");
	urchinTracker("/" + pageName + "#" + historyString);
}

/** Our callback to receive history change events. */
function historyChange(newLocation, historyData) {
	
	// alert('historyChange ['+newLocation+'] - ['+historyData+']');
	// get data from location if no data is provided
	if (newLocation.indexOf(";") > -1) {
		historyData = newLocation.substring(newLocation.indexOf(";") + 1);
		newLocation = newLocation.substring(0, newLocation.indexOf(";"));
	}
	
	// unescape special characters
	newLocation = newLocation.replace(/_1_/g, '\"').replace(/_2_/g, '\'').replace(/_3_/g, '-');

	// alert('historyChange ['+newLocation+'] - ['+historyData+']');

	//alert("new loc: ["+newLocation+"]");
	
	// show index page if nothing is in history
	if (newLocation == "" || newLocation == "do_nothing") {
		var xloc = "/places?style=" + css_id + "&owner_id=" + owner_id;
		//alert('xloc is ['+xloc+']');
		new Ajax.Updater("hvdcontent", xloc,{
		    evalScripts: true,
			method:'post',
		    onFailure: function(){ alert('Error: Something went wrong...') },
		    onException: function(req,ex){ alert('Exception: Something went wrong - '+ex.name+' occured : '+ex.message); }
		  });
		return false;
	}
	
	// get search page from history data
	if (newLocation.indexOf("search") == 0) {
		
		// extract data from location
		newLocation = newLocation.replace(/search\:/, "");
		search_type = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		type = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		result_view = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		search_data = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		query = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		page = newLocation;
		
		// do simple search
		if (search_type == "simple") {
			
			// extract search data and search objects
			data = search_data.substring(0, search_data.indexOf("|"));
			search_data = search_data.substring(search_data.indexOf("|") + 1);
			objects = search_data;
			
			// change data and objects to search for
			new Ajax.Request('/places/change_simple_search_data?data=' + data, { asynchronous:true, evalScripts:true });
			new Ajax.Request('/places/change_simple_search_objects?objects=' + objects, { asynchronous:true, evalScripts:true });
			
			// load simple search page if not yet loaded
			if (document.getElementById("suggestion_name") == null)
				new Ajax.Updater("hvdcontent", "/places?featured_place=false&query=" + query, { asynchronous:true, evalScripts:true });
			else
				document.getElementById("suggestion_name").value = unescape(query);	// insert query into text field
			
			// perform search
			new Ajax.Updater("result_div", "/places/execute_simple_search?query=" + query + "&page=" + page + "&result_view=" + result_view + "&type=" + type, { asynchronous:true, evalScripts:true });
		}
		
		// do advanced search
		else if (search_type == "advanced") {
			
			// load advanced search page
			new Ajax.Updater("hvdcontent", "/places/advanced_search?show=places&type=" + type + getParametersFromQuery(query), { asynchronous:true, evalScripts:true });
			
			// perform search
			new Ajax.Updater("result_div", "/places/execute_advanced_search?page=" + page + "&result_view=" + result_view + "&type=" + type + getParametersFromQuery(query), { asynchronous:true, evalScripts:true });
		}
		
		// do advanced shipwreck search
		else if (search_type == "advanced_ships") {
			
			// load advanced search page
			new Ajax.Updater("hvdcontent", "/places/advanced_search?show=shipwrecks&type=" + type + getParametersFromQuery(query), { asynchronous:true, evalScripts:true });
			
			// perform search
			new Ajax.Updater("result_div", "/places/execute_advanced_search_shipwrecks?page=" + page + "&result_view=" + result_view + "&type=" + type + getParametersFromQuery(query), { asynchronous:true, evalScripts:true });
		}
		
		// exit function
		return false;
	}
			   
	// load advanced search input fields
	if (newLocation.indexOf("advanced_ships") == 0) {
		new Ajax.Updater("hvdcontent", "/places/advanced_search?type=" + historyData + "&show=shipwrecks", { asynchronous:true, evalScripts:true });
		return false;
	}
	
	// load advanced search (shipwrecks) input fields
	if (newLocation.indexOf("advanced") == 0) {
		new Ajax.Updater("hvdcontent", "/places/advanced_search?type=" + historyData + "&show=places&database=true&register=true&inventory=true&councils=true", { asynchronous:true, evalScripts:true });
		return false;
	}
			   
	// load detail page for places
	if (newLocation.indexOf("detail_places") == 0) {
		new Ajax.Updater("hvdcontent", "/places/result_detail/" + historyData, { asynchronous:true, evalScripts:true });
		return false;
	}
			   
	// load detail places for ships
	if (newLocation.indexOf("detail_ships") == 0) {
		new Ajax.Updater("hvdcontent", "/shipwrecks/result_detail/" + historyData, { asynchronous:true, evalScripts:true });
		return false;
	}
			   
	// load large image carousel
	if (newLocation.indexOf("large_image_carousel") == 0) {
			    
		// extract page from location
		newLocation = newLocation.replace(/large_image_carousel\:/, "");
		place_id = newLocation.substring(0, newLocation.indexOf(":"));
		newLocation = newLocation.substring(newLocation.indexOf(":") + 1);
		index = newLocation.substring(0, newLocation.indexOf(";"));
				
		// update div
		new Ajax.Updater("hvdcontent", "/places/large_image_carousel?place_id=" + place_id + "&index=" + index, { asynchronous:true, evalScripts:true });
		return false;
	}
}

// extract parameters for url from history string
function getParametersFromQuery(query) {
	var res = "";
	if (query != "")	query = query.substring(1);
	
	// extract data, while string is not empty
	while (query != "") {
		
		// get key
		key = query.substring(0, query.indexOf("="));
		query = query.substring(query.indexOf("=") + 1);
		
		// end of string not reached, go on
		if (query.indexOf("=") > -1) {
			value = query.substring(0, query.indexOf("="));
			query = query.substring(query.indexOf("=") + 1);
		}
		
		// end of string reached, get last value
		else {
			value = query;
			query = "";
		}
		
		// if the scope is transmitted, then there is additional work to do. first split up the value var
		if (key == "scope") {
			var tokens = value.split("|");
			
			// for every found entry, add a parameter, but only, if theres not the councils involved
			for (var i = 0; i < tokens.length; i++) {
				if (tokens[i].indexOf("councils") == -1)
					res += "&" + tokens[i] + "=true";
				
				// if the councils have to be determinated, then add parameter manually
				else {
					res += "&councils=true";
					
					// if there are numbers given, get them and add them as a parameter
					if (tokens[i].indexOf("$") > -1) res += "&council_id=" + tokens[i].substring(tokens[i].indexOf("$") + 1);
				}
			}
		}
		
		// concat key value pair to existing url parameter string
		else
			res += "&" + key + "=" + value;
	}
	
	// return parameters
	return res;
}

// set the selected index of a dropdown box according to the given value
function changeValueOfSelect(object, value) {
	for (i = 0; i < object.length; i++) {
		if (object.options[i].value == value)	object.selectedIndex = i;
	}
}

function getSelectedCouncils(list) {
	var tokens = list.split("$");
	var councils = document.getElementById("advanced_data_council_id");
	
	// search entry in council select for every found token
	for (var i = 0; i < tokens.length; i++) {
		for (var j = 0; j < councils.options.length; j++) {
			if (councils.options[j].value == tokens[i])	councils.options[j].selected = true;
		}
	}
}
		
// check all fields of the advanced search, if at least one is not empty
function getValuesFromFields() {
	var res = "=scope="
	
	// if "search whole database" is checked then forward only one entry, if not get the other ones
	if (document.getElementById("advanced_data_database").checked)
		res += "database";
	else {
		
		// add register and inventory, if checked
		if (document.getElementById("advanced_data_register").checked)	res += "register|";
		if (document.getElementById("advanced_data_inventory").checked)	res += "inventory|";
		
		// check if the council checkbox is checked, if yes, get the selected councils
		if (document.getElementById("advanced_data_councils").checked) {
			res += "councils$";
			
			// get all selected council ids
			var councils = document.getElementById("advanced_data_council_id");
			for (var i = 0; i < councils.options.length; i++) {
				if (councils.options[i].selected)	res += councils.options[i].value + "$"
			}
		}
		
		// if the string ends with an '|' or an '$', cut that off
		if (res.substring(res.length - 1, res.length) == "|" || res.substring(res.length - 1, res.length) == "$")	res = res.substring(0, res.length - 1);
	}
	
	// check all standard search fields
	if (document.getElementById('withall').value != '')		res += "=withall=" + document.getElementById('withall').value;
	if (document.getElementById('exact').value != '')		res += "=exact=" + document.getElementById('exact').value;
	if (document.getElementById('atleast').value != '')		res += "=atleast=" + document.getElementById('atleast').value;
	if (document.getElementById('without').value != '') 	res += "=without=" + document.getElementById('without').value;
	if (document.getElementById('name').value != '')		res += "=name=" + document.getElementById('name').value;
	if (document.getElementById('vhr').value != '')			res += "=vhr=" + document.getElementById('vhr').value;
	if (document.getElementById('address').value != '')		res += "=address=" + document.getElementById('address').value;
	if (document.getElementById('architect').value != '')	res += "=architect=" + document.getElementById('architect').value;
		
	// check standard drop down boxes
	if (document.getElementById('agency_id') != null && document.getElementById('agency_id').value != '')	res += "=agency_id=" + document.getElementById('agency_id').value;
		
	// check if additional drop down boxes exist (no value check necessary)
	if (document.getElementById('style_id') != null)	res += "=style_id=" + document.getElementById('style_id').value;
	if (document.getElementById('group_id') != null)	res += "=group_id=" + document.getElementById('group_id').value;
	if (document.getElementById('category_id') != null)	res += "=category_id=" + document.getElementById('category_id').value;	
	if (document.getElementById('act_id') != null)		res += "=act_id=" + document.getElementById('act_id').value;
		
	// check all additional text field for existence and check the value
	if (document.getElementById('date') != null && document.getElementById('date').value != '') {
		res += "=date=" + document.getElementById('date').value;
		res += "=date_compare=" + document.getElementById('date_compare').value;
	}
	if (document.getElementById('extent') != null && document.getElementById('extent').value != '')		res += "=extent=" + document.getElementById('extent').value;
	if (document.getElementById('history') != null && document.getElementById('history').value != '')	res += "=history=" + document.getElementById('history').value;
	
	// every field was empty --> no search should be started
	return res;
}

// check all fields of the advanced search, if at least one is not empty
function getValuesFromFieldsForShipwreck() {
	var res = ""
		
	// check all standard search fields
	if (document.getElementById('withall').value != '')	res += "=withall=" + document.getElementById('withall').value;
	if (document.getElementById('exact').value != '')	res += "=exact=" + document.getElementById('exact').value;
	if (document.getElementById('atleast').value != '')	res += "=atleast=" + document.getElementById('atleast').value;
	if (document.getElementById('without').value != '') res += "=without=" + document.getElementById('without').value;
	if (document.getElementById('name').value != '')	res += "=name=" + document.getElementById('name').value;
	if (document.getElementById('swn').value != '')		res += "=swn=" + document.getElementById('swn').value;
	if (document.getElementById('address').value != '')	res += "=address=" + document.getElementById('address').value;
		
	// check if additional drop down boxes exist (no value check necessary)
	if (document.getElementById('propulsion_id') != null)		res += "=propulsion_id=" + document.getElementById('propulsion_id').value;
	if (document.getElementById('rig_id') != null)				res += "=rig_id=" + document.getElementById('rig_id').value;
	
	if (document.getElementById('primary_vessel_id') != null && document.getElementById('primary_vessel_id').value != '')		res += "=primary_vessel_id=" + document.getElementById('primary_vessel_id').value;
	if (document.getElementById('secondary_vessel_id') != null && document.getElementById('secondary_vessel_id').value != '')	res += "=secondary_vessel_id=" + document.getElementById('secondary_vessel_id').value;
		
	// check all additional text field for existence and check the value
	if (document.getElementById('yearbuilt') != null && document.getElementById('yearbuilt').value != '') {
		res += "=yearbuilt=" + document.getElementById('yearbuilt').value;
		res += "=yearbuilt_compare=" + document.getElementById('yearbuilt_compare').value;
	}
	if (document.getElementById('datelost') != null && document.getElementById('datelost').value != '')	{
		res += "=datelost=" + document.getElementById('datelost').value;
		res += "=datelost_compare=" + document.getElementById('datelost_compare').value;		
	}
	if (document.getElementById('departure') != null && document.getElementById('departure').value != '')		res += "=departure=" + document.getElementById('departure').value;
	if (document.getElementById('destination') != null && document.getElementById('destination').value != '')	res += "=destination=" + document.getElementById('destination').value;
	if (document.getElementById('passenger') != null && document.getElementById('passenger').value != '')		res += "=passenger=" + document.getElementById('passenger').value;
	if (document.getElementById('placebuilt') != null && document.getElementById('placebuilt').value != '')		res += "=placebuilt=" + document.getElementById('placebuilt').value;
	if (document.getElementById('registered') != null && document.getElementById('registered').value != '')		res += "=registered=" + document.getElementById('registered').value;
	
	// every field was empty --> no search should be started
	return res;
}

// returns the value of the radio button, if a new search is executed
function getRadioButtonValue(owner_id) {
	if (owner_id != 1)	return "owner";
	
	if (document.getElementById("target_data_owner").checked)		return "owner";
	else if (document.getElementById("target_data_local").checked)	return "local";
	else if (document.getElementById("target_data_ships").checked)	return "ships";
	else															return "database";
}

// returns the value of the data check box, if a new search is executed
function getDataCheckBoxValue(owner_id) {
	if (owner_id != 1)	return "owner";
	
	if (document.getElementById("target_simple_data").checked)		return "register";
	else															return "database";
}

// returns the value of the objects check box, if a new search is executed
function getObjectsCheckBoxValue(owner_id) {
	if (owner_id != 1)	return "places";
	
	if (document.getElementById("target_simple_objects").checked)	return "ships";
	else															return "places";
}

// enables or disables the check boxes at the advanced search screen
function showCheckBoxes(checked) {
	
	// enable all checkboxes
	if (!checked) { 
		document.getElementById("advanced_data_register").disabled = false;
		document.getElementById("advanced_data_inventory").disabled = false;
		document.getElementById("advanced_data_councils").disabled = false;
		
		// show councils select box, if according check box is selected
		showCouncilSelect(document.getElementById("advanced_data_councils").checked);
	}
	
	// disable all checkboxes
	else {
		document.getElementById("advanced_data_register").disabled = true;
		document.getElementById("advanced_data_inventory").disabled = true;
		document.getElementById("advanced_data_councils").disabled = true;
		
		// hide councils select box
		showCouncilSelect(false);
	}
}

// shows or hides the select-box of the councils in adavanced search
function showCouncilSelect(checked) {
	if (checked)
		document.getElementById("advanced_data_council_id").style.visibility = "visible";
	else
		document.getElementById("advanced_data_council_id").style.visibility = "hidden";
}

// change title of additional criteria field
function changeTitle(field_id) {
	var box = document.getElementById("addtional_criteria_id");
	
	if (field_id == "style")				box.title = "A classification of architecture e.g Federation";
	else if (field_id == "date")			box.title = "Date in which a building has been constructed. In some instance precise date is not known. Enter in a year e.g 1962";
	else if (field_id == "extent")			box.title = "Extent of all the building and land as defined by the Heritage Council.";
	else if (field_id == "history")			box.title = "";
	else if (field_id == "references")		box.title = "Name of author, publication or publication date e.g Dawson";
	else if (field_id == "group")			box.title = "Most registered places are allocated a thematic Group. Groups include education, health services, science and religion. An item can belong to one or more groups. Select the Item Group you wish to search on from the drop-down list.";
	else if (field_id == "category")		box.title = "Most registered places are allocated a typological Category.  The categories have a direct association with an Item Group.  Eg. in the Item Group �Military�, you�ll find related Item Categories like Air Raid Shelter, Battery and Fortification. An item can belong to one or more categories. Please note: you most choose a Group first, then a Category."
	else if (field_id == "act")				box.title = "Most places are allocated a Heritage Act Category.  Categories include Heritage Place and Archaeological Place.  An item can belong to one or more categories. Select the Heritage Act Category you wish to search on from the drop-down list.";
	else if (field_id == "yearbuilt") 		box.title = "Year of when the ship was built. e.g. 1901. In some instances, precise date is not known.";
	else if (field_id == "datelost") 		box.title = "Year of when the ship was lost e.g. 1901. In some instances, precise date is not known.";
	else if (field_id == "depature") 		box.title = "City or country where the ship departed from e.g. Liverpool";
	else if (field_id == "destination") 	box.title = "City or country where the ship intended to arrive at e.g. Melbourne";
	else if (field_id == "passenger") 		box.title = "Last names of passengers or crew identified on board the ship. In some instances, precise information is not known.";
	else if (field_id == "placebuilt") 		box.title = "City or country where the ship was built e.g. Liverpool";
	else if (field_id == "registered") 		box.title = "City or country where the ship was registered e.g. Liverpool";
	else if (field_id == "propulsion") 		box.title = "Type of propulsion the ship used e.g. steam, sail, motor. Select the Propulsion Category you wish to search on from the drop-down list.";
	else if (field_id == "rig") 			box.title = "Type of rig the ship used e.g. ketch, schooner, submarine. Select the Rig Category you wish to search on from the drop-down list.";
	else if (field_id == "vessel") 			box.title = "Type of use the ship was intended for e.g. navy, cargo. Select the Vessel Use Category you wish to search on from the drop-down list.";
}

function create_map(latitude, longitude)
{
   var map = new GMap2(document.getElementById("map"));
   map.addControl(new GSmallMapControl());
   map.addControl(new GMapTypeControl());
   map.setCenter(new GLatLng(latitude, longitude), 13);
   return map
}

function add_marker(map, latitude, longitude, html_balloon_source)
{
    var opts = new Object();
    opts.clickable = true;  
    var marker = new GMarker(new GLatLng(latitude, longitude), opts);		

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindow(html_balloon_source);
        });	
                 
    map.addOverlay(marker);

    return marker;
}

function fit_map_section(map, markers)
{
    var bounds = new GLatLngBounds();

    for (var i = 0; i < markers.length; i++) 
        {
        bounds.extend(markers[i].getPoint());
        }    

    var zoom_level = map.getBoundsZoomLevel(bounds);

    map.setZoom(zoom_level-1);;
    map.setCenter(bounds.getCenter());
}

function addMyBookmark(title,url) {
	// alert("title='"+title+"' url='"+url+"'");
	
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	}
	else
	{
		if (window.external)
		{ // IE Favorite
			window.external.AddFavorite(url, title);
		}
	}
	return false;
}
