String.prototype.camelize = function() {
	var parts = this.split('-');
	var len = parts.length;
	if (len == 1) {
		return parts[0];
	}
	var camelized = (this.charAt(0) == '-') ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0];
	for (var i = 1; i < len; i++) {
		camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
	}
	return camelized;
}

String.prototype.htmlDecode = function() {
	var s = this;
	s = s.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot/g, "\"");
	var re = /&#([0-9]{1,5});/;
	var found;
	while ((found = re.exec(s)) != null) {
		s = s.replace(found[0], String.fromCharCode(found[1]));
	}
	return s;
}

Array.prototype.includes = function(target, compareByRef) {
	if (typeof compareByRef != "boolean") {
		compareByRef = false;
	}
	for (var i = 0, len = this.length; i < len; i++) {
		if (i in this) {
			if (compareByRef) {
				if (this[i] === target) {
					return true;
				}
			} else {
				if (this[i] == target) {
					return true;
				}
			}
		}
	}
	return false;
}

Array.prototype.unique = function(compareByRef) {
	if (typeof compareByRef != "boolean") {
		compareByRef = false;
	}
	var arr = [];
	for (var i = 0, len = this.length; i < len; i++) {
		var entry = this[i];
		if (i == 0 || !arr.includes(entry, compareByRef)) {
			arr.push(entry);
		}
	}
	return arr;	
}

GHotSpot.prototype.generateMarkerInfo = function(gLocation) {
	var htm = gLocation.config.name;
	if (gLocation.config.street) {
		htm += '<br \/>' + gLocation.config.street;
	}
	if (gLocation.config.zipcode) {
		htm += '<br \/>' + gLocation.config.zipcode;
	}
	if (gLocation.config.city) {
		var sep = gLocation.config.zipcode ? ', ' : '<br \/>';
		htm += sep + gLocation.config.city;
	}
	return htm;
}

GHotSpot.getIcon = function() {
	return $.extend(new GIcon(), {
		image: "icons/arrow-white_transparent.gif",
		iconSize: new GSize(23, 34),
		iconAnchor: new GPoint(11, 34),
		infoWindowAnchor: new GPoint(0, 0)
	});
}

GHotSpot.getType0Icon = function() {
	return $.extend(new GIcon(), {
		image: "icons/ikon_bolig.gif",
		iconSize: new GSize(12, 18),
		iconAnchor: new GPoint(6, 18),
		infoWindowAnchor: new GPoint(0, 0)
	});
}

GHotSpot.getType1Icon = function() {
	return $.extend(new GIcon(), {
		image: "icons/ikon_erhverv.gif",
		iconSize: new GSize(12, 18),
		iconAnchor: new GPoint(6, 18),
		infoWindowAnchor: new GPoint(0, 0)
	});
}

GHotSpot.getType2Icon = function() {
	return $.extend(new GIcon(), {
		image: "icons/ikon_retail.gif",
		iconSize: new GSize(12, 18),
		iconAnchor: new GPoint(6, 18),
		infoWindowAnchor: new GPoint(0, 0)
	});
}

GHotSpot.resolveIcon = function(gLocation) {
	if (!gLocation || gLocation.constructor !== GLocation) {
		throw new Error("GHotSpot.resolveIcon: Must pass GLocation instance!");
	}
	if (gLocation.config.tid && typeof GHotSpot["getType" + gLocation.config.tid + "Icon"] == "function") {
		return GHotSpot["getType" + gLocation.config.tid + "Icon"]();
	}
	var t = gLocation.config.type || "none";
	for (var i = 0, l = GHotSpot.typeArr.length; i < l; i++) {
		if (t == GHotSpot.typeArr[i]) {
			var mName = "getType" + i + "Icon";
			if (typeof GHotSpot[mName] == "function") {
				return GHotSpot[mName]();
			}
		}
	}
	return GHotSpot.getIcon();
}

GHotSpot.stopEventPropagation = function(e) {
	e = e || window.event;
	if (e) {
		if (e.stopPropagation) {
			e.stopPropagation();
		} else {
			e.cancelBubble = true;
		}
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
	}
	return false;
}

GHotSpot.cookieName = "ghotspot";

GHotSpot.getCategorySettings = function(/*country, type, status*/) {
	if (GHotSpot.categorySettings) {
		var prefixes = ["country", "type", "status"];
		var key = "";
		for (var i = 0; i < arguments.length; i++) {
			var prefix = prefixes[i];
			var arg = GHotSpot.transformValue(prefix, arguments[i]);
			if (arg) {
				var sep = key ? "_" : "";
				key += sep + prefix.charAt(0) + "id" + arg;
			}
		}
		if (key in GHotSpot.categorySettings) {
			return GHotSpot.categorySettings[key];
		}
	}
	return null;
}

