function copy(id) {
	var value = $('original_' + id).value;
	$('translation_'+id).value = value;
}

function wopen(obj) {
	obj.target = '_blank';
}

function popup_scroll(url, width, height) {
      wnd = window.open(url, "popup", "width="+width + ",height="+height
      +",left=150,top=100,resizable=yes,scrollbars=yes");
      wnd.focus();
}

function popup(url) {
	var wnd = window.open(url);
	wnd.focus();
}

function appendTextBlock(text) {
	var input = $('message');
	input.focus();
	if(typeof input.selectionStart != 'undefined')
	{
		/* Einfügen des Formatierungscodes */
		var start = input.selectionStart;
		var end = input.selectionEnd;
		input.value = input.value.substr(0, start) + text + input.value.substr(end);
		var offset = 0;
		if(window.opera) {
			lines = text.split("\n");
			offset = lines.length;
		}
		input.selectionStart = end+text.length+offset;
		input.selectionEnd = end+text.length+offset;
	}
	else if(typeof document.selection != 'undefined') {
		var range = document.selection.createRange();
		range.text = text;
	}
}

function toggleTextBlocks(type) {
	var rows = $$('tr.typeid_'+type);
	rows.forEach(function(row){
		row.style.display = row.style.display == 'none' ? '' : 'none';
	});
}

function changeProject(projectID) {
	$$('.projectvis').each(
		function(el) {
			el.setStyle('display', el.id == 'projecttable_' + projectID ? 'block' : 'none');
		}
	);
	$$('.selected').each(
		function(vl) {
			vl.removeClass('selected');
			vl.addClass('normal');
		}
	);
	$('nav_' + projectID).setAttribute('class', 'selected');
}

function selectAll(checked, name) {
	$$('.' + name).each(
		function(el) {
			el.checked = checked;
		}
	);
}

function check_values(form, id) {
	var select_box = $(id);
	var options = false;

	for(var i = 0; i < select_box.options.length; i++) {
		if(select_box.options[i].disabled != true) {
			options = true;
		}
	}

	if(options == true) {
		form.submit();
		return true;
	}
	else {
		return alert('Invalid resource');
	}
}

function insertBBcode(textareaID, startTag, endTag) {
		var input = $(textareaID);
		input.focus();

		/* für Internet Explorer */
		if(typeof document.selection != 'undefined') {
			 /* Einfügen */
			var range = document.selection.createRange();
			var insText = range.text;
			range.text = startTag + insText + endTag;

			/* Cursorposition anpassen */
			range = document.selection.createRange();
			if (insText.length == 0) {
				range.move('character', -endTag.length);
			} else {
				range.moveStart('character', startTag.length + insText.length + endTag.length);
			}
			range.select();
		}

		/* für neuere auf Gecko basierende Browser */
		else if(typeof input.selectionStart != 'undefined') {
			/* Einfügen */
			var start = input.selectionStart;
			var end = input.selectionEnd;
			var insText = input.value.substring(start, end);
			input.value = input.value.substr(0, start) + startTag + insText + endTag + input.value.substr(end);

			/* Cursorposition anpassen */
			var pos;
			if (insText.length == 0) {
				pos = start + startTag.length;
			} else {
				pos = start + startTag.length + insText.length + endTag.length;
			}
			input.selectionStart = pos;
			input.selectionEnd = pos;
		}
}

