var moduleEdit = new Array();var moduleEditSubmit = new Array();var moduleEditBeforeSubmit = new Array();var moduleEditCancel = new Array();moduleEdit["simplecontent"] = null;if (typeof tinyMCE != 'undefined')
{
	tinyMCE.init({
		// General options
		language : "hu", 
		theme : "advanced",
		width : "100%",
		plugins : "safari,pagebreak,style,layer,table,save,advimage,advlink,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,advdesign,simplepaste",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,styleselect",
		theme_advanced_buttons2 : "forecolor,backcolor,bullist,numlist,hr,sub,sup,|,media,image,insertfile,insertimage,|,undo,redo,|,link,unlink,|,cleanup,removeformat,code,visualaid",
		theme_advanced_buttons3 : "search,preview,|,tablecontrols,|,advdesignlist",
		theme_advanced_toolbar_location : "external",
		//theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		//theme_advanced_statusbar_location : "bottom",
		theme_advanced_styles : ""+_CMS_TINYMCE_STYLES,

			content_css : 'tinymce.css',
			paste_as_plain_text : true,
			paste_create_paragraphs : false,
			paste_create_linebreaks : false,
			paste_use_dialog : true,
			paste_auto_cleanup_on_paste : true,
			paste_convert_middot_lists : false,
			paste_unindented_list_class : "unindentedList",

		forced_root_block : 'div', // surrounds content with <div> - key to br usage
		force_br_newlines : true,
		force_p_newlines : false,
		auto_focus : "frontend_tinymce"

	});
}

var editContentCache = "";

function setAutoResizeTinyMCE(ed)
{
    //Function to fix iframe to document height
    fitEditor = function(ed)
    {
        editorID = ed.id;
        var tble, frame, doc, docHeight, frameHeight;
        
        frame = document.getElementById(editorID+"_ifr");
        if ( frame != null )
        {
            //get the document object
            if (frame.contentDocument) doc = frame.contentDocument; 
            else if (frame.contentWindow) doc = frame.contentWindow.document; 
            else if (frame.document) doc = frame.document; 
            
            if ( doc == null )
            return;
            
            //prevent the scrollbar from showing
            doc.body.style.overflow = "hidden";
            
            //Fixes the issue of the table leaving empty space below iframe
            tble = frame.parentNode.parentNode.parentNode.parentNode;
			//alert(tble.id);
            tble.style.height = 'auto';
            
            frameHeight = parseInt(frame.style.height);
            
            //Firefox
            if ( doc.height ) docHeight = doc.height;
            //MSIE
            else docHeight = parseInt(doc.body.scrollHeight);
            
            //MAKE BIGGER
            if ( docHeight > frameHeight ) frame.style.height = (docHeight) + "px";
            //MAKE SMALLER
            else if ( docHeight < frameHeight ) frame.style.height = Math.max((docHeight), 10) + "px";
        }
    };
    
	fitEditor(ed);
    //add fitEditor function to tinyMCE events
    ed.onSetContent.add( fitEditor );
	ed.onClick.add( fitEditor );
    ed.onChange.add( fitEditor );
    ed.onKeyUp.add( fitEditor );
//Remaining bug: (Chrome and Opera) editor grows but doesn't shrink
}

moduleEdit["simplecontent"] = function (module_id)
{
	var item = $("#simplecontent-"+module_id);
	var pos = item.position();
	
	// IE 7 alatt bugos !
	item.expose({	api: true,
					color: '#000000',
					opacity: 0.1,
					zIndex: 1030,
					loadSpeed: 'slow',
					closeSpeed: 'slow',
					closeOnClick: false});

	item.expose().load();
	
	$("#simplecontent-"+module_id+" .module_edit_button").css("display", "none");
	$("#simplecontent-"+module_id+" .module_delete_button").css("display", "none");
	$(".placeholder").sortable( 'disable' );
	createTinyEditor(module_id);
	//tinyMCE.execInstanceCommand("frontend_tinymce", "mceFocus");
	
	$("#frontend_tinymce_external").append('<div id="simplecontentAcceptButton"  onclick="acceptEdit('+module_id+')"></div>');
	$("#frontend_tinymce_external").append('<div id="simplecontentCancelButton"  style="left: 378px;" onclick="cancelEdit('+module_id+')"></div>');
}

