/*
 * @author	W-Mark Kubacki; kubacki@hurrikane.de
 */

function display_error(msg) {
	if(window['Modalbox']) {
		Modalbox.MessageBox.alert(catgets(0), msg);
	} else {
		alert(msg);
	}
}

function obtJSON(method, url, postVars, onCompleteCallback) {
	new Ajax.Request(url, {
		method: method,
		parameters: postVars,
		requestHeaders: ['Content-Type', 'application/x-www-form-urlencoded'],
		onSuccess: function(r) {
			var json = r.responseText.evalJSON();
			onCompleteCallback(json);
		},
		onFailure: function(r) {
			var json = r.responseText.evalJSON();
			if(json['error']) {
				display_error(json['error']);
			} else {
				display_error(catgets(23));
			}
		}
	});
}
function postJSON(url, postVars, onCompleteCallback) {
	return obtJSON('post', url, postVars, onCompleteCallback);
}
function getJSON(url, postVars, onCompleteCallback) {
	return obtJSON('get', url, postVars, onCompleteCallback);
}

Ajax.Responders.register({
	onCreate: function() {
		$('global_spinner').show();
	},
	onComplete: function() {
		if(Ajax.activeRequestCount <= 0) {
			$('global_spinner').hide();
		}
	}
});

function remove_item_with_effect(id) {
	new Effect.Fade(id, {afterFinish: function() {
		$(id).remove();
	}});
}

function add_incoming_Effect(id) {
	Element.hide(id);
	new Effect.Appear(id);
}

var DynList = {
	hideInputs: function(container_id) {
		Element.hide(container_id + '_form');
		Element.show(container_id + '_opt');
	},

	showInputs: function(container_id) {
		Element.show(container_id + '_form');
		Element.hide(container_id + '_opt');
	}
}

var MainMenuBar = {
	init: function() {
		MainMenuBar.shown = null;
		MainMenuBar.pe = {};
		$$('#main_menu_bar div.submenu ul').invoke('hide');
	},

	showSubMenu: function(mainmenu_id, submenu_id) {
		node = $(submenu_id);
		if(MainMenuBar.shown && MainMenuBar.shown.id != submenu_id) {
			$$('#main_menu_bar .selected').invoke('removeClassName', 'selected');
			MainMenuBar.shown.hide();
		}
		node.show();
		MainMenuBar.shown = node;
		MainMenuBar.stopAutoHiding(submenu_id);
		$(mainmenu_id).addClassName('selected');
	},

	stopAutoHiding: function(submenu_id) {
		if(MainMenuBar.pe[submenu_id]) {
			MainMenuBar.pe[submenu_id].stop();
		}
	},

	scheduleForHiding: function(mainmenu_id, submenu_id) {
		node = $(submenu_id);
		mmu = $(mainmenu_id);
		if(MainMenuBar.pe[submenu_id]) {
			MainMenuBar.pe[submenu_id].stop();
		}
		MainMenuBar.pe[submenu_id] =
		new PeriodicalExecuter(function(pe) {
			if(node.visible()) {
				mmu.removeClassName('selected');
				node.hide();
			}
			pe.stop();
		}, 9);
	}
}

var LanguageDynList = {
	addItemFromText: function(container_id, contact_id, textfield_id) {
		var txt_f = $(textfield_id);
		var value = txt_f.value;
		var container = $(container_id + '_list');;
		function myCallback(result) {
			txt_f.value = '';
			container.tBodies[0].insert(result['item']);
			add_incoming_Effect('language_' + result['lang_id']);
		}
		postJSON('/contact/language/add', {'contact_id': contact_id, 'language': value}, myCallback);
	},

	removeItem: function(language_id) {
		function myCallback(result) {
			remove_item_with_effect('language_' + language_id);
		}
		postJSON('/contact/language/remove', {'language_id': language_id}, myCallback);
	}
}

var PhoneDynList = {
	addItemFromText: function(container_id, ttype, tid, typefield_id, textfield_id, bb_id) {
		var textfield = $(textfield_id);
		if(textfield.value == '') return;
		var ptype = $(typefield_id).value;
		var value = textfield.value;
		var is_business = $(bb_id).checked;
		var container = $(container_id + '_list');
		function myCallback(result) {
			textfield.value = '';
			container.tBodies[0].insert(result['item']);
			add_incoming_Effect('phone_' + result['item_id']);
		}
		postJSON('/phone/add',
			{'ttype': ttype, 'tid': tid, 'phone_type': ptype, 'phone_number': value, 'is_business': is_business},
			myCallback);
	},

	removeItem: function(phone_id) {
		function myCallback(result) {
			remove_item_with_effect('phone_' + phone_id);
		}
		postJSON('/phone/remove', {'phone_id': phone_id}, myCallback);
	}
}