GHotSpot.state = {
	country: "",
	type: "",
	status: ""
}

GHotSpot.initState = function() {
	// read from cookie
	var cookie = new DCookie(GHotSpot.cookieName);
	var country = cookie.getParameter("country") || "";
	var type = cookie.getParameter("type") || "";
	var status = cookie.getParameter("status") || "";
	GHotSpot.setState(country, type, status);
}

GHotSpot.setState = function(country, type, status) {
	GHotSpot.state["country"] = country || "";
	GHotSpot.state["type"] = type || "";
	GHotSpot.state["status"] = status || "";
}

GHotSpot.saveState = function(country, type, status) {
	GHotSpot.setState(country, type, status);
	// save in cookie
	var cookie = new DCookie(GHotSpot.cookieName);
	var obj = GHotSpot.state;
	for (var p in obj) {
		var value = obj[p];
		value = GHotSpot.transformValue(p, value);
		cookie.setParameter(p, value);
	}
	cookie.save();
}

GHotSpot.filterByCountryListener = function(e, country) {
	GHotSpot.filterByCountry(country);
	return GHotSpot.stopEventPropagation(e);
}

GHotSpot.filterByCountryAndTypeListener = function(e, country, type) {
	GHotSpot.filterByCountryAndType(country, type);
	return GHotSpot.stopEventPropagation(e);
}

GHotSpot.filterByCountryTypeAndStatusListener = function(e, country, type, status) {
	GHotSpot.filterByCountryTypeAndStatus(country, type, status);
	return GHotSpot.stopEventPropagation(e);
}

GHotSpot.filterByCountry = function(country) {
	country = GHotSpot.countryObj[country] || country;
	var filter = function(entry, index) {
		if (!country) {
			return true;
		}
		return (entry.config.country == country);
	};
	GHotSpot.instances[0].plot(filter, GHotSpot.getCategorySettings(country));
	GHotSpot.saveState(country);
}

GHotSpot.filterByCountryAndType = function(country, type) {
	country = GHotSpot.countryObj[country] || country;
	type = GHotSpot.typeObj[type] || type;
	var filter = function(entry, index) {
		return (entry.config.country == country && (!type || entry.config.type == type));
	};
	GHotSpot.instances[0].plot(filter, GHotSpot.getCategorySettings(country, type));
	GHotSpot.saveState(country, type);
}

GHotSpot.filterByCountryTypeAndStatus = function(country, type, status) {
	country = country || GHotSpot.state["country"];
	type = type || GHotSpot.state["type"];
	country = GHotSpot.countryObj[country] || country;
	type = GHotSpot.typeObj[type] || type;
	status = GHotSpot.statusObj[status] || status;
	var filter = function(entry, index) {
		return (entry.config.country == country && entry.config.type == type && (!status || entry.config.status == status));
	};
	GHotSpot.instances[0].plot(filter, GHotSpot.getCategorySettings(country, type, status));
	GHotSpot.saveState(country, type, status);
}

GHotSpot.transformValue = function(name, value) {
	var obj = GHotSpot[name + "Obj"];
	for (var p in obj) {
		if (obj[p] == value) {
			return p;
		}
	}
	return value;
}

GHotSpot.cachedDropDownCombinations = {};

GHotSpot.filterDropDownValues = function(name) {
	if (name == "country") {
		return GHotSpot[name + "Arr"];
	}
	var arr = [];
	var selCountry = $("#selCountry")[0];
	var selCountryOption = selCountry.options[selCountry.selectedIndex];
	var key = "cid" + (selCountryOption.value || GHotSpot.transformValue("country", GHotSpot.state.country));
	if (name == "status") {
		var selType = $("#selType")[0];
		var selTypeOption = selType.options[selType.selectedIndex];
		key += "_tid" + (selTypeOption.value || GHotSpot.transformValue("type", GHotSpot.state.type));
		if (key in GHotSpot.cachedDropDownCombinations) {
			return GHotSpot.cachedDropDownCombinations[key];
		}
		for (var i = 0, len = GLocation.instances.length; i < len; i++) {
			var instance = GLocation.instances[i];
			if ((instance.config.cid == (selCountryOption.value || GHotSpot.state.country) || instance.config.country == selCountryOption.text || instance.config.country == GHotSpot.state.country) && (instance.config.tid == (selTypeOption.value || GHotSpot.state.type) || instance.config.type == selTypeOption.text || instance.config.type == GHotSpot.state.type)) {
				arr.push(instance.config.status);
			}
		}
	} else {
		if (key in GHotSpot.cachedDropDownCombinations) {
			return GHotSpot.cachedDropDownCombinations[key];
		}
		for (var i = 0, len = GLocation.instances.length; i < len; i++) {
			var instance = GLocation.instances[i];
			if (instance.config.cid == (selCountryOption.value || GHotSpot.state.country) || instance.config.country == selCountryOption.text || instance.config.country == GHotSpot.state.country) {
				arr.push(instance.config.type);
			}
		}
	}
	arr = arr.unique().sort();
	GHotSpot.cachedDropDownCombinations[key] = arr;
	return arr;
}

