// JavaScript Document
var applications = {
	siteCode: 'MD',
	SID: '',
	requests: 0,
	orderCol: 'name',
	orderDir: 'asc',
	
	init: function (newSiteCode, newSID, loadParams) {
		var loadParams = loadParams || '';
		this.siteCode = newSiteCode;
		this.SID = newSID;
		$('noJava').remove();
		$$('a').invoke('observe', 'click', function (s) {
			window.location.hash = $('applicationControls').serialize() + '&orderCol=' + applications.orderCol + '&orderDir=' + applications.orderDir;
		});
		var queryString = this.convertQueryString();
		this.loadControls(loadParams, queryString);
	},
	
	loadControls: function (params, qs) {
		$('controls').getElementsBySelector('select, input').invoke('enable');
		$('controls').getElementsBySelector('select').invoke('observe', 'change', function (t) {
			applications.updateControls(Event.findElement(t, 'select').id);
		});
		$('searchString').observe('keyup', function(t) {applications.updateString();});
		$('allButton').observe('click', function (t) {applications.showAll()});
		$('resetButton').observe('click', function (t) {applications.resetForm();});
		$('applicationControls').observe('submit', function (e) {Event.stop(e);});
		$$('a.infoLink').invoke('observe', 'click', function (t) {
			popupWindow(Event.findElement(t, 'a').href, '', '390', '252', '', '', '', '');
			Event.stop(t);
		});
		
		// URLにクエリストリング（qs）があれば、すぐにgetResultsを実行する
		if (qs) {
			applications.getResults(qs);
		}

		if (params != '') {
			var test = params.toQueryParams();
			if (test.type && test.type != -1) {
				var type = $('type');
				for (i = 0; i < type.options.length; i++) {
					if (type.options[i].value == test.type) {
						type.selectedIndex = i;
					}
				}
			}
			if (test.industry && test.industry != -1) {
				var industry = $('industry');
				for (i = 0; i < industry.options.length; i++) {
					if (industry.options[i].value == test.industry) {
						industry.selectedIndex = i;
					}
				}
			}
			if (test.taskList && test.taskList != -1) {
				var task = $('taskList');
				for (i = 0; i < task.options.length; i++) {
					if (task.options[i].value == test.taskList) {
						task.selectedIndex = i;
					}
				}
			}
			if (test.searchString && test.searchString != '') {
				$('searchString').value = test.searchString;
				
			}
			if (test.orderCol) {
				applications.orderCol = test.orderCol;
			}
			
			if (test.orderDir) {
				applications.orderDir = test.orderDir;
			}
			applications.getResults();
		}
		$('results').getElementsBySelector('th.sortable').each(function (t) {
			t.addClassName('sortHead');
			t.observe('click', function (s) {
				var order = Event.findElement(s, 'th').id;
				order = order.substring(0, order.length - 3);
				$(applications.orderCol + 'Col').removeClassName('sort' + applications.orderDir);
				if (applications.orderCol == order) {
					if (applications.orderDir == 'asc') {
						applications.orderDir = 'desc';
					}
					else {
						applications.orderDir = 'asc';
					}
				}
				else {
					applications.orderCol = order;
				}
				$(applications.orderCol + 'Col').addClassName('sort' + applications.orderDir);
				applications.getResults();
			});
		});
	},
	
	updateControls: function (element) {
		$('searchString').value = '';
		if (element == 'taskList') {
			applications.getResults();
		}
		else {
			var params = $('applicationControls').serialize() + '&site=' + this.siteCode + '&control=' + element;
			new Ajax.Request('/applicationfinder/controls.php', {
				method: 'get',
				parameters: params,
				onSuccess: function (t) {
					t = t.responseText.evalJSON(true);
					if (t.industry) {
						$('industryWrap').update(t.industry);
						$('industry').observe('change', function (t) {
							applications.updateControls('industry');
						});
					}
					if (t.taskList) {
						$('taskWrap').update(t.taskList);
						$('taskList').observe('change', function (t) {
							applications.updateControls('taskList');
						});
					}
					applications.getResults();
				}
			});
		}
	},
	
	updateString: function () {
		$('controls').getElementsBySelector('select').each(function (t) {
			t.selectedIndex = 0;
		});
		applications.getResults();
	},
	
	resetForm: function () {
		$('controls').getElementsBySelector('select').each(function (t) {
			t.selectedIndex = 0;
		});
		applications.resetControls();
		$('searchString').value = '';
		$('resultsTable').update();
		$('results').addClassName('initial');
		$('spacing').show();
		$('message1').update('Derzeit stehen ');
		$('message2').update('Anwendungen zur Auswahl.');
		$('totalNum').addClassName('initial');
		$('redTotal').update($('totalNum').innerHTML);
	},
	
	showAll: function () {
		applications.resetControls();
		$('controls').getElementsBySelector('select').each(function (t) {
			t.selectedIndex = 0;
		});
		$('searchString').value = '';
		applications.getResults();
	},
	
	resetControls: function () {
		var params = 'type=-1&industry=-1&taskList=-1&searchString=&site=' + this.siteCode + '&control=type';
		new Ajax.Request('/applicationfinder/controls.php', {
				method: 'get',
				parameters: params,
				onSuccess: function (t) {
					t = t.responseText.evalJSON(true);
					if (t.industry) {
						$('industryWrap').update(t.industry);
						$('industry').observe('change', function (t) {
							applications.updateControls('industry');
						});
					}
					if (t.taskList) {
						$('taskWrap').update(t.taskList);
						$('taskList').observe('change', function (t) {
							applications.updateControls('taskList');
						});
					}
				}
			});
	},
	
	getResults: function (qs) {
		var qs = qs || $('applicationControls').serialize();
		var params = qs + '&site=' + this.siteCode + '&orderCol=' + this.orderCol + '&orderDir=' + this.orderDir + '&SID=' + this.SID;
		applications.requests = applications.requests + 1;
		new Ajax.Request ('/applicationfinder/results.php', {
			method: 'get',
			parameters: params,
			onSuccess: function (t) {
				applications.requests = applications.requests - 1;
				if (applications.requests == 0 && t.responseText != '') {
					$('spacing').hide();
					$('resultsTable').update(t.responseText);
					if ($('results').hasClassName('initial')) {
						$('results').removeClassName('initial');
					}
					$('resultsTable').getElementsBySelector('a.imagePop').invoke('observe', 'click', function (s) {
						popupWindow(Event.findElement(s, 'a').href, '', '390', '252', '', '', '', '');
						Event.stop(s);
					});
					applications.updateCrumbs();
				}
				else if (applications.requests == 0 && $F('searchString').length > 0) {
					$('searchWarning').update("Ihre Suchanfrage hat leider keinerlei Ergebnisse geliefert. Bitte versuchen Sie es erneut.");
				}
			}
		});
	},
	
	updateCrumbs: function () {
		if ($F('searchString').length > 0) {
			$('crumbs').update('Suchanfrage: ' + $F('searchString'));
		}
		else if ($F('type') != -1 || $F('industry') != -1 || $F('taskList') != -1) {
			var f = false;
			var newCrumbs = '';
			if ($F('type') != -1) {
				newCrumbs = newCrumbs + $('type').options[$('type').selectedIndex].text;
				f = true;
			}
			if ($F('industry') != -1) {
				if (f) {
					newCrumbs = newCrumbs + ' > ';
				}
				newCrumbs = newCrumbs + $('industry').options[$('industry').selectedIndex].text;
				f = true;
			}
			if ($F('taskList') != -1) {
				if (f) {
					newCrumbs = newCrumbs + ' > ';
				}
				newCrumbs = newCrumbs + $('taskList').options[$('taskList').selectedIndex].text;
				f = true;
			}
			$('crumbs').update(newCrumbs);
		}
		else {
			$('crumbs').update('Alle');
		}
		var num = $('resultsTable').getElementsBySelector('tr.mainRow').size();
		$('numFound').update(num);
		$('redTotal').update(num);
		$('message1').update();
		$('message2').update('Anwendungen von insgesamt');
		$('totalNum').removeClassName('initial');
		
		if (num == 1) {
			$('plural').update();
			$('plural2').update();
		}
		else {
			$('plural').update('s');
			$('plural2').update('s');
		}
		$('searchWarning').update();
	},

	convertQueryString: function() {
		var qs = location.search;
		if (qs.length > 0) {
			var params = qs.slice(1).split('&');
			var result = {};
			params.each(function(param) {
				var q = param.split('=');
				var key = q[0];
				result[key] = q[1];
			});
			return $H(result).toQueryString();
		} else {
			return false;
		}
	}
}

