var legacy = (document.contentEditable != null && navigator.userAgent.indexOf('Mobile') < 0);
var debug = false;
var immediate = true;
var queue = new Array();
var fancyactive = false;

function createlink()
{
	var url = prompt("Please enter a URL", "");
	document.execCommand("createlink", false, url);
}

function togglehtml2(obj)
{
	togglehtml($(obj).parent().parent());
}

function togglehtml(obj)
{
//TODO: fix autosubmission
	var parent = obj;
	var ui = parent.children('#ui').detach();
	var ptext = parent.html();
	ptext = '<code>' + ptext.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&lt;\/p&gt;\s*/g, '&lt;/p&gt;<br /><br />') + '</code>';
	if(!parent.data('htmltoggle')) parent.html(parent.text());
	else parent.html(ptext);
	parent.append(ui);
	parent.data('htmltoggle', !parent.data('htmltoggle'));
}

// Key handling for HTML editor
var isCtrl = false;

if(!document.all)
document.onkeyup = function (e){
	if(e.which == 17) isCtrl = false;
}

if(!document.all)
document.onkeydown = function (e){
	if(isCtrl == true)
	{
		switch(e.which)
		{
			case 66:
				document.execCommand("bold", false, null);
				return false;
				break;
			case 73:
				document.execCommand("italic", false, null);
				return false;
				break;
			case 76:
				var url = prompt("Please enter a URL", "");
				document.execCommand("createlink", false, url);
				return false;
				break;
			case 83:
				while(queue.length > 0)
					ajaxSave(queue.shift());
				return false;
				break;
		}
	}
	else
	{
		switch(e.which)
		{
			case 13:
				if(currentElement && currentElement.data('htmltoggle')) document.execCommand("insertParagraph", false, null);
				break;
			case 17: isCtrl = true; break;
		}
	}
}

function showError(text, thistext)
{
	$.fancybox('<textarea rows="25" cols="100">' + text + '</textarea>',{'showCloseButton' : true});
	if(thistext) thistext.animate({backgroundColor: '#EE0000'}, 500);
}

function ajaxQueue(xsl, parameters, item, value, oldvalue, thistext, id, index)
{
	var obj = new Array();
	obj['xsl'] = xsl;
	obj['parameters'] = parameters;
	obj['item'] = item;
	obj['value'] = value;
	obj['oldvalue'] = oldvalue;
	obj['thistext'] = thistext;
	obj['id'] = id;
	obj['index'] = index;
	if(immediate) ajaxSave(obj);
	else queue.push(obj);
}

function ajaxSave(obj)
{
	var xsl = obj['xsl'];
	var xslobj = $('#xsl-' + xsl);
	var file = xslobj.attr('data-file');
	var parameters = obj['parameters'];
	var item = obj['item'];
	var value = obj['value'];
	var oldvalue = obj['oldvalue'];
	var thistext = obj['thistext'];
	var id = obj['id'];
	var index = obj['index'];
	var mode = "edit";
	if((!oldvalue || oldvalue == '')) mode = "add";
	// clean up stray tags
	if(!value) mode = "remove";
	else
	{
		value = value.replace(/[\r\n]+$/, '').replace(/(<br ?\/?>)+$/g, '').replace(/(<br ?\/?>)+<\/p>/g, '</p>').replace(/^<p><\/p>$/, '');
		if(value == '')
		{
			if(mode == 'add') return;
			mode = "remove";
		}
	}
	
	if(debug) showError(mode + ' file:' + file + ' param:' + parameters + ' item:' + item + ' value:' + escape(value) + ' oldval:' + escape(oldvalue) + ' index:' + index + ' id:' + id);

	var artid = window.location.pathname;
	artid = artid.substr(artid.lastIndexOf('/') + 1);
	$.ajax
	({
		type: 'POST',
		url: '/ajaxsave.jsp',
		data: 
		({
			file: file,
			parameters: parameters,
			item: item,
			value: value,
			oldvalue: oldvalue,
			mode: mode,
			itemindex: id,
			indexvalue: index,
			artid: artid,
			xsl: xslobj.html()
		}),
		dataType: 'xml',
		success: function(xml){
			var error = $(xml).find('error');			
			if(error.length > 0)
			{
				showError(error.text(), thistext);
				return;
			}
			var response = $(xml).find('status');
			if(response.length > 0)
			{
				// Update item
				var thisparent = thistext.parent();
				var newhtml = $(xml).find('update').text();
				if(newhtml.indexOf('Error:') == 0)
				{
					showError(newhtml, thistext);
					return;
				}
				var newparent = $(newhtml);
				setEditable(newparent);
				thisparent.replaceWith(newparent);
				newparent.animate({backgroundColor: '#00EE00'}, 500).animate({backgroundColor: '#FFFFFF'});
			}
			else
			{
				showError('Unknown error:' + $(xml).text(), thistext);
			}
		},
		error: function(xml, status, error){
			showError(status + ' ' + xml.responseText, thistext);
		}
	});
}