GHotSpot.populateDropDown = function(id, name) {
	var selObj = $("#" + id)[0];
	selObj.options.length = 1;
	selObj.disabled = false;
	var arr = GHotSpot.filterDropDownValues(name);
	var index = -1;
	for (var i = 0, len = arr.length; i < len; i++) {
		var txt = arr[i];
		var value = GHotSpot.transformValue(name, txt);
		if (value == GHotSpot.state[name] || txt == GHotSpot.state[name]) {
			index = i;
		}
		var option = document.createElement("option");
		option.setAttribute("value", value);
		var txtNode = document.createTextNode(txt.htmlDecode());
		option.appendChild(txtNode);
		selObj.appendChild(option);
	}
	if (index > -1) {
		setTimeout(function() {
			selObj.selectedIndex = index + 1;
			selObj = null; /* avoid memory leak */
		}, 0); // to execute in separate thread is necessary in IE6
	}
}

GHotSpot.countryOnchange = function(e) {
	var selObj = e ? e.target : $("#selCountry")[0];
	if (selObj) {
		var value = selObj.options[selObj.selectedIndex].value;
		if (value) {
			GHotSpot.filterByCountry(value);
			GHotSpot.populateDropDown("selType", "type");
		} else {
			selObj.form.status.disabled = true;
			GHotSpot.reset();
		}
		selObj.form.type.disabled = !value;
		$("#btnReset").each(function(i, el) {
			el.disabled = !value;
		});
	}
}

GHotSpot.typeOnchange = function(e) {
	var selObj = e ? e.target : $("#selType")[0];
	if (selObj) {
		var value = selObj.options[selObj.selectedIndex].value;
		if (value) {
			var state = GHotSpot.countryObj[GHotSpot.state.country] || GHotSpot.state.country;
			GHotSpot.filterByCountryAndType(state, value);
			GHotSpot.populateDropDown("selStatus", "status");
		} else {
			GHotSpot.countryOnchange();
			selObj.form.status.selectedIndex = 0;
		}
		selObj.form.status.disabled = !value;
	}	
}

GHotSpot.statusOnchange = function(e) {
	var selObj = e ? e.target : $("#selStatus")[0];
	if (selObj) {
		var value = selObj.options[selObj.selectedIndex].value;
		if (value) {
			GHotSpot.filterByCountryTypeAndStatus("", "", value);
		} else {
			GHotSpot.typeOnchange();
		}
		$("#btnShow").each(function(i, el) {
			el.disabled = !value;
		});
	}
}

GHotSpot.reset = function() {
	var cookie = new DCookie(GHotSpot.cookieName);
	cookie.remove(); // must be done before calling initState
	var gHotSpot = GHotSpot.instances[0];
	gHotSpot.map.clearOverlays();
	GHotSpot.initState();
	//gHotSpot.config.onInitMap = null; // otherwise it seems like resetting does nothing
	if (gHotSpot.config.initialAddress instanceof GLatLng) {
		gHotSpot.initMap(gHotSpot.config.initialAddress);
	} else {
		gHotSpot.geocoder.getLocations(gHotSpot.config.initialAddress, GEvent.callback(gHotSpot, gHotSpot.callbackInitMap));
	}
	$("#divForm select").each(function(i, el) {
		el.disabled = (i != 0);
		el.selectedIndex = 0;
	});
	$("#divForm button").each(function(i, el) {
		el.disabled = true;
	});
}

GHotSpot.showProjects = function() {
	var selObj = $("#selCountry")[0];
	var country = selObj.options[selObj.selectedIndex].value;
	selObj = $("#selType")[0];
	var type = selObj.options[selObj.selectedIndex].value;
	selObj = $("#selStatus")[0];
	var status = selObj.options[selObj.selectedIndex].value;
	GHotSpot.saveState(country, type, status);
	var key = "cid" + country + "_tid" + type + "_sid" + status;
	if (key in GHotSpot.projectListUrl && GHotSpot.projectListUrl[key].url) {
		location.href = GHotSpot.projectListUrl[key].url;
	}
}

