// Helmisimpukka utility object

var Helmisimpukka = {
	printViewBaseUrl: "/stc/helmisimpukka/stationview.jsp?url=",
	printViewWindow: null,
	openPrintView: function(url){
		Helmisimpukka.printViewWindow = window.open(this.printViewBaseUrl + url);
	},
	
	// Simple cookie datastore
	datastore: {
		cookiePrefix: "helmisimpukka-",
		cookieDefaultLifetime: (1*24*60*60*1000),
		
		write: function(name,value,lifetime){
			if(!lifetime || typeof(lifetime) == 'undefined')
				lifetime = Helmisimpukka.datastore.cookieDefaultLifetime;

			var date = new Date();
			date.setTime(date.getTime()+(lifetime*60*60*1000));
			var expires = "; expires="+date.toGMTString();
			
			document.cookie = Helmisimpukka.datastore.cookiePrefix + name + "=" + value + expires + "; path=/";
		},
		
		read: function(name){
			var nameEQ = Helmisimpukka.datastore.cookiePrefix + name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},
		
		erase: function(name){
			Helmisimpukka.datastore.write(name, "", -1);
		}
	},
	
	
	// Helmisimpukka myStation functionality
	myStation: {
		cookieName: "mystation",
		
		setCurrent: function(){
			Helmisimpukka.myStation.set(window.location.href);
		},
		
		set: function(url){
			Helmisimpukka.datastore.write(Helmisimpukka.myStation.cookieName, escape(url));
		},
		
		get: function(){
			var value = Helmisimpukka.datastore.read(Helmisimpukka.myStation.cookieName);
			return (value != null) ? unescape(value) : value;
		},
		
		loadContent: function(url, containerId){
			$(containerId).load(url + " #page_station");
		},
		
		init: function(){
			$(document).keydown(Helmisimpukka.myStation.keyListener);
		},
		
		keyListener: function(e){
			if(!e){
				e = window.event;
			}
			var charCode = (e.which) ? e.which : e.keyCode;
			if(e.shiftKey && e.ctrlKey && charCode == 36){
				Helmisimpukka.datastore.erase(Helmisimpukka.myStation.cookieName);
				alert("Cookie erased.");
			}
		}
	},
	
	
	// Simple manager object to encapsulate weekly lunch menu linking functions
	lunchManager: {
		urls: {
			served: "/stc/helmisimpukka/lunch/servedWeekly.jsp",
			buffet: "/stc/helmisimpukka/lunch/buffetWeekly.jsp"
		},
		
		defaultUrl: "/stc/helmisimpukka/lunch/servedWeekly.jsp",
		
		setListURL: function(url){
			var hrefParts = $("#weeklyMenuLink").attr("href").split("?");
			if(hrefParts.length > 1)
				$("#weeklyMenuLink").attr("href", url + "?" + hrefParts[1]);
		}
	}
}

Helmisimpukka.myStation.init();





var MapView = {
	animationSpeed: "slow",
	stationContainer: "#station_container",
	viewContainers: {
		main: "mapView_main",
		subViews: [
			"mapView_1",
			"mapView_2",
			"mapView_3",
			"mapView_4"
		]
	},
	
	showMain: function(){
		MapView.hideAll();
		$("#" + MapView.viewContainers.main).show(MapView.animationSpeed);
	},
	
	hideAll: function(){
		$("#" + MapView.viewContainers.main).hide(MapView.animationSpeed);
		for(var i in MapView.viewContainers.subViews){
			$("#" + MapView.viewContainers.subViews[i]).hide(MapView.animationSpeed);
		}
	},
	
	showView: function(idx){
		MapView.hideAll();
		$("#" + MapView.viewContainers.subViews[idx]).show(MapView.animationSpeed);
	},
	
	updateList: function(){
		var url = Helmisimpukka.myStation.get();
		$("#listArea a").each(function(){
			if($(this).attr("href").indexOf(url) >= 0){
				$(this).addClass("active");
			}
			else{
				$(this).removeClass("active");
			}
		});
	},
	
	loadStation: function(url){
		Helmisimpukka.myStation.set(url);
		Helmisimpukka.myStation.loadContent(url, MapView.stationContainer);
		$("#stations_home_instructions").hide();
		$("#station_container").show();
		MapView.updateList();
	},
	
	
	init: function(){
		var searchStr = window.location.search;
		if(searchStr.indexOf("url=") > 0){
			var queryParts = searchStr.split("url=");
			var url = queryParts[1];
			if(url.indexOf("/_print/") <= 0){
				url += "_print/";
			}
			MapView.loadStation(url);
		}
	}
}