function loadSelect(obj, xsl, parameters, item, index, indexitem)
{
	obj.children().remove();
	obj.text('Loading...');
	var xslobj = $('#xsl-' + xsl);
	var template = xslobj.html();
	var file = xslobj.attr('data-file');
	if(debug) showError(' file:' + file + ' param:' + parameters + ' item:' + item + ' index:' + index);
	$.ajax
	({
		type: 'POST',
		url: '/ajaxload.jsp',
		data: 
		({
			file: file,
			parameters: parameters,
			item: item,
			index: index,
			xsl: template
		}),
		dataType: 'xml',
		success: function(xml) {
			var error = $(xml).find('error');
			if(error.length > 0)
			{
				showError(error.text());
				return;
			}
			var newselect = $('<select class="select"/>');
			newselect.change(function(event){
				if($(this).data('oldvalue') != $(this).val())
				{
					$(this).animate({backgroundColor: '#DDDDDD'});
					//(xsl, parameters, item, value, oldvalue, thistext, id, index)
					ajaxQueue($(this).attr("data-xsl"), $(this).attr("data-param"), $(this).attr("data-item"), $(this).val(), $(this).data('oldvalue'), $(this), $(this).attr('data-index'), $(this).attr('data-indexitem'));
				}
			});
			var item2 = item.substr(item.lastIndexOf('/') + 1);
			$('<option value="">Select ' + item2 + '</option>').appendTo(newselect);
			$(xml).find(item2).each(function(){
				var newindexitem = $(this).siblings(index).text();
				if(newindexitem == indexitem) newselect.data('oldvalue', newindexitem);
				$('<option value="' + newindexitem +'"' + (newindexitem == indexitem ? ' selected="selected"' : '') + '>' + $(this).text() + '</option>').appendTo(newselect);
			});
			obj.empty();
			obj.append(newselect.attr("data-xsl", xsl).attr("data-param", parameters).attr("data-item", item.substr(0, item.lastIndexOf('/') + 1) + index));
//			obj.data('oldvalue', newselect.data('oldvalue'));
			obj.removeClass('editnow');
		},
		error: function(xml, status, error){showError("Error: " + status + " " + error + " " + xml.responseText, obj);}
	});
}

function editEmpty()
{
	if($.cookie('userview')) return;
	if($(this).attr('data-value') && $(this).attr('data-value') != '') return;
	$(this).html('(' + $(this).attr('data-item').substring($(this).attr('data-item').lastIndexOf("/") + 1) + ')').addClass('editempty');
	$(this).one('click', function(){
		if($(this).hasClass('editblock')) $(this).children('p').empty();
		else $(this).empty();
	});
}

function editEmptySelect()
{
	if($.cookie('userview')) return;
	if($(this).attr('data-value') && $(this).attr('data-value') != '') return;
	$(this).html('(' + $(this).attr('data-item').substring($(this).attr('data-item').lastIndexOf("/") + 1) + ')').addClass('editempty');
}

function relative(obj)
{
	if(obj.css('position') == '' || obj.css('position') == 'static') obj.css('position', 'relative');
}

var editbutton = '<button class="edit" onclick="edit(this)">Edit</button>';
var selectbutton = '<button class="select" onclick="select(this)">Select</button>';
var killbutton = '<button class="kill" onclick="kill(this)">Remove</button>';