/*
* トップページのセレクトボックス用。親セレクトボックスによって子孫セレクトボックスの内容を書き換える（applicationsオブジェクトの移植版）
* ※イベントの割り当てをjQueryに書き換え済み
*/
var ApplicationsTop = function() {
	this.siteCode = 'MD';
	this.loadControls();
}
ApplicationsTop.prototype = {
	loadControls: function () {
		var self = this;
		jQuery('#controls').find('select').live('change', function() {
			var id = jQuery(this).attr('id');
			self.updateControls(id);
		});
	},
	updateControls: function (element) {
		var self = this;
		var params = $('applicationControls').serialize() + '&site=' + this.siteCode + '&control=' + element;
		new Ajax.Request('/applicationfinder/controls.php', {
			method: 'get',
			parameters: params,
			asynchronous: false,
			onSuccess: function (t) {
				t = t.responseText.evalJSON(true);
				if (t.industry) {
					$('industryWrap').update(t.industry);
					jQuery('#industry').live('change', function () {
						self.updateControls('industry');
					});
				}
				if (t.taskList) {
					$('taskWrap').update(t.taskList);
					jQuery('#taskList').live('change', function () {
						self.updateControls('taskList');
					});
				}
			}
		});
	}
}

/*
*  ApplicationsTopのプルダウンを隠して、画像で作成したプルダウンを表示する。
*  本来のselectボックスは、display: noneで非表示にしているが存在しており、
*  画像のプルダウンで選択した項目と常に同期している。
*/

