toc_selected_id = "general_info";

Ajax.number_of_retries = 1;

var location_was_modified = new Object();
var edit_loading_location = new Object();

busy_location_edit = 0;
busy_location_save = 0;
busy_location_delete = 0;
busy_location_add = 0;
var progress_icon_status = new Object();

function tocSelectId(id) {
	Core.setClassName(toc_selected_id, "fshidden");
	Core.setClassName("toc_" + toc_selected_id, "tocnormal");
	Core.setClassName(id, "fsnormal");
	Core.setClassName("toc_" + id, "tocselected");
	toc_selected_id = id;
}


function initMyCities() {
	e = document.getElementsByTagName("td");
	for (i=0; i<e.length; i++) {
		if (e[i].id.match(/^location_(.+)$/)) {
			id = e[i].id.substr(e[i].id.indexOf("_")+1, e[i].id.length);

			if (Core.getText("country_" + id).length > 0) {
				setCmd(id, "edit", true);
				setCmd(id, "delete", true);
			} else {
				setCmd(id, "add", true);
			}
		}
	}
}

function checkLocationBusyStatus(id, status) {
	if (busy_location_add != 0) {
		if (status == "add") {
			return false;
		} 
	}

	if (busy_location_edit != 0) {
		if (status == "edit" || status == "add")  {
			if (busy_location_save != 0 && busy_location_save != id) {
				alert("Saving location, please wait...");
				return false;
			}

			if (busy_location_edit != 0) {
				if (!location_was_modified || confirm("Previous location was modified. Would you like to skip changes?")) {
					cancelEditLocation(busy_location_edit, true);
					return true;
				} else {
					return false;
				}
			}
		}
	}

	if (busy_location_save != 0) {

	}

	if (busy_location_delete != 0) {

	}

	return true;
}

function editLocation(id) {
	if (!checkLocationBusyStatus(id, "edit")) {
		return;
	}

	edit_loading_location = true;
	busy_location_edit = id;

	showHideLocationPreview(id);
	showCountries(id);

	setCmd(id, "cancel", true);
	setCmd(id, "add", false);
	setCmd(id, "edit", false);
	setCmd(id, "delete", false);

	updateCountries(id);
	getRegions(id);
	getCities(id);
}

function saveLocation(id) {
	country = Core.getElementU("select_country_" + id);
	region = Core.getElementU("select_region_" + id);
	city = Core.getElementU("select_city_" + id);

	if (country == undefined || country.selectedIndex == 0) {
		alert("Please select a country first.");
		return;
	}

	showHideLocationPreview(id);

	value_city = (city != null) ? city.options[city.selectedIndex].value : 0;
	value_region = (region != null) ? region.options[region.selectedIndex].value : 0;
	setLocationValues(id, country.options[country.selectedIndex].value, value_region, value_city);

	preview_city = (city != null && city.selectedIndex > 0) ? city.options[city.selectedIndex].text : "";
	preview_region = (region != null && region.selectedIndex > 0) ? (region.options[region.selectedIndex].text + ((preview_city.length > 0) ? "," : "")) : "";
	preview_country = (country.selectedIndex > 0) ? (country.options[country.selectedIndex].text + ((preview_region.length > 0) ? "," : "")) : "";
	setLocationPreview(id, preview_country, preview_region, preview_city);

	removeCountries(id);
	removeRegions(id);
	removeCities(id);

	setCmd(id, "save", false);
	setCmd(id, "cancel", false);

	data = new Object;
	data["id"] = id;
	data["country"] = country.options[country.selectedIndex].value;
	data["region"] = value_region;
	data["city"] = value_city;

	busy_location_save = id;
	showProgressIcon(id);
	Ajax.sendRequest("save_" + id, "saveLocation", "saveLocationCallback", data);
}

function saveLocationCallback(response) {
	id = getIdByToken(response.token);

	busy_location_edit = 0;
	busy_location_add = 0;
	busy_location_save = 0;
	location_was_modified = false;

	hideProgressIcon(id);

	if (response.token.match(/^other/)) {
		// update id and code for other location
		id = response.params.id;
		id_old = response.params.id_old;

		e = Core.getElementU("location_" + id_old);
		e.firstChild.nextSibling.innerHTML = response.params.code;
		e.firstChild.nextSibling.id = "location_" + id;
	}

	setCmd(id, "edit", true);
	setCmd(id, "delete", true);
}

function deleteLocation(id) {
	if (!checkLocationBusyStatus(id, "delete")) {
		return;
	}

	if (!confirm("Delete this location?")) {
		return;
	}

	busy_location_delete = id;

	setCmd(id, "edit", false);
	setCmd(id, "delete", false);

	showProgressIcon(id);

	Ajax.sendRequest("delete_" + id, "deleteLocation", deleteLocationCallback, id);
}

function deleteLocationCallback(response) {
	id = getIdByToken(response.token);

	setLocationValues(id, "", "", "");
	setLocationPreview(id, "", "", "");

	setCmd(id, "add", true);

	busy_location_delete = 0;
	hideProgressIcon(id);

	if (id.match(/^\d+$/)) {
		// remove other location container
		loc = Core.getElementU("location_" + id);
		loc.parentNode.parentNode.removeChild(loc.parentNode);
		Core.flushElementCache();
	}
}