function kill(obj)
{
	var par = $(obj).parent().parent();
	if(!confirm("Are you sure?")) return;
	par.unbind('click');
	par.animate({backgroundColor: '#DDDDDD'});
	par=par.children('.edithide');
	var item = par.attr('data-item').substring(0, par.attr('data-item').lastIndexOf('/') + 1) + par.attr('data-index');
	if(par.hasClass('editselect')) ajaxQueue(par.attr('data-xsl'), par.attr('data-param'), item, '', par.attr('data-indexitem'), par, undefined, undefined);
	else ajaxQueue(par.attr('data-xsl'), par.attr('data-param'), par.attr('data-item'), '', par.data('oldvalue'), par, par.attr('data-index'), par.attr('data-indexitem'));
	par.parent().empty();
}

function select(i)
{
	var obj = $(i).parent().parent();
	if(!obj.hasClass('editselect')) obj = obj.children('.editselect');
	loadSelect(obj.parent(), obj.attr('data-xsl'), obj.attr('data-param'), obj.attr('data-item'), obj.attr('data-index'), obj.attr('data-indexitem'));
}

function select2(i)
{
	var obj = $(this);
	loadSelect(obj.parent(), obj.attr('data-xsl'), obj.attr('data-param'), obj.attr('data-item'), obj.attr('data-index'), obj.attr('data-indexitem'));
}

function textedit(e)
{
	e.stopPropagation();
	if(currentElement == this) return;
	texteditblur(currentElement);
	currentElement = this;
	if($(this).hasClass('editing')) return;
	var oldvalue = $(this).clone(true);
	oldvalue.children('#ui').remove();
	relative($(this));
	if(legacy)
	{
		$(this).addClass('editing');
		if($(this).hasClass('edittext'))
		{
			if($(this).hasClass('editempty')) $(this).data('oldvalue', '');
			else $(this).data('oldvalue', oldvalue.html()); // store old value
			$(this).html('<input type="text" value="' + $(this).data('oldvalue') + '" />');
			$(this).children('input').focus();
		}
		else if($(this).hasClass('editblock'))
		{
			if($(this).hasClass('editempty')) $(this).data('oldvalue', '');
			else $(this).data('oldvalue', oldvalue.html()); // store old value
			$(this).html('<textarea>' + $(this).data('oldvalue') + '</textarea>');
			$(this).children('textarea').focus();
		}			
	}
	else
	{
		var range = window.getSelection().getRangeAt(0);
		var startC = range.startContainer;
		var startO = range.startOffset;
		var endC = range.endContainer;
		var endO = range.endOffset;
		if($(this).hasClass('editblock') && $(this).children('p').length == 0) $(this).wrapInner('<p/>');
		$(this).addClass('editing').attr('contentEditable', true).focus();
		if($(this).hasClass('editempty')) $(this).data('oldvalue', '');
		else $(this).data('oldvalue', oldvalue.html()); // store old value
		range = window.getSelection().getRangeAt(0);
		range.setStart(startC, startO)
		range.setEnd(endC, endO);
		if($(this).hasClass('editblock'))
		{
			$(this).data('htmltoggle', true);
			$(this).append('<div id="ui"><button onclick="document.execCommand(\'bold\', false, null);">B</button>'
				+ '<button onclick="document.execCommand(\'italic\', false, null);">I</button>'
				+ '<button onclick="createlink();">Link</button>'
				+ '<button onclick="togglehtml2(this);">HTML</button></div>');
		}
	}
}

function edit(obj)
{
	edit2($(obj).parent().parent());
}

function edit2(obj)
{
	var hidden = obj.find('.edithide');
	obj.unbind('hover');
	if(hidden)
	{
		obj.empty();
		obj.append(hidden);
		hidden.removeClass('edithide');
		hidden.each(function(){if($(this).attr('data-value') != '') $(this).html($(this).attr('data-value'));});
		hidden.show();		
	}
	obj.find('.edittext,.editblock').each(function()
	{
		$(this).before(' ' + $(this).attr('data-item').substring($(this).attr('data-item').lastIndexOf('/') + 1) + ': ');
	});
	obj.find('.edittext,.editblock').click(textedit).select(textedit).hover(edithover1, edithover2).blur(texteditblur);
	
	obj.find('.editselect').each(select2);
}