var CompanyInterestDynList = {
	addItemFromText: function(container_id, company_id, key_f, region_f, locally_present_c) {
		var c = $(container_id + '_list');
		var key = $(key_f).value;
		var region = $(region_f).value;
		var locally_present = $(locally_present_c).checked;
		function myCallback(result) {
			c.tBodies[0].insert(result['item']);
			add_incoming_Effect('company_interest_' + result['item_id']);
		}
		postJSON('/company/interest/add',
			{'company_id': company_id, 'key': key, 'region': region, 'locally_present': locally_present},
			myCallback);
	},

	removeItem: function(id) {
		function myCallback(result) {
			remove_item_with_effect('company_interest_' + id);
		}
		postJSON('/company/interest/remove', {'id': id}, myCallback);
	}
}

var CompanyTagDynList = {
	addItemFromText: function(container_id, company_id, tag_f, confirmed_c) {
		var c = $(container_id + '_list');
		var txt_f = $(tag_f);
		if(txt_f.value == '') return;
		var tag = txt_f.value;
		var confirmed = $(confirmed_c).checked;
		function myCallback(result) {
			txt_f.value = '';
			c.tBodies[0].insert(result['item']);
			add_incoming_Effect('company_tag_' + result['item_id']);
		}
		postJSON('/company/tag/add', {'company_id': company_id, 'tag': tag, 'confirmed': confirmed}, myCallback);
	},

	removeItem: function(id) {
		function myCallback(result) {
			remove_item_with_effect('company_tag_' + id);
		}
		postJSON('/company/tag/remove', {'id': id}, myCallback);
	}
}

var CatDynList = {
	addItemFromText: function(container_id, type, company_id, category_f) {
		var txt_f = $(category_f);
		if(txt_f.value == '') return;
		var category = txt_f.value;
		var c = $(container_id + '_list');
		function myCallback(result) {
			txt_f.value = '';
			c.tBodies[0].insert(result['item']);
			add_incoming_Effect('company_category_' + result['item_id']);
		}
		postJSON('/company/category/add', {'company_id': company_id, 'category': category}, myCallback);
	},

	removeItem: function(id) {
		function myCallback(result) {
			remove_item_with_effect('company_category_' + id);
		}
		postJSON('/company/category/remove', {'id': id}, myCallback);
	},

	selectAndClose: function() {
		$('catdyn_input').value = $('category_id_f').value;
		this.addItemFromText('catdyn', 'company', $('company_input_form_id').value, 'catdyn_input');
		Modalbox.hide();
	},

	selectCategory: function(category) {
		$('category_id_f').value = category;
	}
}

var NoteDynList = {
	showItem: function(note_id) {
		function myCallback(result) {
			$('note_' + note_id).replace(result['item']);
		}
		postJSON('/note/display_show', {'note_id': note_id},myCallback);
	},

	editItem: function(note_id) {
		function myCallback(result) {
			$('note_' + note_id).replace(result['item']);
		}
		postJSON('/note/display_edit', {'note_id': note_id}, myCallback);
	},

	saveItem: function(note_id, textarea_id) {
		var text = $(textarea_id).value;
		function myCallback(result) {
			$('note_' + note_id).replace(result['item']);
		}
		postJSON('/note/save', {'note_id': note_id, 'text': text}, myCallback);
	},

	addItemFromText: function(container_id, ttype, tid, textfield_id) {
		var value = $(textfield_id).value;
		function myCallback(result) {
			$(container_id + '_tbody').insert(result['item']);
			// add_incoming_Effect('note_' + result['item_id']);
			DynList.hideInputs(container_id);
			$(textfield_id).value = '';
		}
		postJSON('/note/add', {'ttype': ttype, 'tid': tid, 'text': value}, myCallback);
	},

	removeItem: function(note_id) {
		function myCallback(result) {
			remove_item_with_effect('note_' + note_id);
		}
		postJSON('/note/remove', {'note_id': note_id}, myCallback);
	}
}

