var winManager = new Object;
var activeWindow = null;
// Inline window z-indexes
winManager.zControl = {
	bottom: 100,
	top: 200,
	currentTop: 100,
	currentTopElement: null,
	switchZ: function (win1Id, win2Id) {
		alert(win1Id + ', ' + win2Id);
		win1 = winManager.registry.activeWindows.win1Id;
		win2 = winManager.registry.activeWindows.win2Id;
		win1.zIndex = win2.zIndex;

		win2.zIndex = temp;

		win1.applyZ();
		win2.applyZ();
	},
}

// modal buffer
winManager.modalBuffer = [];

// window registry
winManager.registry = {
	activeWindows: {},
	activeWindowIds: [],
	add: function (obj) {
		this.activeWindows['inline_win_' + this.activeWindowIds.length] = obj;
		this.activeWindowIds.push(this.activeWindowIds.length);
		return this.activeWindowIds.length-1;
	}
};

winManager.inlineWindow = Class.create();

winManager.inlineWindow.prototype = {

	zIndex: null,

	title: null,

	content: null,
	contentURL: null,

	onContent: function () {},

	mode: 'content', // content, iframe, ajax

	isModal: false,

	winId: null,

	buttons: [],

	dragObj: null,

	popupElement: null,

	onClose: function () {},

	onLoad: function () {},

	initialize: function () {
		this.winId = winManager.registry.add(this);
		this.onLoad(arguments);

	},


	doModal: function () {
		this.isModal = true;
		this.show();
	},

	hide: function () {
		if (this.isModal)
		{
			winManager.modalBuffer.pop();

			try {
				$('overlay').style.display = 'none';
			}
			catch (e) {
				alert('overlay not found. cannot do modal');
			}

		}

		this.popupElement.style.display = 'none';
	},

	show: function () {
		if (this.isModal)
		{
			winManager.modalBuffer.push(this.winId);

			try {
				$('overlay').style.display = 'block';
			}
			catch (e) {
				alert('overlay not found. cannot do modal');
			}

		}

		this.popupElement = document.createElement('div');
		this.popupElement.className = 'popup';
		this.popupElement.id = 'inline_win_' + this.winId;

		tmp = ''
		+ '<div class="header"><h1 id="inline_win_handle' + this.winId + '">'
		+ this.title
		+ '</h1><img class="win_close_btn" style="position: absolute; right: 10px; top: 10px;" src="' + APP_DIR + '/image/cancel.png" onclick="winManager.registry.activeWindows[\'inline_win_' + this.winId + '\'].close();"/></div>';

		if (this.mode == 'content' || this.mode == 'ajax') {		
			tmp += '<div class="body" id="inline_win_content' + this.winId + '">'
			+ (this.content ? this.content : '')
			+ '</div>'
			+ '<div style="clear: both"></div>';
		} else {
			tmp += '<iframe class="body" id="inline_win_content' + this.winId + '" src="' + this.contentURL + '">'
			+ '</iframe>'
			+ '<div style="clear: both"></div>';
		}

		this.popupElement.innerHTML = tmp;


		for (i in this.buttons)
		{
			if (typeof(this.buttons[i]) == 'function') continue;

			b = document.createElement('input');
			b.type = 'button';
			b.value = this.buttons[i]['value'];
			b.onclick = this.buttons[i]['onclick'];
			b.style.float = 'right';
			this.popupElement.appendChild(b);
		}
		this.bringToTop();

		this.popupElement.onclick = function () {
			if (winManager.registry.activeWindows[this.id] != winManager.zControl.currentTopElement)
			{
				winManager.registry.activeWindows[this.id].bringToTop();
			}
		}

		test = document.body.appendChild(this.popupElement);
		this.dragObj = new Draggable('inline_win_' + this.winId, {handle: 'inline_win_handle' + this.winId});

		setTimeout (this.onLoad, 700);
	},

	invalidateContent: function () {
		if (!(oldBody = $('inline_win_content' + this.winId)))
		{
			return false;
		}

		newBody = document.createElement('div');
	
		newBody.id = 'inline_win_content' + this.winId;
		newBody.className = 'body';
		newBody.style.display = 'none';

		newBody.innerHTML = (this.content ? this.content : '');

		pNode = oldBody.parentNode;
		oldBody.style.display = 'none';
		pNode.removeChild(oldBody);

		pNode.appendChild(newBody);
		newBody.style.display = 'block';

	},

	close: function () {
		try {
			elem = $('inline_win_' + this.winId)
		}
		catch (e) {
			alert('Window #' + this.winId + ' does not exist');
		}

		if (this.isModal) {
			winManager.modalBuffer.pop();

			if (!winManager.modalBuffer.length) {
				try {
					$('overlay').style.display = 'none';
				}
				catch (e) {
					alert('overlay not found. cannot do modal');
				}
			}
		}

		this.dragObj.destroy();
		elem.hide();
		elem.remove();
	},

	bringToTop: function () {
		this.zIndex = winManager.zControl.currentTop + 1;
		winManager.zControl.currentTop = this.zIndex;
		winManager.zControl.currentTopElement = 'inline_win_' + this.winId;
		this.applyZ();
	},

	applyZ: function() {
		this.popupElement.style.zIndex = this.zIndex;
	},

	updateContent: function (request) {
		this.content = request.responseText;
		$('inline_win_content' + this.winId).innerHTML = this.content;
	},

	updateContentFromURL: function (url) {
		activeWindow = this;
		this.contentURL = url;
		var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: '',
				evalScripts: true, 
				onSuccess: function (r) { activeWindow.doUpdateContent(r);}
			});
	},

	doUpdateContent: function (reponse) {
		this.content = reponse.responseText;
		this.invalidateContent();
	},

	linearizeForm: function () {
//		test = $('inline_win_content' + this.winId).innerHTML;
//		sleep(1);
		fs = $('inline_win_content' + this.winId).getElementsByTagName('form');
		
		inputs = fs[0].getElementsByTagName('input');

		for (i in inputs) {
			if (inputs[i].type == 'submit') {
				inputs[i].type = 'button';
				
				inputs[i].setAttribute("onclick", ""
						+ "new Ajax.Request('" + this.contentURL + "', {"
						+ "	onSuccess: activeWindow.linearFormSuccess, "
						+ "	postBody: Form.serialize(this.form)"
						+ "}); return false;"
						);
				}
		}
	},

	linearFormSuccess: function (response) {
		try {
			eval('v = ' + response.responseText);

			if (v.status == 'error') {
				alert(v.message);
				return;
			}

			activeWindow.onClose(v);
			activeWindow.close();
		}
		catch (e) {
			activeWindow.close();
		}
	}
}