jQuery.noConflict();
var alternateSelectMenuBuilder = function() {
	var classes = {
		unit: 'selectMenuUnit',
		selectedItem: 'altSelectedItem',
		menu: 'altMenu'
	};
	var prefixId = {
		selectedItem: 'si_',
		menu: 'm_'
	};
	return (function() {
		// オリジナルのselectボックスを取得
		var selects = jQuery('.' + classes.unit).find('select');
		var ids = {};

		// selectボックスからメニュの枠組みを生成
		selects.each(function(i, elem) {
			var id = jQuery(elem).attr('id');
			var wrapper = jQuery(elem).parent('span');
			var selectedItemId = prefixId.selectedItem + id;
			var menuId = prefixId.menu + id;
			wrapper
				.after('<div />').next().eq(0).addClass(classes.selectedItem).attr('id', selectedItemId)
					.after('<div />').next().eq(0).addClass(classes.menu).attr('id', menuId).append('<p />').append('<ul />')
				.end()
			.end();
			ids[id] = [selectedItemId, menuId];
		});
		return ids;
	})();
}

var AlternateSelectMenu = function(selectId, selectedItemId, menuId, label) {
	this.label = label;
	this.selectId = selectId;
	this.selectedItemId = selectedItemId;
	this.menuId = menuId;
	
	this.selectedClass = 'selected';
	this.showClass = 'show';
	this.list = [];
	
	// 初期化
	this.init();
}

