var cms_data = null;
var cms_progress_cnt = 0;
var cms_show_error = null;

$(function(){
	$('#left_menu').accordion({
		header: 'h3',
		collapsible: true,
		navigation: true,
		navigationFilter: function(idx) {
			var links = $(this).parents().filter('.ui-accordion-group').find('a.adm').filter(function(){
				var page = $(this).attr('href').split(/[?#]/)[0].replace(/^(.+\/)?([^\/]+)$/, '$2');
				return window.location.href.indexOf(page) >= 0;
			});
			return links.length > 0;
		}
	});

	$('.ui-accordion-content a').click(function() {
		var url = this.href;
		cms_progress(1);
		$.getJSON(url, function(data) {
			cms_progress(-1);
			cms_data = data;
			cms_data.list_url = url;
			cms_list_build();
		});
		return false;
	});
	
	var status = $('<div></div>').appendTo('body');
	status.dialog({
		buttons: {
			'Close': function() {$(this).dialog('close')}
		},
		title: 'AJAX Request Failed',
		minWidth: 400,
		minHeight: 200,
		width: 500,
		height: 400,
		autoOpen: false
	});
	cms_show_error = function(msg) {
		$(status).html(msg);
		$(status).dialog('open');
	};
	status.ajaxError(function(event, request, settings, err) {
		cms_show_error((err ? err.toString() + '<br>' : '') + request.responseText);
	});
});

function cms_item_action(url) {
	cms_progress(1);
	$.getJSON(url, function(data) {
		cms_progress(-1);
		cms_item_action_process(data);
	});
	return false;
}

function cms_item_action_process(data) {
	if(data.content) {
		var div = $('<div></div>');
		var cont = $('div:first', div);
		var y = false;
		if(cont[0]) y = cont[0].scrollTop;
		div.html(data.content);
		if(cont[0]) $('div:first', div)[0].scrollTop = y;
		for(var i in data.buttons) {
			var val = data.buttons[i];
			if(val.match(/^:cms_/)) {
				data.buttons[i] = eval(val.substring(1));
			} else {
				val = String(val).replace(/'/, '\\\'');
				eval('data.buttons[i] = function() { cms_item_action(\'' + val + '\'); $(this).dialog(\'destroy\'); $(this).remove(); }');
			}
		}
		div.dialog({
			buttons: data.buttons,
			title: data.title,
			minWidth: 400,
			minHeight: 200,
			width: 500,
			height: 400,
			resizeStop: function(e, ui) {
				$('div:first', this)
					.width(ui.size.width)
					.height(ui.size.height - $('.ui-dialog-buttonpane', div.parent()).height() - $('.ui-dialog-titlebar', div.parent()).height() - 15);
			},
			close: function(e, ui) {
				$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', this).untinymce();
				$(this).dialog('destroy');
				$(this).remove();
			}
		}).css('padding', '0px');

		$('.HTMLArea_mini', div).tinymce({mini: true});
		$('.HTMLArea_flash', div).tinymce({flash: true});
		$('.HTMLArea_full', div).tinymce();
		
		var w = $('div:first', div)[0].scrollWidth + 15;
		var h = Math.min($('div:first', div)[0].scrollHeight + $('.ui-dialog-buttonpane', div.parent()).height(), window.innerHeight - 100);
		div.data('width.dialog', w);
		div.data('height.dialog', h);
		div.data('position.dialog', [(window.innerWidth - w) / 2, (window.innerHeight - h) / 2]);
		$('div:first', div).height(h - $('.ui-dialog-buttonpane', div.parent()).height() - $('.ui-dialog-titlebar', div.parent()).height() - 15);

		$('form', div).submit(function() {
			cms_form_ajax(this, div);
			return false;
		});
	} else {
		cms_list_refresh(data);
	}
}

function cms_item_info(id, cell) {
	if(id == cms_data.active_id) {
		cms_item_edit(id);
		return;
	}
	$('td', $(cell).closest('table')).removeClass('selected');
	$('td', $(cell).parent()).addClass('selected');
	cms_data.active_id = id;
	var url = cms_data.info_url.split(/\?/, 2);
	cms_progress(1);
	$.get(url[0], url[1] + id, function(html) {
		cms_progress(-1);
		$('#cms_item').html(html);
	});
}

function cms_item_edit(id) {
	return cms_item_action(cms_data.edit_url + id);
}

function cms_form_ajax(form, dlg) {
	$(form).smoothSubmit({
		dataType: 'json',
		processing: $('<span>Processing data...</span>'),
		success: function(data) {
			if(data.content) {
				cms_item_action_process(data);
			} else if(data.error) {
				cms_show_error(data.error);
				$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', dlg).untinymce();
				$(dlg).dialog('destroy');
				$(dlg).remove();
			} else {
				$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', dlg).untinymce();
				$(dlg).dialog('destroy');
				$(dlg).remove();
				cms_list_refresh();
				cms_item_action_process(data);
			}
		}
	});
}

function cms_form_submit() {
	$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', this).commit();
	cms_form_ajax($('form', this)[0], this);
}

function cms_form_refresh() {
	$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', this).untinymce();
	$(this).dialog('destroy');
	$(this).remove();
	cms_list_refresh();
}

function cms_form_cancel() {
	$('.HTMLArea_mini, .HTMLArea_flash, .HTMLArea_full', this).untinymce();
	$(this).dialog('destroy');
	$(this).remove();
}

function cms_list_refresh(url) {
	if(typeof(url) != 'string' || !url)
		url = cms_data.list_url;
	cms_progress(1);
	$.getJSON(url, function(data) {
		cms_progress(-1);
		cms_data = data;
		cms_data.list_url = url;
		cms_list_build();
	});
}

function cms_list_build() {
	html = '<table border="0" cellspacing="0" cellpadding="0" width="100%" class="tablesorter"><thead><tr>';
	
	$('#cms_page_title').html(cms_data.page_title);
	
	for(var i in cms_data.columns)
		html += '<th><div></div>' + cms_data.columns[i].title + '</th>';
	html += '</tr></thead>';

	if(cms_data.footer || cms_data.footer_buttons) {
		var colspan = cms_data.columns.length > 1 ? ' colspan="' + cms_data.columns.length + '"' : '';
		html += '<tfoot><tr><td style="padding-top:5px;"' + colspan + '>';
		if(cms_data.footer)
			html += '<div style="float:left; padding:5px;">' + cms_data.footer + '</div>';
		if(cms_data.footer_buttons) {
			html += '<div class="cms_button_box" style="float:right; padding:0px 5px;">';
			for(var text in cms_data.footer_buttons)
				html += '<button type="button" onclick="cms_item_action(\'' + cms_data.footer_buttons[text] + '\');">' + text + '</button>';
			html += '</div>';
		}
		html += '</td></tr></tfoot>';
	}

	html += '<tbody>';
	for(var i in cms_data.rows) {
		html += '<tr>';
		for(var j in cms_data.rows[i])
			html += '<td onclick="cms_item_info(\''+String(i).replace(/'/, '\\\'')+'\', this);">' + cms_data.rows[i][j] + '</td>';
		html += '</tr>';
	}
	html += '</tbody>';

	html += '</table>';

	$('#cms_table').html(html);
	$('#cms_table > table').tablesorter();
	$('#cms_item').empty();
	$('#cms_table > table a').click(function() {
		if(this.href)
			cms_item_action(this.href);
		return false;
	});
	var h = window.innerHeight ? window.innerHeight :
		(document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : $('body')[0].clientHeight);
	h = Math.round(h - $('#cms_table').offset().top - 150);
	var tbody = $('#cms_table > table tbody');
	if(tbody.height() > h) {
		tbody.css({
			'height': h + 'px',
			'overflow-x': 'hidden',
			'overflow-y': 'auto'
		});
	}
}

function cms_progress(i) {
	if(cms_progress_cnt == 0 && i > 0)
		$('#progress_bar').show();
	cms_progress_cnt += i;
	if(cms_progress_cnt <= 0) {
		cms_progress_cnt = 0;
		$('#progress_bar').hide();
	}
}

