var ajaxProcesses = new Array();

//TODO: remove
/*try {
	elRTE.prototype.save = function() {
		this.beforeSave();
		var v = trim($('#wysiwyg').elrte('val'));
		$('.expanded_rich_text').val(v);
		$('#wysiwyg_dialog').dialog('close');
	}
}
catch(e) {}*/

$(document).ready(function() {
	$('body').bind('ajaxSend', function() {
		$('p.save_btn input').attr('disabled', 'disabled');
		if(ajaxProcesses.length == 0) {
			$('p.save_btn input').each(function() {
				var val = $(this).attr('value');
				$(this).attr('dummy', val);
				$(this).attr('value', 'Подождите...');
			});
		}
		ajaxProcesses.push(1);
	}).bind('ajaxComplete', function() {
		ajaxProcesses.pop();
		if(ajaxProcesses.length == 0) {
			$('p.save_btn input').each(function() {
				var val = $(this).attr('dummy');
				$(this).attr('value', val);
				$(this).removeAttr('dummy');
			});
			$('p.save_btn input').removeAttr('disabled');
		}
	});
	
	 if(window.location.hash) window.scroll(0, 0);
});

function crosstable_del(page_id, tag_id) {
	var data = {
		"page_id" : page_id,
		"field" : $("#"+tag_id).attr("field"),
		"field_id" : $("#"+tag_id).attr("field_id")
	};
	$.post("api.php", {"cmd":"crosstable_del", "data":data}, function(res) {
		//alert(res);
		$("#"+tag_id+"_wrap_"+page_id).remove();
	});
}
function alu_zebra(selector, first_td_align) {
	if(!selector) selector = "body";
	if(!first_td_align) first_td_align = "right";
	var odd = $("table.alu > tbody > tr:odd", $(selector));
	var even = $("table.alu > tbody > tr:even", $(selector));
	odd.css({"background-color":"#eee"});
	even.css({"background-color":"#f7f7f7"});
	var first_td = {"padding":"3px 20px 10px 6px", "text-align":first_td_align, "vertical-align":"top"};
	$("td:eq(0)", odd).css(first_td);
	$("td:eq(0)", even).css(first_td);
	var second_td = {"padding":"3px 3px 10px 6px", "text-align":"left", "vertical-align":"top"};
	$("td:eq(1)", odd).css(second_td);
	$("td:eq(1)", even).css(second_td);
}
function add_check_list(tag_id) {
	var jq = $("#"+tag_id);
	$("input[type='checkbox']", jq).click(function() {
		var p = $(this).parent();
		if($(this).is(":checked")) {
			p.addClass("checked_line");
			$("input[type='text']", p).removeAttr("disabled");
		}
		else {
			p.removeClass("checked_line");
			$("input[type='text']", p).attr("disabled", "disabled");
		}
	});
}
function toggle_check_list(tag_id, jq) {
	jq.toggleClass("icon_minus");
	var rel = jq.parent().parent().parent().attr("rel");
	if(jq.hasClass("icon_minus")) expand_list_branch(tag_id, rel);
	else collapse_list_branch(tag_id, rel);
}
function expand_list_branch(tag_id, rel) {
	$("."+tag_id+"_parent_"+rel).each(function() {
		$(this).removeClass("hidden");
		if($(".icon_minus", $(this)).size() > 0) expand_list_branch(tag_id, $(this).attr("rel"));
	});
}
function collapse_list_branch(tag_id, rel) {
	$("."+tag_id+"_parent_"+rel).each(function() {
		$(this).addClass("hidden");
		if($(".icon_minus", $(this)).size() > 0) collapse_list_branch(tag_id, $(this).attr("rel"));
	});
}
function wysiwyg_editor(selector) {
	$(selector).after("<div class='link rich_text_editor' style='margin-bottom:10px;'> - расширенный редактор - </div>");
	$(".rich_text_editor").click(function() {
		$(".expanded_rich_text").removeClass("expanded_rich_text");
		$(this).prev().addClass("expanded_rich_text");
		$("#wysiwyg_dialog").dialog("open");
	});
}
function wysiwyg_dialog() {
	$("#wysiwyg_dialog").dialog({
		width:730,
		position:["50%", 20],
		autoOpen:false,
		modal:true,
		resizable:false,
		open:function() {
			$("#wysiwyg_dialog").html("<div id='wysiwyg_area'><center><textarea id='wysiwyg' style='height:400px;'>"+$(".expanded_rich_text").val()+"</textarea></center></div>");
			init_wysiwyg();
		},
		close:function() {
			$("#wysiwyg_area").remove();
			$(".expanded_rich_text").removeClass("expanded_rich_text");
		},
		buttons: {
			"Ok" : function() {rich_text_save()}
		}
	});
	if($('#filemanager_dialog').length == 1) {
		$('#filemanager_dialog').dialog({
			width:640,
			position:['50%', 20],
			autoOpen:false,
			modal:true,
			resizable:false,
			open:function() {open_filemanager();},
			close:function() {close_filemanager();}
		});
	}
}
function rich_text_save() {
	$(".expanded_rich_text").val($("#wysiwyg").tinymce().getContent());
	$("#wysiwyg_dialog").dialog("close");
}
function open_wysiwyg() {
	// фикс для ie и пустых полей
	var v = $('.expanded_rich_text').val() ? $('.expanded_rich_text').val() : "<p></p>";
	$('#wysiwyg_dialog').html("<div id='wysiwyg_area'><div id='wysiwyg'>"+v+"</div></div>");
	init_wysiwyg();
}
function close_wysiwyg() {
	$('#wysiwyg').elrte('destroy');
	$('#wysiwyg_area').remove();
	$('.expanded_rich_text').removeClass('expanded_rich_text');
}
function init_wysiwyg() {
	$("#wysiwyg").tinymce({
		// Location of TinyMCE script
		script_url : "../tiny_mce/tiny_mce.js",
		
		// General options
		mode : "textareas",
		language : "ru",
		theme : "advanced",
		plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
		relative_urls : false,
		
		// Theme options
		theme_advanced_buttons1 : "code,cleanup,removeformat,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,formatselect,|,bold,italic,underline,strikethrough,|,forecolor,backcolor,|,justifyleft,justifycenter,justifyright,justifyfull,|,fullscreen,preview,help",
		theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,tablecontrols",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		
		// Example content CSS (should be your site CSS)
		content_css : "/media/common.css",
		
		// elFinder
		file_browser_callback : function(field_name, url, type, win) {
			$('<div id="mighty_elfinder_wysiwyg" />').elfinder({
				url : "../elfinder/connectors/php/connector.php",
				lang : "ru",
				dialog : {
					width : 800,
					modal : true,
					resizable : false,
					title : "Менеджер файлов",
					zIndex : 300330,
					close : function() {
						$(document).unbind("keydown");
						$(document).unbind("keypress");
					}
				},
				editorCallback : function(url) {
					win.document.forms[0].elements[field_name].value = url;
					$("iframe").contents().find("input#src").change();
				}
			});
		}
	});
}
function save_tab_check(tag_id, api_location, callback) {
	if(!api_location) api_location = '';
	var json = {};
	var jq = $("#"+tag_id);
	$("div.hie_checkbox_item", jq).each(function(index) {
		json[index] = {
			"key" : $(this).attr("key"),
			"level" : $(this).attr("level"),
			"val" : $("input[type='text']:first", $(this)).val(),
			"checked" :  $("input[type='checkbox']:first", $(this)).is(":checked") ? 1 : 0
		};
	});
	var data = { 
		"field" : jq.attr("field"), 
		"field_id" : jq.attr("field_id"), 
		"list_id" : jq.attr("list_id"), 
		"json" : json 
	};
	$.post(api_location+"api.php", {"cmd":"save_tab_check", "data":data}, function(res) {
		if(res) alert(res);
		else if(callback) eval(callback);
	});
}
function set_tab(selector) {
	try {$(selector).tabs("destroy");}
	catch(e) {}
	$(selector).tabs({
		select: function(event, ui) {
			var li = $('li:eq('+ui.index+')', $(selector));
			// loader для вкладок с атрибутом ajax
			if(!isNaN(li.attr('ajax'))) $($('a', li).attr('href'), selector).html("<img src='images/wait.gif' />");
		},
		ajaxOptions: {
			error: function(xhr, status, index, anchor) {
				$(anchor.hash).html("Ошибка загрузки");
			}
		}
	});
}
function save_cost() {
	var data = {
		'page_id' : cnf['page_id'],
		'cost' : $('#cost').val(),
		'cost_ua' : $('#cost_ua').val()
	};
	$.post('api.php', {'cmd':'save_cost', 'data':data}, function(res) {
		if(res) alert(res);
	});
}
function feed_add(page_id) {
	if(confirm("Добавить питание?")) {
		var data = {'page_id' : page_id};
		$.post('api.php', {'cmd':'feed_add', 'data':data}, function(res) {
			if(res) $("table#feed").append(res);
		});
	}
}
function feed_del(feed_id) {
	if(confirm("Удалить питание?")) {
		var data = {'feed_id' : feed_id};
		$.post('api.php', {'cmd':'feed_del', 'data':data}, function(res) {
			if(res) alert(res);
			else $('#feed tr[rel="'+feed_id+'"]').remove();
		});
	}
}
function feed_save() {
	var dummy = {};
	$("tr.feed_row").each(function() {
		var id= $(this).attr("rel");
		dummy[id] = {
			"period" : $(".feed_period", $(this)).val(),
			"system_id" : $(".feed_system", $(this)).val(),
			"type_id" : $(".feed_type", $(this)).val(),
			"note" : $(".feed_note", $(this)).val()
		};
	});
	var data = {"dummy" : dummy};
	$.post("api.php", {"cmd":"feed_save", "data":data}, function(res) {
		if(res) alert(res);
	});
}
function ajax_loader(selector) {
	$(selector).html("<p><img src='/media/images/wait.gif' /></p>");
}
