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);
			}, 450);
		}
		else
		{
			tinyMCE.execCommand('mceAddControl', false, 'frontend_tinymce');
			
			// haxos
			setTimeout(function(){
				setAutoResizeTinyMCE(tinyMCE.get('frontend_tinymce'));
				tinyMCE.get('frontend_tinymce').plugins['advdesign'].setListValue("normal");
			}, 450);
		}
		
		$("#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["cellarlisting"] = null;
moduleEdit["cellarlisting"] = function(module_id)
{
	//initEditDialog(_CMS_DIR+"/frontend/modules/cellarlisting/edit.form.php", module_id, "cellarlisting");
}

/*moduleEditSubmit["cellarlisting"] = function(data)
{
	var new_data = new Array();
		
		new_data[0] = {name: 'booklisting_limit', value: ""};
		new_data[1] = {name: 'booklisting_sort_by', value: ""};
		new_data[2] = {name: 'booklisting_sequence', value: ""};
		new_data[3] = {name: 'edited_content_id', value: data[3]["value"]};
		
	var id = "";
	$("#booklistingSortTable tr.visible").each(function(){
	
		id = $(this).children(".book_id_field").html();
		sequence += id+";";
	});
	
	new_data[2]["value"] = sequence;
	
	var sort_by = "";
	var sorted_column = $("#booklistingSortTableHead 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;
	alert(data[0]['name']);
}*/

function setUpSortTable()
{
	$("#booklistingSortTable").sortable({ 	handle: '.arrange_icon',
											axis: 'y'});


	$('.dTable thead .sortable').each(function(column){
		$(this).click(function(){ sortTheColumn(this, column, 0); });
	});
	
}

function sortTheColumn(col_head, 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).is('.sorted-asc') ? -1 : 1;
						
						//step back up the tree and get the rows with data
						//for sorting
						var $rows		= $(col_head).parent()
																.parent()
																.parent()
																.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) {
							$('.dTable tbody').append(row);
							row.sortKey = null;
						});
						
						//identify the column sort order
						$('.dTable thead th').removeClass('sorted-asc sorted-desc');
						var $sortHead = $('th').filter(':nth-child(' + (col + 1) + ')');
						sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
						
						//identify the column to be sorted by
						$('td').removeClass('sorted')
									.filter(':nth-child(' + (col + 1) + ')')
									.addClass('sorted');
}