function cancelEditLocation(id, force) {
	if (location_was_modified && !force && !confirm("Skip changes?")) {
		return;
	}

	busy_location_edit = 0;
	busy_location_add = 0;
	location_was_modified = false;

	if (id.match(/^other(\d+)$/)) {
		container = Core.getElementU("location_" + id);
		container.parentNode.removeChild(container);
		Core.flushElementCache();
		return;
	}

	showHideLocationPreview(id);

	removeCountries(id);
	removeRegions(id);
	removeCities(id);

	setCmd(id, "save", false);
	setCmd(id, "cancel", false);

	if (Core.getElementU("country_" + id).value.length > 0) {
		setCmd(id, "edit", true);
		setCmd(id, "delete", true);
	} else {
		setCmd(id, "add", true);
	}
}

function updateCountriesAdvAjax(id, autodetect) {
	country = Core.getElementU("select_country_" + id);
	country_value = Core.getElementU("country_" + id).value;

	select_id = 0;
	if (country_value) {
		select_id = getSelectIndexByValueAdvAjax(country.options, country_value);
	}
	country.selectedIndex = select_id;

	country_onchange = new Function("getRegionsAdvAjax('"+id+"', '"+autodetect+"')");
	country.onchange = country_onchange;
}

function getRegionsAdvAjax(id, autodetect) {
	removeCitiesAdvAjax(id);
	removeRegionsAdvAjax(id);

	country_value = Core.getElementU("country_" + id).value;
	country = Core.getElementU("select_country_" + id);

	if (!edit_loading_location[id]) {
		location_was_modified[id]= (wasLocationModifiedAdvAjax(id) && country.selectedIndex > 0);
	}

	//setCmd(id, "save", location_was_modified);

	if (country.selectedIndex > 0) {
		country_value = country.options[country.selectedIndex].value;
	} else {
		edit_loading_location[id] = false;
		return;
	}
	
	if (!autodetect) {
      autodetect = '';
   }
	
      advAJAX.post({
         "cmd"      : "getRegions",
         "country"  : '' + country_value,
         "token"    : '' + id,
         "autodetect" : '' + autodetect,
         "retry"    : 4,
         "timeout"  : 30000,
   
         onLoading: function(obj) {
            Core.getElementU("select_country_" + id).disabled = true;
            showProgressIconAdvAjax(id);
         },
         
         onSuccess : function(obj) {
            hideProgressIconAdvAjax(id);
         	Core.setText("container_region_" + id, obj.responseText);
         
         	region_value = Core.getElementU("region_" + id).value;
         	region = Core.getElementU("select_region_" + id);
         
         	if (region_value) {
         		region.selectedIndex = getSelectIndexByValueAdvAjax(region.options, region_value);
         	}
         	
         	region_onchange = new Function("getCitiesAdvAjax('" + id + "', '"+autodetect+"')");
         	region.onchange = region_onchange;
         	Core.getElementU("select_country_" + id).disabled = false;
         },
   
         onTimeout: function() {
            Core.getElementU("select_country_" + id).disabled = false;
         },
         
         onError: function(obj) {
            Core.getElementU("select_country_" + id).disabled = false;
         }
      });
	
}

function getCitiesAdvAjax(id, autodetect) {
	removeCitiesAdvAjax(id);

	if (!edit_loading_location[id]) {
		location_was_modified[id] = wasLocationModifiedAdvAjax(id);
	}

	//setCmd(id, "save", location_was_modified);
	
	country = Core.getElementU("select_country_" + id);
	country_id = country.options[country.selectedIndex].value;
	region = Core.getElementU("select_region_" + id);
	region_id = Core.getElementU("region_" + id).value;

	if ((country.selectedIndex == 0) || (region && region.selectedIndex == 0) ||
		(region == null && (region_id.length == 0 || region_id == 0))) {
		edit_loading_location[id] = false;
		return;
	}

	if (region && region.selectedIndex > 0) {
		region_id = region.options[region.selectedIndex].value;
	}
	
	
	if (region_id != "none" && region_id.length < 5) {

		
      advAJAX.post({
         "cmd"      : "getCities",
         "country"  : '' + country_id,
         "region"   : '' + region_id,
         "token"    : '' + id,
         "autodetect" : '' + autodetect,
         "retry"    : 4,
         "timeout"  : 30000,
   
         onLoading: function(obj) {
            showProgressIconAdvAjax(id);
         },
         
         onSuccess : function(obj) {
         	hideProgressIconAdvAjax(id);
         	Core.setText("container_city_" + id, obj.responseText);
         
         	city_value = Core.getElementU("city_" + id).value;
         	if (city_value) {
         		city = Core.getElementU("select_city_" + id);
         		city.selectedIndex = getSelectIndexByValueAdvAjax(city.options, city_value);
         	}
         
         	edit_loading_location[id] = false;
         
         	city_onchange = new Function("onCityChangeAdvAjax('"+id+"')");
         	Core.getElementU("select_city_" + id).onchange = city_onchange;
         },
   
         onTimeout: function() {

         },
         
         onError: function(obj) {

         }
      });		
		
	}
}