MultipleSelector = Class.create();
MultipleSelector.prototype = Object.extend(winManager.inlineWindow.prototype, {
	lister_url: '',
	add_form_url: '',
	submit_form_url: '',

	host_url: APP_DIR + '/_popup_selector/multiple',

	page: 1,
	hidden_name: 'default',
	
	currentTupple: null,
	selectedSet: [],

	allowMultiple: false,

	listRender: null,

	loadHost: function () {
		this.updateContentFromURL(this.host_url+'/'+this.winId);
	},

	hostLoaded: function (page) {
		if (!page) page = 1;
		new Ajax.Request(this.lister_url + '/' + page + '/1',
			{
				onSuccess: loadlist_cl('inline_win_' + this.winId)
			}
		)
		this.onload();
	},

	getAddForm: function () {
		new Ajax.Request(this.adder_url + '/' + this.winId,
			{
				onSuccess: loadform_cl('inline_win_' + this.winId)
			}
		)
	},

	addReturn: function (res) {

		try {
			eval('r = ' + res.responseText);
		}
		catch(e) {
			alert(e.message);
		}
	
		if (r.status == 'OK') {
			this.hostLoaded();
		}
		else {
			alert(r.message);
		}
	},

	loadForm: function (res) {
		$('win_' + this.winId + '_list_button').disabled = false;
		$('win_' + this.winId + '_add_button').disabled = true;

		$('win_' + this.winId + '_list_controls').style.visibility = 'hidden';
		
		$('win_' + this.winId + '_list_pane').innerHTML = ''
		+ '<form method="POST">'
		+ res.responseText
		+ '<hr/>'
		+ '<input type="button" value="Προσθήκη" onclick="'
		+ "new Ajax.Request('" + this.adder_url + "', {"
		+ "	onSuccess: addreturn_cl('inline_win_" + this.winId + "'), "
		+ "	postBody: Form.serialize(this.form)"
		+ "}); return false;"
		+ '"/>'
		+ '</form>';
	},

	loadList: function (res) {

		try {
			eval('r = ' + res.responseText);
		}
		catch(e) {
			alert(e.message);
		}

		$('win_' + this.winId + '_list_button').disabled = true;
		$('win_' + this.winId + '_add_button').disabled = false;

		$('win_' + this.winId + '_list_controls').style.visibility = '';

		$('win_' + this.winId + '_current_page').innerHTML = r['page'];
		$('win_' + this.winId + '_total_pages').innerHTML = r['total_pages'];

		// controls
		if (r['page'] == '1') {
			$('win_' + this.winId + '_prev_button').disabled = true;
		}
		else {
			$('win_' + this.winId + '_prev_button').disabled = false;
			$('win_' + this.winId + '_prev_button').setAttribute('onclick', 'winManager.registry.activeWindows[\'inline_win_' + this.winId + '\'].hostLoaded(' + (parseInt(r['page'],10)-1) + ')');
		}

		if (r['page'] == r['total_pages']) {
			$('win_' + this.winId + '_next_button').disabled = true;
		}
		else {
			$('win_' + this.winId + '_next_button').disabled = false;
			$('win_' + this.winId + '_next_button').setAttribute('onclick', 'winManager.registry.activeWindows[\'inline_win_' + this.winId + '\'].hostLoaded(' + (parseInt(r['page'],10)+1) + ')');
		}

		// populate list
		$('win_' + this.winId + '_list_pane').innerHTML = '';
		for (i in r['tuples']) {
			t = r['tuples'][i];

			if (typeof t == 'function') continue;

			$('win_' + this.winId + '_list_pane').innerHTML += ''
			+ '<div class="inline_lister_option" onclick="if (winManager.registry.activeWindows[\'inline_win_' + this.winId + '\'].add_to_selected(\'' + t['id'] + '\')) { this.style.backgroundImage = \'\'; }">'
			+ t['title']
			+ (t['informal'] ? '<br/><span class="inline_lister_option_informal">' + t['informal'] + '<span>' : '')
			+ '</div>';

		}

		this.currentTupple = r['tuples'];
	},

	add_to_selected: function (id, title) {

		for (i in this.selectedSet) {
			if (this.selectedSet[i] && this.selectedSet[i].id == id) {
				alert("Το έχει προσθέσει αυτό βρε παπάρα...");
				return false;
			}
		}
		

		if (title) {
			t = {};
			t['id'] = id;
			t['title'] = title;
		}
		else {
			for (i in this.currentTupple) {
				t = this.currentTupple[i];
				if (t['id'] == id) break;
			}
		}

		$('win_' + this.winId + '_selected_pane').innerHTML += ''
		+ '<div class="inline_lister_selected_option" onclick="if (winManager.registry.activeWindows[\'inline_win_' + this.winId + '\'].remove_from_selected(\'' + t['id'] + '\')) { Element.replace(this, \'\') } ">'
		+ t['title']
		+ (t['informal'] ? '<br/><span class="inline_lister_option_informal">' + t['informal'] + '<span>' : '')
		+ '</div>';

		this.selectedSet[this.selectedSet.length] = {'id': t['id'], 'title': t['title']};
		return true;

	},

	remove_from_selected: function (id) {
		for (i in this.selectedSet) {
			if (this.selectedSet[i] && this.selectedSet[i].id == id) {
				this.selectedSet[i] = null;
				return true;
			}
			
		}

		return false;
	},

	setURLs: function (lister, add, submit) {
		this.lister_url = lister;
		this.add_form_url = add;
		this.submit_form_url = submit;
	},

	onOK: function () {
		ret = [];
		for (i in this.selectedSet) {
			if (typeof this.selectedSet[i] == 'function') continue;

			if (!this.selectedSet[i]) continue;

			ret[ret.length] = this.selectedSet[i]; 
		}

		if (!this.listRender) {
			alert(ret);
		}
		else {
			this.listRender(ret);
		}
	},

	onCancel: function () {
		alert('cancel');
	}

});

function loadlist_cl(id) {
	return function (res) {
		return winManager.registry.activeWindows[id].loadList(res);
	}
}

function loadform_cl(id) {
	return function (res) {
		return winManager.registry.activeWindows[id].loadForm(res);
	}
}

function addreturn_cl(id) {
	return function (res) {
		return winManager.registry.activeWindows[id].addReturn(res);
	}
}