var CompanyContact = {
	changePositionInCompany: function(e, rel_id, old_val) {
		function jsCallback(btn, txt) {
			if(btn == 'ok') {
				function myCallback(result) {
					$(e).update(txt);
				}
				postJSON('/contact/position/change', {'rel_id': rel_id, 'position': txt}, myCallback);
			}
		}
		Modalbox.MessageBox.prompt(catgets(1), catgets(2).replace('{0}', old_val), old_val, jsCallback);
	},

	addExistingContact: function(company_id) {
		function jsCallback(btn, txt) {
			if(btn == 'ok') {
				function myCallback(result) {
					PagingDataGrid.reload('contact_companies');
				}
				postJSON('/company/add_contact', {'company_id': company_id, 'contact_id': txt}, myCallback);
			}
		}
		Modalbox.MessageBox.prompt(catgets(3), catgets(4), '', jsCallback);
	},

	addToExistingCompany: function(contact_id) {
		function jsCallback(btn, txt) {
			if(btn == 'ok') {
				function myCallback(result) {
					PagingDataGrid.reload('contact_companies');
				}
				postJSON('/company/add_contact', {'company_id': txt, 'contact_id': contact_id}, myCallback);
			}
		}
		Modalbox.MessageBox.prompt(catgets(5), catgets(6), '', jsCallback);
	},

	disconnect: function(e, rel_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.reload('contact_companies');
				}
				postJSON('/contact/position/disconnect', {'rel_id': rel_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(7), catgets(8), jsCallback);
	}
}

var Company = {
	drop: function(container, company_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.removeRow(container, company_id);
				}
				postJSON('/company/delete', {'company_id': company_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(9), catgets(10), jsCallback);
	},

	setLogoAndClose: function(logo_url) {
		$('company_logo').src = logo_url;
		Modalbox.hide();
	}
}

var Address = {
	drop: function(container, address_id, company_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.removeRow(container, address_id);
				}
				postJSON('/company/address/delete', {'company_id': company_id, 'address_id': address_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(30), catgets(31), jsCallback);
	}
}

var User = {
	drop: function(container, user_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.removeRow(container, user_id);
				}
				postJSON('/user/delete', {'user_id': user_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(32), catgets(33), jsCallback);
	},

	toggleLock: function(container, user_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.reload(container);
				}
				postJSON('/user/toggle_lock', {'user_id': user_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(34), catgets(35), jsCallback);
	}
}

var Contact = {
	addAcquaintance: function(button_id, contact_id, user_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					$(button_id).replace(result['cellopts']);
					add_incoming_Effect(button_id);
				}
				remove_item_with_effect(button_id);
				postJSON('/contact/connect_with_user', {'contact_id': contact_id, 'user_id': user_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(21), catgets(22), jsCallback);
	},

	removeAcquaintance: function(button_id, contact_id, user_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					$(button_id).replace(result['cellopts']);
					add_incoming_Effect(button_id);
				}
				remove_item_with_effect(button_id);
				postJSON('/contact/disconnect_from_user', {'contact_id': contact_id, 'user_id': user_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(13), catgets(14), jsCallback);
	},

	drop: function(container, contact_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.removeRow(container, contact_id);
				}
				postJSON('/contact/delete', {'contact_id': contact_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(11), catgets(12), jsCallback);
	}
}

var RobinsonList = {
	proceed_bounces: function(frm) {
		var i = $(frm).serialize(true);
		if(i.procedure == 'remove' || i.procedure == 'unsubscribe') {
			function myCallback(result) {
				$("email_txt").value = result['remaining'];
				alert(result['msg_processed']);
			}
			postJSON('/mailings/proceed_bounces', {'email_txt': i.email_txt, 'remove': i.procedure == 'remove'}, myCallback);
		} else if(i.procedure == 'notify') {
			function cbl(result) {
				$("email_txt").value = "";
				alert(result['msg_processed']);
				$(frm).enable();
			}
			postJSON('/mailings/notify', {'to': i.email_txt, 'subject': $('email_subject').value, 'body': $('email_body').value}, cbl);
			$(frm).disable();
			window.setTimeout("$('"+frm+"').enable()", 10000);
		} else if(i.procedure == 'robinson') {
			function bkc(result) {
				$("email_txt").value = "";
				alert(result['msg_processed']);
			}
			postJSON('/mailings/add_to_robinson', {'email_txt': i.email_txt}, bkc);
		}
	},

	drop: function(container, entry_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					PagingDataGrid.removeRow(container, entry_id);
				}
				postJSON('/mailings/robinson_list/remove', {'entry_id': entry_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(19), catgets(20), jsCallback);
	}
}