function edithover1()
{
	$(this).addClass('editnow');
}

function edithover2()
{
	if(!$(this).data('stillediting')) $(this).removeClass('editnow');
}

function texteditblur(i)
{
	if($(i).hasClass('editblock') && !$(i).data('htmltoggle') && !fancyactive) {togglehtml($(i));}
	$(i).children('#ui').remove();
	$(i).removeClass('editnow');
	$(i).removeClass('editing');
	if(legacy)
	{
		$(i).html($(i).children('input,textarea').val());
	}
	else
	{
		$(i).attr('contentEditable', false);
	}
	var newvalue = $(i).clone(true);
	newvalue.children('#ui').remove();
	if($(i).data('oldvalue') != newvalue.html())
	{
		if($(i).hasClass('editblock') && newvalue.html().length > 0 && newvalue.html().indexOf('<') < 0)
		{
			alert('Formatting lost. Please e-mail Aaron, telling him what you were doing when this message appeared.');
			window.location = 'http://www.nintendoworldreport.com/mail/7367?subject=FORMATTING BUG';
			return;
		}
		$(i).animate({backgroundColor: '#DDDDDD'});
		ajaxQueue($(i).attr('data-xsl'), $(i).attr('data-param'), $(i).attr('data-item'), newvalue.html(), $(i).attr('data-oldvalue').slice(1,-1)/* $(i).data('oldvalue')*/, $(i), $(i).attr('data-index'), $(i).attr('data-indexitem'));
		$(i).data('oldvalue', newvalue.html());
	}
	$(i).removeClass('editempty');
	if($(i).html() == '' || $(i).html() == '<p></p>') $(i).each(editEmpty);
}

var currentElement;

// Dynamic editor
function setEditable(i)
{
	if($.cookie('userview')) return;

	$('html').click
	(function(){
		if(currentElement) texteditblur(currentElement);
		currentElement = undefined;
	});
	
	i.find('.edittext,.editblock').click(textedit).select(textedit).css('minHeight', '1em');

	i.find('.edittext,.editblock,.editdate').hover(edithover1, edithover2);

	i.find('.edittext').bind('paste', function(e){
		e.preventDefault();
		return false;
	});

	
// Empty editable fields
	i.find('.edittext:empty,.editblock:empty').each(editEmpty);
	i.find('.editselect:empty').each(editEmptySelect);

// Add
	i.find('.additem').hide();
	i.find('.addable').each
	(function(i){
		if($.cookie('userview')) return;
		var id = $(this).attr('data-item');
		var additem = $(this).find('.additem');
		var addbutton = $('<button class="new">Add ' + id.substring(id.lastIndexOf("/") + 1) + '</button>');
//		addbutton.data("additem", additem);
		addbutton.click
		(function(event){
//			var additem = $(this).data("additem");
	//		var newitem = additem.clone(true);
			var newitem = $(this).prev().find('.additem').clone(true);
			$(this).prev().append(newitem.show());
			edit2(newitem);
			// set additem index to -1
		});
		$(this).after(addbutton);
	});
	
	i.find('.editselect').hover
	(function(){
			var ui = $('<div id="ui"/>');
			ui.append(selectbutton);
			if($(this).parent('.addable').length > 0) ui.append(killbutton);
			$(this).append(ui);
			$(this).addClass('editnow');
	},
	function(){
			$(this).children('#ui').remove();
			$(this).removeClass('editnow');
	});

	
// Date edit
	i.find('.editdate').click
	(function(){
		if($.cookie('userview')) return;
//		$(this).append("<div></div>");
//		cal = $(this).children(':last').datepicker();
	});
	
	i.find('.editdate').blur
	(function(){
		if($.cookie('userview')) return;
		var datetext = $(this).value();
// Months

// Quarters

// Cancelled
		if(datetext == 'Cancelled') datetext = '1/1/4000';
// Rumor		
		if(datetext == 'Rumor') datetext = '1/1/5000';
		ajaxQueue($(this).attr('data-xsl'), $(this).attr('data-param'), $(this).attr('data-item'), datetext, $(this).data('oldvalue'), mode, $(this), $(this).attr('data-index'), $(this).attr('data-indexitem'));
//		cal.remove();
	});

	i.find('.edithide').parent(':not(.edititem)').wrapInner('<span class="edititem"/>');
//$('.edithide').parent(':not(.edititem)').html('XXX');
	i.find('.edithide').hide();
	
	i.find('.edititem').hover
	(function(){
			var ui = $('<div id="ui"/>');
			if($(this).children('.edithide').length > 0)
			{
				if($(this).children('.edithide').length == 1 && $(this).children('.editselect').length == 1) ui.append(selectbutton);
				else ui.append(editbutton);
			}
			relative($(this));
			relative($(this).parent());
			if($(this).parent().hasClass('addable')) ui.append(killbutton);
			$(this).append(ui);
			$(this).addClass('edititemnow');
	},
	function(){
			$(this).children('#ui').remove();
			$(this).removeClass('edititemnow');
	});
	
	i.filter('.edititem').hover
	(function(){
			var ui = $('<div id="ui"/>');
			if($(this).children('.edithide').length > 0)
			{
				if($(this).children('.edithide').length == 1 && $(this).children('.editselect').length == 1) ui.append(selectbutton);
				else ui.append(editbutton);
			}
			relative($(this));
			relative($(this).parent());
			if($(this).parent().hasClass('addable')) ui.append(killbutton);
			$(this).append(ui);
			$(this).addClass('edititemnow');
	},
	function(){
			$(this).children('#ui').remove();
			$(this).removeClass('edititemnow');
	});

	
// Image edit TODO
	
}