AlternateSelectMenu.prototype = {
	// 初期化
	init: function() {
		var self = this;

		j(this.menuId).children('p').text(this.label);
		// オリジナルのselectボックスからリストを取得し、ulへセット
		this.updateMenuList();

		// メニューの1番上の項目を選択状態にする
		var label = (function(label) {
			var label = label;
			return {
				text: function() {
					return label;
				}
			}
		})(this.label);
		this.setSelectedItem(label, false);
	},

	// selectedItemに選択中の項目を表示する
	setSelectedItem: function(item, classChanging) {
		var selectedItem = j(this.selectedItemId);
		selectedItem.text(item.text());
		if (classChanging !== false) { 
			item.siblings().removeClass(this.selectedClass).end().addClass(this.selectedClass);
		}
	},

	// オリジナルのselectボックスの値を変更
	changeSelect: function(n) {
		var select = j(this.selectId);
		select.get(0).options.selectedIndex = n;
		select.change();
	},
	
	// オリジナルのselectボックスからリストを取得し、ulへセット
	updateMenuList: function() {
		var self = this;
		var select = j(this.selectId);
		var options = select.find('option');
		var menu = j(this.menuId);
		var ul = menu.children('ul');
		ul.empty(); // ulを空にする
		var isSelected = false;
		options.each(function(i, option) {
			isSelected = jQuery(option).attr('selected');
			ul.append('<li>' + jQuery(option).text() + '</li>');
			var li = ul.children().eq(i);
			li.hover(
				function() {
					jQuery(this).addClass('hover');
				},
				function() {
					jQuery(this).removeClass('hover');
				}
			).data('num', i);
			self.list.push(li);
			// selectedがtrueのoptionのとき、画像プルダウンの方も選択された状態にする
			if (isSelected) {
				self.setSelectedItem(li);
			}
		});
	},

	// プルダウンの表示・非表示切り替え
	toggleMenu: function() {
		var menu = j(this.menuId);
		if (menu.hasClass('show')) {
			this.hideMenu();
		} else {
			this.showMenu();
		}
	},

	// プルダウンを表示
	showMenu: function() {
		var menu = j(this.menuId);
		var co = j('controls').offset();
		var o = j(this.selectedItemId).offset();
		menu.css({
			left: o.left - co.left + 'px',
			top: (o.top - co.top + 20) + 'px'
		});
		menu.addClass(this.showClass).show();
	},

	// プルダウン非表示
	hideMenu: function() {
		var menu = j(this.menuId);
		menu.removeClass(this.showClass).hide();
	}
}

function j(id) {
	return jQuery('#' + id);
}

// DOM構築後に実行（主にイベントの割り当て）
jQuery(function() {
	var labels = {
		type: 'Produkttyp',
		industry: 'Industrie',
		taskList: 'Anwendung'
	};
	var ids = alternateSelectMenuBuilder();
	
	var menus = {};
	jQuery.each(ids, function(selectId, id) {
		menus[selectId] = new AlternateSelectMenu(selectId, id[0], id[1], labels[selectId]);
	});

	jQuery.each(menus, function(id, menuUnit) {
		var selectedItem = j(menuUnit.selectedItemId);
		var menu = j(menuUnit.menuId);
		selectedItem.click(function(event) {
			var id = jQuery(this).attr('id');
			hideAllMenu(id);
			menuUnit.toggleMenu();
			event.stopPropagation();
		});

		menu.find('li').live('click', function() {
			var item = jQuery(this);
			var n = item.data('num');
			menuUnit.setSelectedItem(item);
			menuUnit.changeSelect(n);
			menuUnit.hideMenu();
			refreshMenu();
		});
	});

	jQuery('body').click(function(event) {
		hideAllMenu();
	});

	function hideAllMenu(ignoreId) {
		jQuery.each(menus, function(id, menuUnit) {
			if (menuUnit.selectedItemId == ignoreId) return true;
			menuUnit.hideMenu();
		});
	}

	function refreshMenu() {
		jQuery.each(menus, function(id, menuUnit) {
			menuUnit.updateMenuList();
		});
	}
});