function createTinyEditor(id)
{
	editContentCache = $("#simplecontent-"+id).html();
	
	var wrapper = $("#simplecontent-"+id+" .simplecontentTextWrapper").wrapInner('<div id="frontend_tinymce" class="mceContentBody" ></div>');
	
		if( $("#simplecontent-"+id+" .box_top").length > 0)
		{
			var current_design = $("#simplecontent-"+id+" .box_top").attr("class").substr(8);
			var backcolor = $("#wrapper-"+id).css("background-color");
			tinyMCE.execCommand('mceAddControl', false, 'frontend_tinymce');
			
			// haxos
			setTimeout(function()
			{
				setAutoResizeTinyMCE(tinyMCE.get('frontend_tinymce'));
				tinyMCE.getInstanceById('frontend_tinymce').getWin().document.body.style.backgroundColor = backcolor;
				tinyMCE.get('frontend_tinymce').plugins['advdesign'].setListValue(current_design);
			}, 500);
		}
		else
		{
			tinyMCE.execCommand('mceAddControl', false, 'frontend_tinymce');
			
			// haxos
			setTimeout(function(){
				setAutoResizeTinyMCE(tinyMCE.get('frontend_tinymce'));
				tinyMCE.get('frontend_tinymce').plugins['advdesign'].setListValue("normal");
			}, 500);
		}
		
		$("#frontend_tinymce_external").css("margin-top", "-60px");
}

function acceptEdit(id)
{
	var design = "";
	
	if (tinyMCE.getInstanceById('frontend_tinymce'))
	{
		design = tinyMCE.get('frontend_tinymce').plugins['advdesign'].getCurrentValue();
	
		if(design != "normal")
			design = design.substr(14);
		
		tinyMCE.triggerSave();
		
		tinyMCE.execCommand('mceFocus', false, 'frontend_tinymce');
		tinyMCE.execCommand('mceRemoveControl', false, 'frontend_tinymce');
	}
	
	$("#simplecontent-"+id).expose().close();
	$("#simplecontent-"+id).expose({api: false});
	
	$("#simplecontentAcceptButton").remove();
	$("#simplecontentCancelButton").remove();
	$("div#frontend_tinymce").after($('div#frontend_tinymce').children()).remove();
	$("#simplecontent-"+id+" .module_edit_button").css("display", "");
	$("#simplecontent-"+id+" .module_delete_button").css("display", "");
	$(".placeholder").sortable( 'enable' );
	
	var content = $("#simplecontent-"+id+" .simplecontentTextWrapper").html();
	$.post(	_CMS_DIR+'/frontend/modules/simplecontent/edit.handler.php',
			{	'edited_content_id' : id,
				'content': content,
				'content_frame': design},
			function(data)
			{
				
			});
}

function cancelEdit(id)
{
	if (tinyMCE.getInstanceById('frontend_tinymce'))
	{	
		tinyMCE.execCommand('mceRemoveControl', false, 'frontend_tinymce');
	}
	
	$("#simplecontent-"+id).html(editContentCache);
	$("#simplecontent-"+id).expose().close();
	$("#simplecontent-"+id).expose({api: false});
	
	$("#simplecontentAcceptButton").remove();
	$("#simplecontentCancelButton").remove();
	$("div#frontend_tinymce").after($('div#frontend_tinymce').children()).remove();
	$("#simplecontent-"+id+" .module_edit_button").css("display", "");
	$("#simplecontent-"+id+" .module_delete_button").css("display", "");
	$(".placeholder").sortable( 'enable' );
}moduleEdit["menu"] = null;moduleEdit["booklisting"] = null;
moduleEdit["booklisting"] = function(module_id)
{
	initEditDialog(_CMS_DIR+"/frontend/modules/booklisting/edit.form.php", module_id, "booklisting");
}