var AjaxWindow = {
	Binds: ['focusOn'],
	windows: {},

	focusOn: function(name) {
		for(var w in this.windows) {
			this.windows[w].setStyle('z-index', 100);
		}

		this.windows[name].setStyle('z-index', 101);
	},	
	
	rightshow: function(name, id, nickname)
	{
		var window_key = name + '_' + id;
		var window_div = new Element('div', {'id': 'window_' + window_key, 'class': 'window'});
		this.windows[window_key] = window_div;

		/**
		 * create window xhtml
		 */
		var xhtml = '<div class="window_borders">';
		xhtml += '<h2 id="window_' + window_key + '_handle" style="cursor: move">Set Supporter Rights ' + nickname + '</h2><a href="javascript:AjaxWindow.close(\'' + window_key + '\');" class="window_close">Close</a>';
		xhtml += '<div id="window_' + window_key + '_content" class="window_content"></div>';
		xhtml += '</div>';
		window_div.set('html', xhtml);
		
		var scrollH = Window.getScrollTop() + 50;
		window_div.setStyle('top', scrollH + 'px');

		window_div.injectInside('windows');

		window_div.addEvent('mousedown', function() {
			this.focusOn(window_key);
		}.bind(this));
		
		var drag = new Drag(window_div, {handle: 'window_' + window_key + '_handle'});

		new Request({
			url: '/rights/' + name +'/?id=' + id, 
			method: 'post',
			data: {

			},
			onComplete: function(data)
			{

				data = JSON.decode(data);
				window.addEvent('domready', function(){
					$('window_' + window_key + '_content').set('html', data.page);
					new Toggler($$('input[type="checkbox"]'));
				});				
			}.bind(this)
		}).send();
	},

	editshow: function(name, id, nickname)
	{
		var window_key = name + '_' + id;
		var window_div = new Element('div', {'id': 'window_' + name, 'class': 'window'});
		this.windows[window_key] = window_div;

		/**
		 * create window xhtml
		 */
		var xhtml = '<div class="window_borders">';
		xhtml += '<h2 id="window_' + window_key + '_handle" style="cursor: move">Edit Signature ' + nickname + '</h2><a href="javascript:AjaxWindow.close(\'' + window_key + '\');" class="window_close">Close</a>';
		xhtml += '<div id="window_' + window_key + '_content" class="window_content"></div>';
		xhtml += '</div>';
		window_div.set('html', xhtml);
		
		var scrollH = Window.getScrollTop() + 50;
		window_div.setStyle('top', scrollH + 'px');

		window_div.injectInside('windows');
		
		window_div.addEvent('mousedown', function() {
			this.focusOn(window_key);
		}.bind(this));
		
		var drag = new Drag(window_div, {handle: 'window_' + window_key + '_handle'});

		new Request({
			url: '/rights/' + name +'/?id=' + id,
			method: 'post',
			data: {

			},
			onComplete: function(data)
			{
				data = JSON.decode(data);
				window.addEvent('domready', function(){
					$('window_' + window_key + '_content').set('html', data.page);
					new Toggler($$('input[type="checkbox"]'));
				});
			}.bind(this)
		}).send();
	},
	
	payshow: function(name, id)
	{
		var window_key = name + '_' + id;
		var window_div = new Element('div', {'id': 'window_' + name, 'class': 'window'});
		this.windows[window_key] = window_div;

		/**
		 * create window xhtml
		 */
		var xhtml = '<div class="window_borders">';
		xhtml += '<h2 id="window_' + window_key + '_handle" style="cursor: move">Delegate to payment team</h2><a href="javascript:AjaxWindow.close(\'' + window_key + '\');" class="window_close">Close</a>';
		xhtml += '<div id="window_' + window_key + '_content" class="window_content"></div>';
		xhtml += '</div>';
		window_div.set('html', xhtml);
		
		var scrollH = Window.getScrollTop() + 50;
		window_div.setStyle('top', scrollH + 'px');

		window_div.injectInside('windows');

		window_div.addEvent('mousedown', function() {
			this.focusOn(window_key);
		}.bind(this));
		
		var drag = new Drag(window_div, {handle: 'window_' + window_key + '_handle'});

		new Request({
			url: '/tickets/paydeleg/?id=' + id,
			method: 'post',
			data: {

			},
			onComplete: function(data)
			{
				data = JSON.decode(data);
				window.addEvent('domready', function(){
					$('window_' + window_key + '_content').set('html', data.page);
					new Toggler($$('input[type="checkbox"]'));
				});
			}.bind(this)
		}).send();
	},

	setJSHTML: function(div, content)
	{
		// return if div is no element (possibly window already closed)
		if(!div) {
			return;
		}

		var search = content;
		var script;
		var endscript;
		var scriptInsert = false;

		div.innerHTML = content;

		while((script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i))) {
			search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);
			if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) {
				break;
			}

			var block = search.substr(0, search.indexOf(RegExp.$1));
			search = search.substring(block.length + RegExp.$1.length);
			eval(block);
	    }
	},

	close: function(name)
	{
		this.windows[name].dispose();
	}
};