function ready()
{
	setEditable($('body'));
	
// Staff/User view toggle
	$('#edittoggle').click
	(function(event){
		if($(this).html() == 'User View')
		{
//			$(this).html('Staff View');
			$.cookie("userview", "true");
		}
		else
		{
//			$(this).html('User View');
			$.cookie("userview", null);
		}
		$('body').animate({opacity: 0}, 1000, function() {});
		window.location.reload();
//		$('.staffaccess,.selectable,.kill,.new,.editempty').toggle();
	});
	
	if($.cookie('userview'))
	{
		$('#edittoggle').html('Staff View');
		$('.staffaccess,.selectable,.kill,.new,.editempty,.additem').toggle();
	}

// Slide menu   
	$('.slidetrigger').click
	(function(event){
		if($(this).next().is(':hidden'))
		{
			$('.slidemenu').slideUp('slow');
			$(this).next().slideDown('slow');
		}
	});

	$('.slidemenu').hide();
	$('.slidemenu:first').show();

// Filter menu
	$('#filterForm select').change
	(function(event){
		$('#filterForm').submit();
	});

// FancyBox image/iframe handling
	$('a.image,a.thickbox').fancybox({'type': 'image', 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'titlePosition': 'inside', 'onStart': function(){fancyactive = true;}, 'onClosed': function(){fancyactive = false;}});
	$('a.iframe').fancybox({'hideOnContentClick': false, 'transitionIn': 'elastic', 'titlePosition': 'inside', 'transitionOut': 'elastic', 'onStart': function(){fancyactive = true;}, 'onClosed': function(){fancyactive = false;}});

// Front page headline switching
	$('a.fronthover').hover
	(function(){
		$(this).data('prevheadline', $(this).siblings('a.sectionLeader').html());
		$(this).siblings('a.sectionLeader').html($(this).html());
	},
	function(){
		$(this).siblings('a.sectionLeader').html($(this).data('prevheadline'));
	});

// Reviews page 2
	$('#scorespage').hide();
	$('.conclusion,.conclusion2').click
	(function(event){
		$('#article').toggle();
		$('#summary').toggle();
		$('#scorespage').toggle();
	});

// Related link labels
	$('.relatedLabel').each
	(function(i){
		var div = document.createElement('div');
		$(div).hide();
		$(div).html($(this).is('img') ? $(this).attr('alt') : $(this).html());
		document.body.appendChild(div);
		$(this).css('font-size', Math.min(parseFloat($(this).css('font-size'), 10) / $(div).outerWidth() * $(this).width() * 0.75, 20) + 'px');
		$(div).remove();
	});
	//if(!document.all) document.execCommand("styleWithCSS", false, false);
}

$(document).bind("ready", ready);

