var stanBrowserJSONHandler = {
	url: '/index.php?eID=stan_json',
	cookieOptions: {path: '/'},
	
	/**
	 * This method takes a method name and some parameter and sends them to the coresponding JSON
	 * call on server side. The result will be dispatched to a method in this class to process
	 * the result set.
	 */
	dispatchMethod: function(methodName, parameters) {
		var params = new Object;
		params['method'] = methodName;
		params['params'] = parameters;
		
			// do the request
		var jsonRequest = new Request.JSON({
			url:this.url,
			onSuccess: function(responseJSON, responseText) {
					// dispatch result
				switch (responseJSON.method) {
					case 'updateSB':
						if (responseJSON.target != '') {
							stanBrowserJSONHandler.updateSelectBoxes(responseJSON.data, responseJSON.target);						
						}
						break;
				}
			}
		}).get(params);
	},
	
	/**
	 * Takes a data structure and updates the requested dropdown.
	 */
	updateSelectBoxes: function(data, target) {
		var selectBox = $(target);
			// clear the selectbox but don't clear the cookie
		stanBrowserJSONHandler.clearSelectBox(target, false);
		
			// if we have some data...
		if (data && data.length > 0) {
				// write it to cookie for caching (reload)
			Cookie.write(target+'_data', JSON.encode(data), stanBrowserJSONHandler.cookieOptions);
			
				// cycle through the data and and some options to the select box
			data.each(function(item, index) {
				var option = stanBrowserJSONHandler.getSelectOption(item.uid,((item.subtitle == '') ? item.title : item.subtitle));
				option.injectInside(selectBox);
			});
			
				// enable the selectbox 
			selectBox.removeProperty('disabled');
		}	
	},
	
	/**
	 * Clears all items in a given select box. It leaves the first option untouched because this
	 * is a static "make selection" option.
	 */
	clearSelectBox: function(target, removeCookie) {
		var selectBox = $(target);
		var length = selectBox.options.length;
		
			// remove the last child until only on option is left
		if (length > 1) {
			for (i = length; i > 1; i--) {
				selectBox.removeChild(selectBox.lastChild);
			}
		}
		
			// remove the selection from cache if requested
		if (removeCookie) Cookie.write(target, '', stanBrowserJSONHandler.cookieOptions);
		
			// clear cache in cookie
		Cookie.write(target+'_data', '', stanBrowserJSONHandler.cookieOptions);
		
			// disable the select box
		selectBox.setAttribute('disabled', 'disabled');
	},
	
	/**
	 * Set the selected option for a given select box from cookie.
	 */
	markSelectedItem: function(target) {
		var selectBox = $(target);
		var length = selectBox.options.length;
		
			// cycle throuhg all options of a select box...
		if (length > 1) {
			for (i = length; i > 1; i--) {
				var option = selectBox.options[i-1];
				
					// set it to "unselected" by default
				option.selected = false;
				
					// now check if the value in cookie for this select boy equals the current id and select it if it does
				if (option.value == Cookie.read(target, stanBrowserJSONHandler.cookieOptions)) {
					option.selected = true;
				}
			}
		}
	},
	
	/**
	 * Create a DOM object for an option element
	 */
	getSelectOption: function(value, title) {
		var option = new Element('option', {'value':value,'title':title});
		option.appendText(title);
		return option;
	}
}

	// initial loading
window.addEvent('domready', function() {

	if ($('stan_browser')) {
			// first level dropdown
		$('stan_browser_fltheme').addEvent('change', function(e) {
			var parentId = $('stan_browser_fltheme').value;
				// write selection to cookie
			if ($('check_remember').checked) Cookie.write('stan_browser_fltheme', parentId, stanBrowserJSONHandler.cookieOptions);
			
				// clear other dropdowns
			stanBrowserJSONHandler.clearSelectBox('stan_browser_sltheme', true);
			stanBrowserJSONHandler.clearSelectBox('stan_browser_p', true);
			
				// load second level data...
			stanBrowserJSONHandler.dispatchMethod('loadThemes', {'parentId':parentId});
		});
	
			// second level drop down
		$('stan_browser_sltheme').addEvent('change', function(e) {
			var parentId = $('stan_browser_sltheme').value;
				// write selection to cookie
			if ($('check_remember').checked) Cookie.write('stan_browser_sltheme', parentId, stanBrowserJSONHandler.cookieOptions);
			
				// clear other dropdowns
			stanBrowserJSONHandler.clearSelectBox('stan_browser_p', true);
			
				// load products...
			stanBrowserJSONHandler.dispatchMethod('loadProducts', {'parentId':parentId});
		});
		
			// products dropdown
		$('stan_browser_p').addEvent('change', function(e) {
				// enable submit button
			$('stan_browser_submit').removeProperty('disabled');
			
				// store selection in cookie
			if ($('check_remember').checked) Cookie.write('stan_browser_p', $('stan_browser_p').value, stanBrowserJSONHandler.cookieOptions);
			
			if ($('stan_browser_p').options.length > 1) {
				$('stan_browser_submit').removeProperty('disabled');
			} else {
				$('stan_browser_submit').setAttribute('disabled', 'disabled');
			}
		});
	
			// get checkbox
		var check_remember = $('check_remember');
		
			// add some handling for change of remember checkbox
		check_remember.addEvent('change', function(e) {
			
				// clear and reset cookie if checkbox is checked
			Cookie.write('remember', check_remember.checked, stanBrowserJSONHandler.cookieOptions);
			if (check_remember.checked) {
					// write the current state of selection to the cookie
				Cookie.write('stan_browser_fltheme', $('stan_browser_fltheme').value, stanBrowserJSONHandler.cookieOptions);
				Cookie.write('stan_browser_sltheme', $('stan_browser_sltheme').value, stanBrowserJSONHandler.cookieOptions);
				Cookie.write('stan_browser_p', $('stan_browser_p').value, stanBrowserJSONHandler.cookieOptions);
			} else {
					// checkbox is NOT selected: clear all states in cookie
				Cookie.write('stan_browser_fltheme', '', stanBrowserJSONHandler.cookieOptions);
				Cookie.write('stan_browser_sltheme', '', stanBrowserJSONHandler.cookieOptions);
				Cookie.write('stan_browser_p', '', stanBrowserJSONHandler.cookieOptions);
			}
		});
		
			// restore data and selection from JS. This is needed to make caching possible
		if (check_remember.checked) {
				// first level dropdown has only needs selection of option
			stanBrowserJSONHandler.markSelectedItem('stan_browser_fltheme');
			
				// second level needs a restore of the last data and a selection of the current option
			var data = JSON.decode(Cookie.read('stan_browser_sltheme_data', stanBrowserJSONHandler.cookieOptions));
			stanBrowserJSONHandler.updateSelectBoxes(data, 'stan_browser_sltheme');
			stanBrowserJSONHandler.markSelectedItem('stan_browser_sltheme');
			
				// products dropdown: data and selection restore 
			data = JSON.decode(Cookie.read('stan_browser_p_data', stanBrowserJSONHandler.cookieOptions));
			stanBrowserJSONHandler.updateSelectBoxes(data, 'stan_browser_p');
			stanBrowserJSONHandler.markSelectedItem('stan_browser_p');
			
			if (data != null) {
				$('stan_browser_submit').removeProperty('disabled');
			}
		}
		
			// display the whole browser
			// This makes sure, the browser is only visible if JavaScript is enabled
		$('stan_browser').setStyle('display');
	}
});