GHotSpot.onInit = function() {
	$.each(["country", "type", "status"], function(index, entry) {
		if (GHotSpot.state[entry] || index == 0) {
			var id = ("sel-" + entry).camelize();
			GHotSpot.populateDropDown(id, entry);
			if (index == 0) {
				if (GHotSpot.state[entry]) {
					$("#btnReset")[0].disabled = false;
				}
			}
			else if (index == 2) {
				$("#btnShow")[0].disabled = false;
			}
		}
		return true;
	});
	if (GHotSpot.state["status"]) {
		GHotSpot.filterByCountryTypeAndStatus(GHotSpot.state["country"], GHotSpot.state["type"], GHotSpot.state["status"]);
	}
	else if (GHotSpot.state["type"]) {
		GHotSpot.filterByCountryAndType(GHotSpot.state["country"], GHotSpot.state["type"]);
		GHotSpot.populateDropDown("selStatus", "status");
	}
	else if (GHotSpot.state["country"]) {
		GHotSpot.filterByCountry(GHotSpot.state["country"]);
		GHotSpot.populateDropDown("selType", "type");
	} else {
		GHotSpot.plotAll();
	}
}

GHotSpot.plotAll = function() {
	for (var i = 0, len = GHotSpot.instances.length; i < len; i++) {
		var gHotSpot = GHotSpot.instances[i];
		gHotSpot.plot(null, { markCenter: false, useBoundsCenter: false, zoomLevel: gHotSpot.config.initialZoomLevel });
	}
}

GHotSpot.markerClicked = function(gLocation) {
	if (gLocation.config.url) {
		location.href = gLocation.config.url;
	}
}

GHotSpot.hideMarkerInfo = function(gLocation) {
	GHotSpot.toggleMarkerInfo.apply(this, [gLocation, false]);
}

GHotSpot.showMarkerInfo = function(gLocation) {
	GHotSpot.toggleMarkerInfo.apply(this, [gLocation, true]);
}

GHotSpot.toggleMarkerInfo = function(gLocation, show) {
	var gHotSpot = this;
	if (show) {
		$("#divForm").hide();
		$("#divMarkerInfo").html(gHotSpot.generateMarkerInfo(gLocation)).show();
	} else {
		$("#divMarkerInfo").hide().html("");
		$("#divForm").show();
	}
};

/*
GHotSpot.toggleMarkerInfo = function(gLocation, show) {
	var gHotSpot = this;
	if (show) {
		$("#divTabs").hide();
		$("#divMarkerInfo").html(gHotSpot.generateMarkerInfo(gLocation)).show();
	} else {
		$("#divMarkerInfo").hide().html("");
		$("#divTabs").show();
	}
};
*/
/*
GHotSpot.toggleMarkerInfo = function(gLocation, show) {
	var gHotSpot = this;
	if (gHotSpot.fading) {
		return;
	}
	gHotSpot.fading = true;
	if (show) {
		$("#divTabs").fadeOut("normal", function() {
			$("#divMarkerInfo").html(gHotSpot.generateMarkerInfo(gLocation)).fadeIn("normal", function() { gHotSpot.fading = false; });
		});
	} else {
		$("#divMarkerInfo").fadeOut("normal", function() {
			$(this).html("");
			$("#divTabs").fadeIn("normal",  function() { gHotSpot.fading = false; });
		});
	}
};*/

(function() {
	var countryArr = [];
	var typeArr = [];
	var statusArr = [];
	var countryObj = {};
	var typeObj = {};
	var statusObj = {};
	for (var i = 0, len = GLocation.instances.length; i < len; i++) {
		var instance = GLocation.instances[i];
		countryArr.push(instance.config.country);
		if (instance.config.cid) {
			countryObj[instance.config.cid] = instance.config.country;
		}
		typeArr.push(instance.config.type);
		if (instance.config.tid) {
			typeObj[instance.config.tid] = instance.config.type;
		}
		statusArr.push(instance.config.status);
		if (instance.config.sid) {
			statusObj[instance.config.sid] = instance.config.status;
		}
	}
	GHotSpot.countryArr = countryArr.unique().sort();
	GHotSpot.typeArr = typeArr.unique().sort();
	GHotSpot.statusArr = statusArr.unique().sort();
	GHotSpot.countryObj = countryObj;
	GHotSpot.typeObj = typeObj;
	GHotSpot.statusObj = statusObj;
	GHotSpot.initState();
})();

$(document).ready(function() { // in IE this fires AFTER window.onload!!!
	$("#btnReset").bind("click", function(e) {
		e.preventDefault();
		GHotSpot.reset();
	});
	$("#btnShow").bind("click", function(e) {
		e.preventDefault();
		GHotSpot.showProjects();
	});
	$("#selCountry").change(GHotSpot.countryOnchange);
	$("#selType").change(GHotSpot.typeOnchange);
	$("#selStatus").change(GHotSpot.statusOnchange);
});