moduleEditBeforeSubmit["booklisting"] = function(data)
{	
	
	var id = "";
	var sequence = "";
	var full_sequence = "";
	
	if($("#booklistingEditTable tr.active_row").length < 1)
	{
		alert("Legalább 1 elemet ki kell választania !");
		return false;
	}
	
	$("#booklistingEditTable tr.active_row").each(function(){
		id = $(this).children(".book_id_field").html();
		sequence += id+";";
	});
	
	$("#booklistingEditTableBody tr").each(function(){
		id = $(this).children(".book_id_field").html();
		full_sequence += id+";";
	});
	
	
	var sort_by = "";
	var sorted_column = $("#booklistingEditTableHead tr").find(".sorted-asc, .sorted-desc");
	
	if(sorted_column.hasClass("sorted-asc"))
	{
		sort_by = sorted_column.attr("id").substr(12);
		sort_by += " ASC";
	}
	else if(sorted_column.hasClass("sorted-desc"))
	{
		sort_by = sorted_column.attr("id").substr(12);
		sort_by += " DESC";
	}
	
	document.getElementById("booklisting_sort_by").value  = sort_by;
	document.getElementById("booklisting_limit").value    = document.getElementById("booklistingLimitSetter").value;
	document.getElementById("booklisting_sequence").value = sequence;
	document.getElementById("booklisting_full_sequence").value = full_sequence;
	
	return true;
}


function setUpSorting()
{
	$("#booklistingEditTableBody").sortable({ 	handle: '.arrange_icon',
												axis: 'y',
												change: function(event, ui) {
													$("#booklistingEditTableHead tr th").removeClass("sorted-asc");
													$("#booklistingEditTableHead tr th").removeClass("sorted-desc");
												} 
											});


	$('#booklistingEditTableHead .sortable').each(function(column){
		$(this).click(function()
		{
			sortTheColumn('booklistingEditTable', this.id, column, 0);
		});
	});
	
}

function sortTheColumn(table_id, col_head_id, col, direction)
{
	var findSortKey = 	function($cell)
						{
							return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
						};
						
						if(direction != 0)
							var sortDirection = direction;
						else
							var sortDirection = $("#"+col_head_id).is('.sorted-asc') ? -1 : 1;
						
						var $rows = $("#"+table_id).find('tbody tr').get();
						
						//loop through all the rows and find 
						$.each($rows, function(index, row) {
							row.sortKey = findSortKey($(row).children('td').eq(col));
						});
						
						//compare and sort the rows alphabetically
						$rows.sort(function(a, b) {
							if (a.sortKey < b.sortKey) return -sortDirection;
							if (a.sortKey > b.sortKey) return sortDirection;
							return 0;
						});
						
						//add the rows in the correct order to the bottom of the table
						$.each($rows, function(index, row) {
							$('#'+table_id+' tbody').append(row);
							row.sortKey = null;
						});
						
						//identify the column sort order
						$('#'+table_id+'Head tr th').removeClass('sorted-asc sorted-desc');
						var $sortHead = $('#'+table_id+' thead th').filter(':nth-child(' + (col + 1) + ')');
						sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
						
						//identify the column to be sorted by
						$('#'+table_id+' tbody td').removeClass('sorted')
									.filter(':nth-child(' + (col + 1) + ')')
									.addClass('sorted');
}

function changeVisibilityState(element, id)
{
	$("#sorttable_row_"+id).toggleClass("active_row");
}

function changeLimitBox(direction)
{
	var limit = parseInt(document.getElementById("booklistingLimitSetter").value);
	if(direction == "up")
	{
		 document.getElementById("booklistingLimitSetter").value = (limit+1);
	}
	else
	{
		if(!(limit < 2))
			document.getElementById("booklistingLimitSetter").value = (limit-1);
	}
}

var openMyModal = function(source)
{
	modalWindow.windowId = "myModal";
	modalWindow.width = 500;
	modalWindow.height = 580;
	modalWindow.content = "";
	modalWindow.open();
};