MapView.init();



// Object to encapsulate group form functions and data

var GroupForm = {
	
	// Data objects are grouped into the following groups.
	jsonDataGroups: ["main", "salty", "sweet"],
	
	// Each group is populated using its own JSON array read from the DOM element content. Elements are designated using these selectors.
	jsonSelectors: {
		main: "#content_body_right #json_main",
		salty: "#content_body_right #json_salty",
		sweet: "#content_body_right #json_sweet"
	},
	
	emailMapping: [],
	
	// Form field element selectors. Extend if necessary.
	emtSelectors: {
		company: "#txt_company",
		name: "#txt_name",
		phone: "#txt_phone",
		from: "#txt_email",
		visitDate: "#select_date",
		visitMonth: "#select_month",
		visitYear: "#select_year",
		visitHour: "#select_hour",
		visitMinutes: "#select_minutes",
		adults: "#txt_adults",
		children: "#txt_children",
		station: "#select_station",
		main: "#groupForm select.json_main",
		salty: "#groupForm select.json_salty",
		sweet: "#groupForm select.json_sweet",
		addInfo: "#txt_addinfo"
	},
	
	// Simple locale manager object to handle localized strings and other locale related stuff.
	localeManager: {
		availableLocales: ["fi_FI", "en_GB"],
		currentLocale: "fi_FI", // Current locale must be present in the availableLocales array
		localizedStrings: {
			fi_FI: {
				company: "Yritys",
				realname: "Nimi",
				phone: "Puhelin",
				from: "Sähköpostiosoite",
				dateOfVisit: "Vierailupäivä",
				time: "Kellonaika",
				groupSize: "Ryhmän koko",
				station: "Asema",
				meal: "Vähintään yksi annos",
				errorPrefix: "Täytäthän vielä seuraavat kentät:"
			},
			
			en_GB: {
				company: "Company",
				realname: "Name",
				phone: "Phone",
				from: "E-mail",
				dateOfVisit: "Date of visit",
				time: "Time",
				groupSize: "Size of group",
				station: "Station",
				meal: "A meal",
				errorPrefix: "Please, fill in the following fields:"
			}
		},
		
		// Checks that the new locale is present in the availableLocales array.
		setLocale: function(newLocale){
			for(var i in GroupForm.localeManager.availableLocales){
				if(GroupForm.localeManager.availableLocales[i] == newLocale){
					GroupForm.localeManager.currentLocale = newLocale;
					break;
				}
			}
		},
		
		// Parses a locale from the Navigo URL.
		parseLocaleFromUrl: function(url){
			for(var i in GroupForm.localeManager.availableLocales){
				if(url.indexOf("/" + GroupForm.localeManager.availableLocales[i] + "/") >= 0){
					GroupForm.localeManager.setLocale(GroupForm.localeManager.availableLocales[i]);
					break;
				}
			}
		}
	},
	
	// Data objects that hold the parsed JSON data.
	dataObjects: {
		main: null,
		salty: null,
		sweet: null
	},
	
	// Parse JSON to data objects.
	parseJSON: function(){
		for(var i in GroupForm.jsonDataGroups){
			var groupName = GroupForm.jsonDataGroups[i];
			if($(GroupForm.jsonSelectors[groupName]).size() > 0){
				var arr = eval("(" + $(GroupForm.jsonSelectors[groupName]).html() + ")");
				GroupForm.dataObjects[groupName] = new Array();
				for(var j in arr){
					if(arr[j].length >= 2){
						var obj = {value: arr[j][0], title: arr[j][1]};
						GroupForm.dataObjects[groupName].push(obj);
					}
				}
			}
		}
	},
	
	// Update form
	update: function(){
		for(var i in GroupForm.jsonDataGroups){
			if(typeof(GroupForm.dataObjects[GroupForm.jsonDataGroups[i]]) == 'object')
				GroupForm.populateSelect(GroupForm.emtSelectors[GroupForm.jsonDataGroups[i]], GroupForm.dataObjects[GroupForm.jsonDataGroups[i]]);
		}
	},
	
	/*
		Populate a dropdown element with an array of data objects.
		Objects are required to have value and title properties.
	*/
	populateSelect: function(selector, objects){
		$(selector).each(function(){
			$(this).empty();
			for(var i in objects){
				$(this).append("<option value=\"" + objects[i].value + "\">" + objects[i].title + "</option>");
			}
		});
	},
	
	
	// Preselect station appointed by myStation
	selectCurrentStation: function(){
		var email = GroupForm.getEmailByURL(Helmisimpukka.myStation.get());
		$("#groupForm select.stationlist option").each(function(){
			if($(this).val() == email)
				this.selected = true;
			else
				this.selected = false;
		});
	},
	
	// Resolve email from emailMapping array by URL
	getEmailByURL: function(url){
		var retval = null;
		
		if(url != null){
			if(url.indexOf("/_print/") < 0)
				url += "_print/";
			
			for(var i in GroupForm.emailMapping){
				if(GroupForm.emailMapping[i].url.indexOf(url) >= 0){
					retval = GroupForm.emailMapping[i].email;
					break;
				}
			}
		}
		
		return retval;
	},
	
	
	
	// Form field row counters
	fieldRowCounters: {
		main: 1,
		salty: 1,
		sweet: 1
	},
	
	// Display additional form field rows
	addFieldsToView: function(clickSrc, group){
		$(clickSrc).hide();
		GroupForm.fieldRowCounters[group]++;
		$("#" + group + "Row_" + GroupForm.fieldRowCounters[group]).show();
	},
	
	
	// Validate form
	validate: function(){
		var retval = true;
		var errors = 0;
		var errorFields = new Array();
		$("#groupForm input.required").each(function(){
			if($(this).val() == ""){
				errors++;
				errorFields.push("- " + GroupForm.localeManager.localizedStrings[GroupForm.localeManager.currentLocale][$(this).attr("name")]);
			}
		});
		
		if($("#groupForm select.stationlist option:selected").val() == ""){
			errors++;
			errorFields.push("- " + GroupForm.localeManager.localizedStrings[GroupForm.localeManager.currentLocale].station);
		}
		
		var selected = 0;
		
		for(var i in GroupForm.jsonDataGroups){
			var selector = GroupForm.emtSelectors[GroupForm.jsonDataGroups[i]];
			$(selector).each(function(){
				if(this.selectedIndex > 0)
					selected++;
			});
		}
		
		if(selected == 0){
			errors++;
			errorFields.push("- " + GroupForm.localeManager.localizedStrings[GroupForm.localeManager.currentLocale].meal);
		}
		
		
		if(errors > 0){
			retval = false;
			alert(GroupForm.localeManager.localizedStrings[GroupForm.localeManager.currentLocale].errorPrefix + "\n" + errorFields.join("\n"));
		}
		
		return retval;
	},
	
	/*
		Initialize form:
		- parse JSON
		- build dropdowns (GroupForm.update())
		- attach event handlers
	*/
	init: function(){
		$(document).ready(function(){
			GroupForm.parseJSON();
			GroupForm.update();
			$("#groupForm").submit(function(){
				return GroupForm.validate();
			});
			GroupForm.selectCurrentStation();
		});
	}
}