function updateCities(response) {
	id = getIdByToken(response.token);

	hideProgressIcon(id);
	Core.setText("container_city_" + id, response.data);

	city_value = Core.getElementU("city_" + id).value;
	if (city_value) {
		city = Core.getElementU("select_city_" + id);
		city.selectedIndex = getSelectIndexByValue(city.options, city_value);
	}

	edit_loading_location = false;

	city_onchange = new Function("onCityChangeAdvAjax('"+id+"')");
	Core.getElementU("select_city_" + id).onchange = city_onchange;
}

function onCityChangeAdvAjax(id) {
	location_was_modified[id] = wasLocationModifiedAdvAjax(id);
	//setCmd(id, "save", location_was_modified);
}

function wasLocationModifiedAdvAjax(id) {
	city_value = Core.getElementU("city_" + id).value;
	city = Core.getElementU("select_city_" + id);
	city_was_modified = ((city != null) && ((city_value.length == 0 && city.selectedIndex > 0) ||
		(city_value.length > 0 && city.options[city.selectedIndex].value != city_value)));

	region_value = Core.getElementU("region_" + id).value;
	region = Core.getElementU("select_region_" + id);
	region_was_modified = ((region != null) && ((region_value.length == 0 && region.selectedIndex > 0) ||
		(region_value.length > 0 && region.options[region.selectedIndex].value != region_value)));

	country_value = Core.getElementU("country_" + id).value;
	country = Core.getElementU("select_country_" + id);
	country_was_modified = ((country_value.length == 0 && country.selectedIndex > 0) ||
		(country_value.length > 0 && country.options[country.selectedIndex].value != country_value));

	return (city_was_modified || region_was_modified || country_was_modified);
}

function showHideLocationPreview(id) {
	Core.showHideElement("preview_country_" + id);
	Core.showHideElement("preview_region_" + id);
	Core.showHideElement("preview_city_" + id);
}

function setLocationPreview(id, country, region, city) {
	Core.setText("preview_country_" + id, country);
	Core.setText("preview_region_" + id, region);
	Core.setText("preview_city_" + id, city);
}

function setLocationValues(id, country, region, city) {
	Core.setText("country_" + id, country);
	Core.setText("region_" + id, region);
	Core.setText("city_" + id, city);
}

function showCountries(id) {
	countries = Core.getElementU("select_country");
	countries_clone = countries.cloneNode(true);
	countries_clone.id = "select_country_" + id;
	Core.getElementU("container_country_" + id).appendChild(countries_clone);
	Core.showElement("select_country_" + id);
}

function removeCountries(id) {
	Core.getElementU("container_country_" + id).removeChild(Core.getElementU("select_country_" + id));
	Core.flushElementCache();
}

function removeRegionsAdvAjax(id) {
	region = Core.getElementU("select_region_" + id);
	if (region != undefined) {
		Core.getElementU("container_region_" + id).removeChild(region);
		Core.flushElementCache();
	}
}

function removeCitiesAdvAjax(id) {
	city = Core.getElementU("select_city_" + id);
	if (city != undefined) {
		Core.getElementU("container_city_" + id).removeChild(city);
		Core.flushElementCache();
	}
}

function setCmd(id, cmd, on) {
	cmd_id = "cmd_" + cmd + "_" + id;
	if (on) {
		Core.showElement(cmd_id);
	} else {
		Core.hideElement(cmd_id);
	}
}

function getIdByToken(token) {
	return token.substr(token.indexOf("_") + 1, token.length);
}

function getSelectIndexByValueAdvAjax(options, value) {
	for (i=0; i<options.length; i++) {
		if (options[i].value == value) {
			return i;
		}
	}
	return 0;
}

function showProgressIconAdvAjax(id) {
	if (!Core.isAnyNumber(progress_icon_status[id])) {
      progress_icon_status[id] = 0;
   }
   progress_icon_status[id]++;
	Core.showElement("progress_" + id);
}

function hideProgressIconAdvAjax(id) {
	if (--progress_icon_status[id] == 0) {
		Core.hideElement("progress_" + id);
	}
}

function getNewLocationId() {
	return Math.floor(Math.random() * 100000);
}

function addOtherLocation() {
	id = "other" + getNewLocationId();

	if (!checkLocationBusyStatus(id, "add")) {
		return;
	}

	busy_location_add = id;

	data = new Object;
	data["id"] = id;
	setCmd("other", "add", false);
	showProgressIcon("add_other");
	Ajax.sendRequest("other_add", "addOtherLocation", addOtherLocationCallback, data);
}

function addOtherLocationCallback(response) {
	setCmd("other", "add", true);
	hideProgressIcon("add_other");
	id = response.params.id;
	code = response.params.code;

	o = Core.getElementU("container_add_other");
	o2 = o.cloneNode(true);
	o.id = "location_" + id;
	o.parentNode.appendChild(o2);
	o.firstChild.nextSibling.innerHTML = code;

	editLocation(id);
}