var JSONSearch = {
	simpleSearch: function(grid_id, data_url, token_e) {
		var sf = $(token_e).value;
		if(sf && sf != '') {
			PagingDataGrid.setNewData(grid_id, data_url, {'token': sf});
		}
	},

	endSearch: function(grid_id, data_url) {
		PagingDataGrid.setNewData(grid_id, data_url, null);
	},

	search: function(exports_url, data_url, token_e, grid_id, result_container) {
		function updateExports(result) {
			lst = $$('#'+result_container+' > ul');
			if(!!lst[0]) {
				lst[0].replace(result['item']);
			}
		}
		var sf = $(token_e).value;
		if(sf && sf != '') {
			postJSON(exports_url, {'token': $(token_e).value}, updateExports);
			JSONSearch.simpleSearch(grid_id, data_url, token_e);
		}
	}
}

var AcquaintanceDynList = {
	connectFromText: function(container, contact_id, user_f) {
		var value = $(user_f).value;
		var c = $(container + '_list');
		function myCallback(result) {
			c.tBodies[0].insert(result['item']);
			add_incoming_Effect('user_' + result['item_id']);
		}
		postJSON('/contact/connect_with_user', {'contact_id': contact_id, 'user_id': value}, myCallback);
	},

	disconnect: function(rel_e, contact_id, user_id) {
		function myCallback(result) {
			remove_item_with_effect(rel_e);
		}
		postJSON('/contact/disconnect_from_user', {'contact_id': contact_id, 'user_id': user_id}, myCallback);
	}
}

var Statistic = {
	get: function(stat_id) {
		function myCallback(result) {
			$('statistic').replace(result['item']);
		}
		postJSON('/statistics/get', {'stat_id': stat_id}, myCallback);
	}
}

var EJournal = {
	createNewIssue: function(publication_id) {
		function myCallback(result) {
			$('issues_listing').insert(result['item']);
			add_incoming_Effect('issue_'+result['id']);
		}
		postJSON('/ejournal/create_new_issue', {'publication_id': publication_id}, myCallback);
	},

	deleteIssue: function(issue_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					remove_item_with_effect('issue_'+issue_id);
				}
				postJSON('/ejournal/delete_issue', {'issue_id': issue_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(19), catgets(20), jsCallback);
	},

	createNewChapter: function(publication_id) {
		function myCallback(result) {
			$('chapter_listing').insert(result['item']);
			add_incoming_Effect('chapter_'+result['id']);
		}
		postJSON('/ejournal/create_new_chapter', {'publication_id': publication_id}, myCallback);
	},

	deleteChapter: function(chapter_id) {
		function jsCallback(btn) {
			if(btn == 'yes') {
				function myCallback(result) {
					remove_item_with_effect('chapter_'+chapter_id);
				}
				postJSON('/ejournal/delete_chapter', {'chapter_id': chapter_id}, myCallback);
			}
		}
		Modalbox.MessageBox.confirm(catgets(19), catgets(20), jsCallback);
	}
}

var resizeables = {}
document.observe('dom:loaded', function() {
	var spinner = $('global_spinner');
	if(spinner) { spinner.hide(); }
	MainMenuBar.init();
	if(typeof(window['Modalbox']) != "undefined") {
		/* Scriptaculous/ModalBox i18n */
		Modalbox.MessageBox.buttonText.cancel = catgets(15);
		Modalbox.MessageBox.buttonText.no = catgets(16);
		Modalbox.MessageBox.buttonText.ok = catgets(17);
		Modalbox.MessageBox.buttonText.yes = catgets(18);
	}
	if(typeof(window['Ext']) != "undefined") {
		/* resizeable text areas */
		$$('textarea.resizeable').each(function(item) {
			new Ext.Resizable(item.id, {
				wrap:true,
				pinned:true,
				width: 600,
				height: 60,
				minWidth: 600,
				minHeight: 60,
				maxWidth: 780,
				dynamic: true
			});
		});
	}
	if(typeof(window['AJAJForms']) != "undefined") {
		AJAJForms.decorateErrors();
		AJAJForms.decorateForms();
	}
	if(typeof(window['PaginationBar']) != "undefined") {
		PaginationBar.text.total = catgets(24);
		PaginationBar.text.first = catgets(25);
		PaginationBar.text.prev = catgets(26);
		PaginationBar.text.next = catgets(27);
		PaginationBar.text.last = catgets(28);
		PaginationBar.text.reload = catgets(29);
		PaginationBar.decoratePagingBars();
	}
});