function toggle_hide_class(classname) {
	var elements = $$('div.' + classname);
	elements.forEach(function(element){
		element.style.display = element.style.display == 'none' ? '' : 'none';
	});
}

function status_toggle_hide() {
	var headers = $$('th.row_header');
	var colspan = 3;


	var days_cells = $$('td.status_age_days');
	var hours_cells = $$('td.status_age_hours');
	var show_days_checkbox = $('show_days');
	var show_hours_checkbox = $('show_hours');

	if(!show_days_checkbox.checked) {
		colspan -= 1;
	}
	if(!show_hours_checkbox.checked) {
		colspan -= 1;
	}

	days_cells.forEach(function(days_cell){
		days_cell.style.display = show_days_checkbox.checked == true ? '' : 'none';
	});

	hours_cells.forEach(function(hours_cell){
		hours_cell.style.display = show_hours_checkbox.checked == true ? '' : 'none';
	});

	headers.forEach(function(header) {
		header.setAttribute("colspan", colspan);
	});
}

function toggleMenu() {
	var state = Cookie.read('menu');
	
	if(!state) { state = 'show'; }
	
	if(state == 'show') {
		Cookie.dispose('menu');
		Cookie.write('menu', 'hide', {duration: 30, path: '/'});
		$('menu').setStyle('display', 'none');
		$('content').setStyle('margin-left', '0px');
		
	}
	else {
		Cookie.dispose('menu');
		Cookie.write('menu', 'show', {duration: 30, path: '/'});
		$('menu').setStyle('display', '');
		$('content').setStyle('margin-left', '175px');
	}
}

function initMenu() {
	var state = Cookie.read('menu');
	
	if(!state) { state = 'show'; }

	if(state != 'show') {
		$('menu').setStyle('display', 'none');
		$('content').setStyle('margin-left', '0px');
	}
	else {
		$('menu').setStyle('display', '');
		$('content').setStyle('margin-left', '175px');
	}
}

function toggleWorlds() {
	if($('worlds').getStyle('display') == 'none') {
		$('worlds').setStyle('display', '');
	}
	else {
		$('worlds').setStyle('display', 'none');
	}
}

function ipLookup(postID, ip) {
	$('ip_container_' + postID).set('html', 'Retrieving...');
	new Request({
		url: '/tickets/ip/?ip=' + ip,
		method: 'get',
		onComplete: function(data)
		{
			data = JSON.decode(data);
			if(data.country == 'XX') data.country = 'unknown';
			$('ip_container_' + postID).set('html', data.host + '<br />Country: ' + data.country);
		}
	}).send();
}

function viewMoreTickets() {
	$$('.ticket_hidden').each( function(el) { el.setStyle('display', 'table-row'); });
}

function checkPlayers(resourceID) {
	var players = $('players').get('value');
	
	new Request( {
		url: '/tickets/checkplayers?players=' + players + '&resource=' + resourceID,
		method: 'get',
		onComplete: function(data)
		{
			data = JSON.decode(data);
			
			if(data.error) {
				alert(data.error);
				return;
			}
			
			xhtml = '<h4>Check results</h4>';
			xhtml += '<ul>';
			$each(data.detailed, function(item, index) { 
				if(item.error) {
					xhtml += '<li><b>' + index + '</b> - <span class="error">Error:</span> ' + item.text + '</li>';
				}
				else {
					xhtml += '<li><b>' + index + '</b> - <span class="success">Success:</span> ' + item.text + '</li>';
				}
			});
			xhtml += '</ul>';
			
			$('check_result').set('html', xhtml);
		}		
	}).send();
}

function selectPayType(select) {
	var hint = select.options[select.selectedIndex].title;
	
	if(hint) {
		var xhtml = '<h3>Important!</h3>';
		xhtml += hint;
		$('pay_hint').set('html', xhtml);
	}
	else {
		$('pay_hint').set('html', '');
	}
}

function showUploadForm() {
	$('upload').setStyle('display', '');
}