/*
 *	Copyright (c) 2009-2011 Focus Imaging Limited - http://www.focus-global.com
 */

 
FFJS['ContentList'] = {
	setting: {	
	},

	init: function(module_param ){	 
		if( module_param.selector ==undefined ){
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};	
		if( module_param.setting.arr_key==undefined ){
			module_param.setting['arr_key'] = new Array('S', 'F', 'O', 'P');
		}
		if( module_param.setting.search_list==undefined ){
			module_param.setting['search_list'] = {
				'S': null,
				'F': null,
				'O': null,
				'P': null
			};
		}	

		FFJS.ContentList.setting[div_id] = module_param.setting;
		var current_table = $(FFJS.ContentList.setting[div_id].target+'>tbody');
		var current_head = $(FFJS.ContentList.setting[div_id].target+'>thead');
		
		var key = FFJS.ContentList.setting[div_id].arr_key;	
		for (var i = 0 ; i < key.length ; i++) {
			FFJS.ContentList.setting[div_id].search_list[key[i]] = '';
		};
		
		$(FFJS.ContentList.setting[div_id].target).find('tr:odd').addClass('odd')
					.end().find('tr:even').addClass('even');
					
		if ( current_table.data( 'ContentList' ) === true ) {		
			current_table = null;
			current_head = null;
			return;
		}else{	
			current_table.data('ContentList', true );
		}	

		
		current_table.delegate('td.data>a','click', function() {
			var pid = $(this).parents("#load_list").attr('id');			
			if(pid == "load_list"){
				var filename = $(this).parent().parent().find('td.data a' ).attr("value");
				FFJS.Dialog.update_field_value(filename, this,'record');
				//FFJS.Dialog.update_field_value(filename, this, 'category');
				//FFJS.Dialog.update_field_value(filename, this, 'access');
				filename = null;
			}
		});	
		
		current_table.delegate('a.photo>img','click', function() {
//alert("in img");
			var pid = $(this).parents("#load_list").attr('id');			
			if(pid == "load_list"){
				var filename = $(this).attr('src').replace(/^.*\//, '');
				FFJS.Dialog.update_field_value(filename, this, 'image');
				filename = null;
			}
		});
		
		current_table.delegate('a.doc','click', function() {
			var pid = $(this).parents("#load_list").attr('id');			
			if(pid == "load_list"){
				var filename = $(this).attr('title');
				//var filename = $(this).html();
				FFJS.Dialog.update_field_value(filename, this, 'file');
				filename = null;
			}
		});	
		
		current_head.delegate('a.col_sort','click', function() {
			var header = $(this).parent().parent().parent();
			if (!header.hasClass('sort_up')) {
				header.addClass('sort_up')
						.removeClass('sort_down');
			}else {
				header.addClass('sort_down')
					.removeClass('sort_up');
			}			
			FFJS.ContentList.run(div_id, 'order', header);	
			header = null;
		});
		
		current_table.delegate('tr.data',{
			'mouseover':function(){$(this).addClass('selected');},
			'mouseout':function(){$(this).removeClass('selected');}				
		});

		current_table = null;
		current_head = null;
		key = null;
	},	

	run : function(selector, mode, param) {	
		FFJS.ContentList.updateFilter(selector, mode,param );
		FFJS.ContentList.search( selector,FFJS.ContentList.setting[selector].search_list );		
	},
	
	updateFilter : function(selector, mode,param){
		switch(mode) {
			case 'order':					
				FFJS.ContentList.handle_order( selector,param );
				break;
			case 'page':
				FFJS.ContentList.handle_paging(selector, param );
				break;
			default:
				FFJS.ContentList.handle_reset(selector);	
				break;
		}	
	},

	reload: function( selector ,simple_url){
		var url = '';				
		//$(this).log(0,selector);
		if (simple_url == undefined) {			
			$.each (FFJS.ContentList.setting[selector].search_list,function(key,value){	
				if(value){
					url += '_'+key+'/'+value+'/';
				}
			});	
		}else {
			url = simple_url;
		}
			
		var callback11 = function(){
			if( FFJS.ContentList.setting[selector].callback!= undefined ){
				FFJS.ContentList.setting[selector].callback();				
			}
		};

		$(FFJS.ContentList.setting[selector].target+'>tbody').load(FFJS.url_root+FFJS.ContentList.setting[selector].post_base+url, callback11 );	
		return false;
	},

	search : function(selector,search_list) {
		var search_url = '/';		

		$.each (search_list,function(key,value){	
			if( key == 'S' || key == 'F' ){
				FFJS.ContentList.setting[selector].search_list[key] = value;
			}			
		});		
		
		$.each (FFJS.ContentList.setting[selector].search_list,function(key,value){				
			if(value){
				search_url += '_'+key+'/'+value+'/';
			}
		});	
		FFJS.ContentList.reload(selector,search_url);
	},	

	handle_order : function(selector,obj) {	
		var str_order = obj.attr('id').split('_');
		var ord = '';
		
		if (obj.hasClass('sort_down')) {
			ord = '-d';
		};
		
		FFJS.ContentList.setting[selector].search_list['O'] = str_order[1]+ord;			
		
		if (FFJS.ContentList.setting[selector].search_list['O'] != '') {
			var lu = FFJS.ContentList.setting[selector].search_list['O'].split('/');

			for (var i = 0 ; i <= 2 ; i++) {
				if (lu[i] != undefined) {						
					var tmp = lu[i].split('-');
					
					if (tmp[0] != str_order[1]) {
						FFJS.ContentList.setting[selector].search_list['O'] += '/'+lu[i];
					}
				}
			}
		}		
	},
	
	handle_paging : function(selector, page ) {				
		FFJS.ContentList.setting[selector].search_list['P'] = page;		
	},
	
	handle_reset : function(selector) {		
		$.each (FFJS.ContentList.setting[selector].search_list,function(key,value){			
			FFJS.ContentList.setting[selector].search_list[key] = '';		
		});
	}
};

FFJS['Dialog'] = {
	element : '#dialog',
	modal_val : false,
	width_val : null,
	height_val : null,
	pos_val : 'center',
	resize_val : false,
	title_val : 'Focus CMS',		
	btn_obj : {
		OK: function() {
			$(this).dialog('close');
		}
	},
	post_name : null,
	post_base : null,
	
	init : function( width_val, height_val, title_val ) {
		$(this.element).attr('style', 'text-align:left; display:none;');
		$(this.element).dialog("destroy");

		if (width_val != undefined) {			
			this.width_val = width_val;
		}
		
		if (height_val != undefined) {
			this.height_val = height_val;
		}
		
		if (title_val != undefined) {
			this.title_val = this.title_val + ' - ' + title_val;
		}
	},
	
	reset : function() {
		this.title_val = 'Focus CMS';
		this.btn_obj = {
			OK: function() {
				$(this).dialog('close');
			}
		};
	},
	
	open : function(element_val) {
		if (element_val != undefined) {
			this.element = element_val;
		}
		
		$(this.element).dialog({
			modal : this.modal_val,				
			width : this.width_val,
			height : this.height_val,
			resizable : this.resize_val,
			position : this.pos_val,			
			title : this.title_val
		})
		.dialog('open');
		
		FFJS.Dialog.reset();
		FFJS.Dialog.fix_bug2();
	},
	
	msg_dialog : function (element_val, btn_val) {
		if (element_val != undefined) {
			this.element = element_val;
		}

		if (btn_val != undefined) {
			this.btn_obj = btn_val;
		}

		$(this.element).dialog({
			dialogClass : 'msg_dialog',	
			closeOnEscape : false,
			modal : this.modal_val,				
			width : this.width_val,
			height : this.height_val,
			resizable : this.resize_val,
			position : this.pos_val,			
			title : this.title_val,				
			buttons: this.btn_obj				
		})
		.dialog('open');

		FFJS.Dialog.reset();
		//Dialog.fix_bug();
	},
	
	errorHandler : 	function(response, status, xhr) {
		var msgD = '#msgDialog';			
		if (status == "error") {			
			if(typeof(response) == 'object'){
				var text = response.responseText;
			}else{
				var text = response;
			}
			var msg = "<p class='error'> Sorry ! "+ text + "</p>";
			$(msgD).html(msg);
			FFJS.Dialog.init(500, 250, 'Alert');
			FFJS.Dialog.msg_dialog(msgD);
		}else{
			var error = new Array();
			var err_html = '';
			var id = 0;

			if (response.responseText != undefined){
				var text = response.responseText;
			}else{
				var text = response;
			}

			if ($(text).find('error').length > 0) {
				error = $(text).find('error');		
				for (var r = 0 ; r < error.length ; r++) {								
					err_html += '<p class="error">'+$(error[r]).text()+'</p>';
				}	
				$(msgD).html(err_html);
				FFJS.Dialog.init(500,250, 'Alert');
				FFJS.Dialog.msg_dialog(msgD);
			}
		}		
	},
	
	blank_dialog : function( element_val ) {
		if (element_val != undefined) {
			this.element = element_val;
		}
		
		$(this.element).dialog({
			dialogClass : 'focus_blank',	
			modal : this.modal_val,				
			width : this.width_val,
			height : this.height_val,
			resizable : this.resize_val,
			position : this.pos_val,			
			title : this.title_val,
			buttons: {
				
			}
		})
		.dialog('open');
		
		FFJS.Dialog.reset();
		FFJS.Dialog.fix_bug();		
	},
	
	fix_bug : function() {
		$(this.element).parent().css('width', '');
		$(this.element).attr('style', '');
	},
	
	fix_bug2 : function() {
		$(this.element).parent().css('width', this.width_val);
		$(this.element).parent().css('text-align', 'left');
		$(this.element).attr('style', '');
	},
	
	close : function() {
		$(this.element).dialog('close');
	},
	
	showLoad : function( div_name,url ) {
		FFJS.Dialog.hideLoad();
		FFJS.Dialog.post_name = div_name;
		FFJS.Dialog.post_base = url;
		
		FFJS.Dialog.load_list(div_name);
		
		//NOTE: dialog auto positioning
		var container = $('#list_data_'+div_name);
		var pos = container.offset();
		
		var x = pos.left+100;
		var y = pos.top + container.height()+20;
		this.pos_val = [x, y];
		this.width_val = $('.box_right').width() + $('.box_left').width() - x - 20;
		this.height_val = 'auto'; //$(document).height()-y;
		
		//alert(x+' '+y+' '+w+' '+h);
		$('#table-loader').dialog({
			title : 'Focus CMS',
			width: this.width_val,
			minWidth: 700,
			height: this.height_val,
			minHeight: 200,
			position: this.pos_val,
			close: function(event, ui) { 
				FFJS.Dialog.clear_load_list();
				$(this).dialog('destroy');
			}
		});
	},
	
	hideLoad : function() {
		$('#table-loader').dialog('close');
		FFJS.Dialog.clear_load_list();
		$('div.img_selector_parent').attr('style', '');	
	},
	
	load_list : function( div_name ) {	
		$('#load_list').load(
			FFJS.CMS.url_root+FFJS.Dialog.post_base	,
			function(response, status, xhr) {
				if (status == "error") {
					var msg = "<p class='error'> Sorry ! ";
					$(this).parent().find("div.error").html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");
				}
			}			
		);
	},
	
	clear_load_list : function( div_name ) {	
		//$('#load_list').html('');
		$('#load_list').empty();
	},
	
	update_field_value : function(filename, obj, type) {
		//c_value = c_value.replace(new RegExp(old_value,''),'');  for record
		var post_name = FFJS.Dialog.post_name;			
		var tar_obj = $('#list_data_'+post_name);
		var cnt_for_save = tar_obj.attr("value");
	
		var used = 'msg_ok';
		//var ids = tar_obj.find(':input[name='+post_name+']');
		var ids = tar_obj.find('div.focuscms-'+type+'-holder input');

		var row_id = '';
		switch(type){
			case 'image':
				row_id = $(obj).parent().attr('name');
				break;
			case 'file':	
				row_id = $(obj).attr('name');			
				break;
			case 'record':
				var row_id = $(obj).parent().parent().attr('id');
				if(isNaN(row_id)){			
					row_id = FFJS.CMS.TreeTable.getIdOfClass($(obj).parent().parent());
				}				
				break;		
			// case 'category':
			// case 'access':		
				// row_id = FFJS.CMS.TreeTable.getIdOfClass($(obj).parent().parent());				
				// break;
		}	
			

		if(cnt_for_save!=0  && ids.length >= cnt_for_save ){
			used = 'msg_replaced';			
		}					

		if ( ids.length != 0 ) {		
			ids.each(function(){
				if(row_id == $(this).attr("value")){
					used = 'msg_used';
					//break;
				}
			});

			if (used == 'msg_ok') {				
				FFJS.Dialog.prepend(post_name, obj, filename,row_id, type);				
			}else if( used == 'msg_replaced'){
				$('#msgDialog').html('<p>Enough items. Please delete old one !</p>');			
				FFJS.Dialog.init(500, 200, 'Alert');
				FFJS.Dialog.msg_dialog('#msgDialog')				
			}
			else {
				$('#msgDialog').html('<p class="message">'+filename+' </p>Item Used Already');			
				FFJS.Dialog.init(500, 200, 'Alert');
				FFJS.Dialog.msg_dialog('#msgDialog')	
			}
		}else {
			FFJS.Dialog.prepend(post_name, obj, filename,row_id, type);
		}
		
		if(cnt_for_save==1){FFJS.Dialog.hideLoad();}
	},
	
	update_field_value_img : function(filename, obj) {
		FFJS.Dialog.update_field_value(filename, obj ,'image');	
	},
	
	update_field_value_file : function(filename, obj) {
		FFJS.Dialog.update_field_value(filename, obj ,'file');	
	},
	
	update_field_value_record : function(filename, obj) {
			FFJS.Dialog.update_field_value(filename, obj ,'record');	
	},
	
	prepend : function(post_name, obj, filename,row_id, type) {
		var code = '';
		
		code += '<div class="focuscms-'+type+'-holder">';
		
		code+= '<a class="btn picker_delete">Delete </a>';
		if(type == 'image'){
			code += '<img width="100" height="100" src="'+$(obj).attr('src')+'"/>';
			
		}
		//code += '<input type="checkbox" style="display:none;" name="'+post_name+'_del[]" value="'+filename+'"/>';
		if(type != 'image'){
			code += '<span id="filename-'+post_name+'">'+filename+'</span>';			
		}		
		code += '<input type="hidden" name="'+post_name+'[]" value="'+row_id+'"/>';
		code += '</div>';
		
		$('#list_data_'+post_name).prepend(code);
		$('#list_data_'+post_name+'>.focuscms-'+type+'-holder:first').trigger('mouseenter');
	},
	
	prepend_img : function(post_name, obj, filename) {
		FFJS.Dialog.prepend(post_name, obj, filename, 'image');
	},
	
	prepend_file : function(post_name, obj, filename) {
		FFJS.Dialog.prepend(post_name, obj, filename, 'file');
	},
	
	prepend_record : function(post_name, obj, filename) {
		FFJS.Dialog.prepend(post_name, obj, filename, 'record');
	}

};


FFJS.CMS['Form'] = {
	setting: {	
	},
	div_id : null,
	
	init: function( module_param) {	
	
		if( module_param.selector ==undefined ){
			div_id = FFJS.CMS.div_id;
			this.div_id = div_id;
		}else{
			div_id = module_param.selector;
			this.div_id = module_param.selector;
		}

		setting = module_param.setting;
		if( setting.sub_form_id == undefined ){
			setting['sub_form_id'] = 'FocusCMS_ContentForm'+'_'+div_id;
			setting['del_form_id'] = 'FocusCMS_DeleteForm'+'_'+div_id;
			setting['log_form_id'] = 'FocusCMS_LogForm'+'_'+div_id;			
		}
		
		if( setting.current_div == undefined ){
			setting['current_div'] = '#content'+div_id;
			setting['next_div'] = '#content_next'+div_id;
			//setting['module_name'] = FFJS.CMS.page_section;
		}

		FFJS.CMS.Form.setting[div_id] = setting;	
		//console.debug(FFJS.CMS.Form.setting[div_id]);
		var nextDiv = $(FFJS.CMS.Form.setting[div_id]['next_div']);
		var formId = $('#'+FFJS.CMS.Form.setting[div_id]['sub_form_id']);
		
		formId.delegate('a.submit_button','click', function() {
			FFJS.CMS.Form.Submit(FFJS.CMS.Form.div_id);
		});	
		
		formId.delegate('a.reset_button','click', function() {		
			FFJS.CMS.Form.Reset(FFJS.CMS.Form.div_id);
		});	
		
		formId.delegate('a.delete_button','click', function() {				
			FFJS.CMS.Form.Delete(FFJS.CMS.Form.div_id);
		});	
		
		formId.delegate('a.sync_button', 'click', function() {
			FFJS.CMS.Form.Sync(FFJS.CMS.Form.div_id);
		});
		
		formId.delegate('a.picker_delete','click', function() {	
			var holder = $(this).parent();
			holder.remove();
		});	
		
				
		formId.delegate('div.focuscms-image-holder, div.focuscms-file-holder, div.focuscms-record-holder','mouseover', function() {	
			var $this = $(this);
			if($this.hasClass("ui-draggable")){
				return;
			}
			$this.parent().find('div.focuscms-image-holder, div.focuscms-file-holder, div.focuscms-record-holder').trigger('mouseenter');
		});
		
		formId.delegate('div.focuscms-image-holder, div.focuscms-file-holder, div.focuscms-record-holder','mouseenter', function() {	
			var $this = $(this);
			if($this.hasClass("ui-draggable")){
				return;
			}
			
			if(!$this.is(':data(draggable)')){			
				$this.draggable({
				  helper: "clone",
				  opacity: .75,
				  refreshPositions: true, // Performance?
				  revert: "invalid",
				  revertDuration: 300,
				  scroll: true,
					  start:function(e,ui){},        
					  drag:function(e,ui){},        
					  stop:function(e,ui){} 
				});

				$this.droppable({
					accept: ".focuscms-image-holder, .focuscms-file-holder, .focuscms-record-holder",
					drop: function(e, ui) {					
						var drag_div = $($(ui.draggable)[0]);
						if(drag_div.parent().attr("id") == $(this).parent().attr("id")){
							$(this).before(drag_div);
						}
					
						drag_div = null;
					},
					hoverClass: "accept",
					over: function(e, ui) {
					
					}
				});	
			}
		});	
		
	
		//FFJS.CMS.Form.setDraggable('#'+FFJS.CMS.Form.setting[div_id]['sub_form_id']);
		//FFJS.CMS.Form.setDroppable('#'+FFJS.CMS.Form.setting[div_id]['sub_form_id']);

		if ( nextDiv.data( 'Form' ) === true ) {	
			nextDiv = null;
			formId = null;
			return;
		}else{	
			nextDiv.data('Form', true );
		}

		nextDiv.delegate('div.back_panel>a.btn_back','click', function() {
			//var div_id = FFJS.CMS.Form.div_id;
			var div_id = $(this).parents(".form").attr("name");
			FFJS.Div.switch_div(div_id,FFJS.CMS.Form.setting[div_id]['next_div'],FFJS.CMS.Form.setting[div_id]['current_div']);
			$(FFJS.CMS.Form.setting[div_id]['next_div']).empty();
			$('div.cke_dialog_background_cover').remove();
			$('div.file-uploader').remove();
			$('div.table-loader').remove();
			FFJS.ContentList.reload(div_id);
		});				
		
		nextDiv = null;
		formId = null;
	},	
	
	// setDroppable: function(form_id){
		// $(form_id+" a.picker_delete").each(function() {
			// $(this).parent().droppable({
				// accept: ".focuscms-image-holder, .focuscms-file-holder, .focuscms-record-holder",
				// drop: function(e, ui) { 
					// var drag_div = $($(ui.draggable)[0]);
					// if(drag_div.parent().attr("id") == $(this).parent().attr("id")){
						// $(this).before(drag_div);
					// }
				
					// drag_div = null;
				// },
				// hoverClass: "accept",
				// over: function(e, ui) {
				
				// }
			// });
		// });
	// },
	
	// setDraggable: function(form_id){	
		// var dragList = $(form_id+" a.picker_delete").parent();
		// dragList.draggable({
		  // helper: "clone",
		  // opacity: .75,
		  // refreshPositions: true, 
		  // revert: "invalid",
		  // revertDuration: 300,
		  // scroll: true,
			  // start:function(e,ui){},        
			  // drag:function(e,ui){},        
			  // stop:function(e,ui){} 
		// });
		// dragList = null;
	// },

	Sync : function(div_id) {

		FFJS.CMS.load_page('#msgDialog','module/sync', 'sync/'+FFJS.CMS.Form.setting[div_id]['module_name']+'/'+FFJS.CMS.Form.setting[div_id]['row_id'],
			function(response, status, xhr) {							
				if (status == "error") {
					FFJS.Dialog.errorHandler(response, status, xhr);
				}else{						
					var msg = "<p class='message'> Sync Success! ";
					$('#dialog').html(msg + response + "</p>");
				}							
			}
		);	
	},
	
	Reset : function(div_id) {	
		if( div_id == undefined )
		{
			div_id = FFJS.CMS.div_id;
		}	
		$('#'+FFJS.CMS.Form.setting[div_id].sub_form_id).find(':input:not(:button,[readonly=True])').val('');						
	},
	
	Submit : function(div_id,call_back_func) {	
		if ($('#msgDialog'+div_id).length > 0) { 
			var msgD = '#msgDialog'+div_id;
		}else{
			var msgD = '#msgDialog';
		}
		if( div_id == undefined )
		{
			div_id = this.div_id;//FFJS.CMS.div_id;
		}
	
		var options = {
			ajax : {				
				mode : 'post',				
				post_to : FFJS.url_root+'module/'+FFJS.CMS.Form.setting[div_id]['module_name']+'/save/'+FFJS.CMS.Form.setting[div_id]['row_id']+'/'+div_id,				
				errorHandler : function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);} ,
				call_back : function(data) {
					FFJS.Dialog.errorHandler(data);	
					var id = $(data).find('last_id').text();					
									
					//$(this).log(0,this);
					var btn_obj = {							
						'Back To List' : function() {		
							$(this).dialog('close');						
							if( typeof(FFJS.ContentList.setting[div_id]) != "undefined"){								
								$(FFJS.CMS.Form.setting[div_id]['next_div']).find('div.back_panel>a.btn_back').trigger( 'click' );
								//FFJS.Div.switch_div(div_id,FFJS.CMS.Form.setting[div_id].next_div,FFJS.CMS.Form.setting[div_id].current_div);
								//FFJS.ContentList.reload(div_id);
							};
							//$(this).dialog('close');
						},						
						'View Saved Record' : function() {
							$(FFJS.CMS.Form.setting[div_id].next_div).load(							
								FFJS.CMS.url_root+'module/'+FFJS.CMS.Form.setting[div_id].module_name+'/edit/'+id+'/'+div_id
							);
							$(this).dialog('close');
						}
					};
					
					if(id > 0){			
						$(msgD).html('<p>Record [ '+id+' ] Saved<br/>Please Select Your Action</p>');
						FFJS.Dialog.init(600, 400, 'Record Saved');
						FFJS.Dialog.msg_dialog(msgD, btn_obj);	
					}
	
				}
			}
		};
		
		if ((call_back_func != undefined)) {
			options.ajax['call_back'] = call_back_func;
		}

		FormHandler.init(FFJS.CMS.Form.setting[div_id].form_elements, options);
		FormHandler.checkForm(FFJS.CMS.Form.setting[div_id].sub_form_id);
		
	},
	
	Delete : function(div_id,id) {	
		var msgD = '#msgDialog';	
		$(msgD).html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>');	
		
		if( div_id == undefined )
		{
			div_id = this.div_id;
		}
		if( id == undefined )
		{
			id = FFJS.CMS.Form.setting[div_id]['row_id'];
		}
		var btn_obj = {
			'Cancel' : function() {
				$(this).dialog('close');
			},
			'Delete' : function() {
				var options = {
					ajax : {				
						mode : 'post',
						load_target : '#ContentList'+FFJS.CMS.Form.setting[div_id].module_name+div_id+' tbody',
						post_to : FFJS.url_root+'module/'+FFJS.CMS.Form.setting[div_id]['module_name']+'/delete/'+id+'/'+div_id,
						errorHandler :  function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);} ,	
						call_back : function(data) {						
							FFJS.Dialog.errorHandler(data);
							var id = $(data).find('last_id').text();																		
							var btn_obj = {
								'Back To List' : function() {
									FFJS.Div.switch_div(div_id,FFJS.CMS.Form.setting[div_id].next_div,FFJS.CMS.Form.setting[div_id].current_div);
									FFJS.ContentList.reload(div_id);
									$(this).dialog('close');
								},
								
								'View Saved Record' : function() {				
									$(this).dialog('close');
								}
							};		
									
							if(id > 0){						
								$(msgD).html('Record [ '+id+' ] Deleted ');
								FFJS.Dialog.init(600, 400, 'Message');
								FFJS.Dialog.msg_dialog(msgD, btn_obj);	
							}										
						}	
					}
				};		
				
				FormHandler.init({}, options);
				$('#'+FFJS.CMS.Form.setting[div_id].del_form_id).find('input[name="id"]').val(id);
				FormHandler.checkForm(FFJS.CMS.Form.setting[div_id].del_form_id);		
			}
		};
		
		FFJS.Dialog.init(400, 300, 'Confirm Delete');
		FFJS.Dialog.msg_dialog(msgD, btn_obj);

	},
	
	DeleteMulti : function(div_id,module_name,ids) {	
		if ($('#msgDialog'+div_id).length > 0) { 
			var msgD = '#msgDialog'+div_id;
		}else{
			var msgD = '#msgDialog';
		}
		var cnt = ids.length;
		$.each (ids,function(key,id){	
			cnt--;
			if(id){					
				var options = {
					ajax : {				
						mode : 'post',
						post_to : FFJS.url_root+'module/'+module_name+'/delete/'+id+'/'+div_id,
						load_target : FFJS.ContentList.setting[div_id].target+' tbody',
						errorHandler : function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);} 
					}
				};					
				FormHandler.init({}, options);	
				$('#DeleteForm_'+div_id).find('input[name="id"]').val(id);			
				FormHandler.checkForm('DeleteForm_'+div_id);
			}
		});		
				
		 setTimeout("FFJS.ContentList.reload(div_id);	",500);	
	},
	
	DeleteOne : function(div_id,module_name,id) {	
		if ($('#msgDialog'+div_id).length > 0) { 
			var msgD = '#msgDialog'+div_id;
		}else{
			var msgD = '#msgDialog';
		}
		if(id){					
			var options = {
				ajax : {				
					mode : 'post',
					post_to : FFJS.url_root+'module/'+module_name+'/delete/'+id+'/'+div_id,
					load_target : FFJS.ContentList.setting[div_id].target+' tbody',
					errorHandler :	 function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);FFJS.ContentList.reload(div_id);} ,	
					call_back:
						function(data){
							FFJS.Dialog.errorHandler(data);
							var id = $(data).find('last_id').text();	
							if(id > 0){						
								$(msgD).html('Record [ '+id+' ] Deleted ');
								FFJS.Dialog.init(500, 200, 'Message');
								FFJS.Dialog.msg_dialog(msgD);	
								FFJS.ContentList.reload(div_id);
							}						
						}										
				}
			};					
			FormHandler.init({}, options);	
			$('#DeleteForm_'+div_id).find('input[name="id"]').val(id);			
			FormHandler.checkForm('DeleteForm_'+div_id);
		}	
	}	
};

FFJS['SearchUI'] = {
	setting: {	
	},
			// arr_key : new Array('S', 'F', 'O', 'P'),
			// div_target : '#div_advance_search'+selector,
			// form_id : '#focuscms_search'+selector,
			// search_list: {
				// 'S': null,
				// 'F': null,
				// 'O': null,
				// 'P': null
			// },
	init: function( module_param ){
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};
		if( module_param.setting.arr_key==undefined )
		{
			module_param.setting['arr_key'] = new Array('S', 'F', 'O', 'P');
		}
		if( module_param.setting.search_list==undefined )
		{
			module_param.setting['search_list'] = {
				'S': null,
				'F': null,
				'O': null,
				'P': null
			};
		}
	//$(this).log(0,selector);		
		FFJS.SearchUI.setting[module_param.selector] = module_param.setting;
		var key = FFJS.SearchUI.setting[module_param.selector].arr_key;	
		for (var i = 0 ; i < key.length ; i++) {
			FFJS.SearchUI.setting[module_param.selector].search_list[key[i]] = '';
		};
		
		var simple_search = $('#focuscms_simplesearch'+div_id);
		var ad_search = $('#focuscms_search'+div_id);
		
		if ( simple_search.data( 'SearchUI' ) === true ) {		
			simple_search = null;
			return;
		}else{	
			simple_search.data('SearchUI', true );
		}		
		
		simple_search.delegate('input[type="text"]',{
			'focus':function(){ 
						if ($(this).hasClass('hint')){ 
						   $(this).removeClass('hint').val(''); 
						}
					}			
			,
			'blur':function(){
					  if($(this).val() == ''){
						$(this).addClass('hint').val($(this).attr('title'));
					  } 
					}			
		});

		//$('a.bt_search').unbind('click').bind('click', function() {	
		simple_search.delegate('a.bt_search','click', function() {					
			FFJS.SearchUI.simple_search(div_id);
		});	
		
		simple_search.keyup(function(e) {		
			if(e.keyCode == 13) {
				FFJS.SearchUI.simple_search(div_id);
				return false;
			}
		});
		
		ad_search.keyup(function(e) {		
			if(e.keyCode == 13) {
				FFJS.SearchUI.run(div_id,'filter');
				return false;
			}
		});
		
		//$('a.search_button').unbind('click').bind('click', function() {		
		ad_search.delegate('a.search_button','click', function() {			
			FFJS.SearchUI.run(div_id,'filter');
		});	
		
		//$('a.reset_button').unbind('click').bind('click', function() {	
		ad_search.delegate('a.reset_button','click', function() {				
			FFJS.SearchUI.run(div_id);
		});	
		simple_search = null;
		ad_search = null;
	},	
	
	run : function(selector, mode) {	
		var url = '';
		if (mode == "filter"){
			FFJS.SearchUI.handle_filter(selector);
		}else{
			FFJS.SearchUI.handle_reset(selector);
		}
		FFJS.ContentList.search( selector,FFJS.SearchUI.setting[selector].search_list );		
	},
	
	simple_search : function(selector) {
		var keywords = FFJS.SearchUI.prepare_keywords(selector,'simple_keywords');		

		FFJS.SearchUI.setting[selector].search_list['S'] = keywords;
		FFJS.ContentList.search( selector,FFJS.SearchUI.setting[selector].search_list );
	},
	
	prepare_keywords : function(selector,obj_name) {			
		var keywords = '';
		
		if (obj_name.indexOf("simple") == -1 ) {
			var obj = $(FFJS.SearchUI.setting[selector].form_id+' input[name='+obj_name+']');		
		}else{
			var obj = $(FFJS.SearchUI.setting[selector].form_id.replace("search","simplesearch")+' input[name='+obj_name+']');	
		}
		if (obj.val() != '') {
			keywords = obj.val().replace(/\s/g, '-');				
		}		
		return keywords;
	},
	
	handle_filter : function(selector) {
		// For Search Keywords
		var keywords = FFJS.SearchUI.prepare_keywords(selector,'keywords');
		// For Filtering Words
		var filter_obj = $(FFJS.SearchUI.setting[selector].form_id+' :input.filter');
		var str_filter = '';
		var str_tmp = null;
		var counter = 1;
		
		for (var f = 0 ; f < filter_obj.length ; f++) {
			var box = filter_obj.eq(f);
			
			if (box.val() != '') {
				str_tmp = box.attr('name').split('_');
				str_filter += str_tmp[1]+'-'+box.val()
				
				if (counter < filter_obj.length) {
					str_filter += '/';
				}				
				counter++;
			}
		}
		
		FFJS.SearchUI.setting[selector].search_list['S'] = keywords;
		FFJS.SearchUI.setting[selector].search_list['F'] = str_filter;
	},
	
	handle_reset : function(selector) {		
		$(FFJS.SearchUI.setting[selector].form_id).find(':input:not(:button)').val('');			
		$.each (FFJS.SearchUI.setting[selector].search_list,function(key,value){			
			FFJS.SearchUI.setting[selector].search_list[key] = '';		
		});		
	}
};

FFJS.CMS['Button'] = {
	setting: {	
	},
	
	init: function( module_param) {		
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};

		this.setting[div_id] = module_param.setting;
		var currentDiv = $(this.setting[div_id].current_div);
		
		if ( currentDiv.data( 'Button' ) === true ) {		
			currentDiv = null;
			return;
		}else{	
			currentDiv.data('Button', true );
		}
		
		currentDiv.delegate('div.addbutton>a.add_button','click', function() {				
			FFJS.CMS.load_page(FFJS.CMS.Button.setting[div_id].next_div,'module/'+FFJS.CMS.Button.setting[div_id].module_name,'add/0/'+div_id,
				function(response, status, xhr) {							
					if (status == "error") {
						//var msg = "<p class='error'> Sorry ! ";
						//$('#dialog').html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");	
						FFJS.Dialog.errorHandler(response, status, xhr);
					}else{						
						FFJS.Div.switch_div(div_id,FFJS.CMS.Button.setting[div_id].current_div,FFJS.CMS.Button.setting[div_id].next_div);
						setTimeout("FFJS.Dialog.close();", 200);												
					}
				}			
			);
		});	
		
		currentDiv = null;		
	},
	
	switch_upload_image: function(current_div,module_name,task){
		//var current_div = $(currentDiv);
		
		if(current_div.find('.ImageList').hasClass("ImageList")){
			current_div.find('div.addbutton>span.pic_on').show();
			current_div.find('div.addbutton>span.row_on').hide();
		}else{
			current_div.find('div.addbutton>span.pic_on').hide();
			current_div.find('div.addbutton>span.row_on').show();
		};

		current_div.delegate('div.addbutton>span.pic_on>a.row_on','click', function() {
			var target = current_div.parent()[0];
			//$(target).unbind().empty();
			module_name = FFJS.CMS.Button.setting[div_id].switch_module.upload_image[1];
			FFJS.CMS.load_page(target,'module/'+module_name,'list/',
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
			target = null;
		});
		
		current_div.delegate('div.addbutton>span.row_on>a.pic_on','click', function() {
			module_name = FFJS.CMS.Button.setting[div_id].switch_module.upload_image[2];	
			var target = current_div.parent()[0];
			FFJS.CMS.load_page(target,'module/'+module_name,task+'/',
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
			target = null;
		});
	},
	switch_category: function(current_div,module_name,task){
		if(current_div.find('.simple').hasClass("simple")){
			current_div.find('div.addbutton>span.pic_on').show();
			current_div.find('div.addbutton>span.row_on').hide();
		}else{
			current_div.find('div.addbutton>span.pic_on').hide();
			current_div.find('div.addbutton>span.row_on').show();	
		};

		current_div.delegate('div.addbutton>span.pic_on>a.row_on','click', function() {
			var target = current_div.parent()[0];
			FFJS.CMS.load_page(target,'module/'+module_name,'list/',
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
			target = null;
		});
		
		current_div.delegate('div.addbutton>span.row_on>a.pic_on','click', function() {
			var target = current_div.parent()[0];
			FFJS.CMS.load_page(target,'module/'+module_name,'simple/',
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
			target = null;
		});
	}
};

FFJS.CMS['Page'] = {
	setting: {	
	},
	
	init: function( module_param) {		
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};

		FFJS.CMS.Page.setting[div_id] = module_param.setting;
		var current_table = $(FFJS.CMS.Page.setting[div_id].currentTable+'>tbody');

		if ( current_table.data( 'Page' ) === true ) {		
			current_table = null;
			return;
		}else{	
			current_table.data('Page', true );
		}
		
		current_table.delegate('select[name="pagesize"]','change',function(){
			var pagesize = $(FFJS.CMS.Page.setting[div_id].currentTable+'>tbody').find('select[name="pagesize"] option:selected').val();
			var pagestr = '1-'+ pagesize;
			FFJS.ContentList.run(div_id,'page', pagestr);	
			pagesize = null;
			pagestr = null;					
		});
		
		current_table.delegate('a.page','click', function() {
			var pagesize = $(FFJS.CMS.Page.setting[div_id].currentTable+'>tbody').find('select[name="pagesize"] option:selected').val();
			if($(this).attr("name") != 0){
				var pagestr = $(this).attr("name")+'-'+pagesize;
				FFJS.ContentList.run(div_id,'page', pagestr);
			}
			pagesize = null;
			pagestr = null;			
		});
		
		current_table.delegate('a.jumpto','click', function() {
			var pagesize = $(FFJS.CMS.Page.setting[div_id].currentTable+'>tbody').find('select[name="pagesize"] option:selected').val();
			var jumpto = $(FFJS.CMS.Page.setting[div_id].currentTable+'>tbody').find('input#jumpto').val();
			if(jumpto != 0){
				var pagestr = jumpto+'-'+pagesize;
				FFJS.ContentList.run(div_id,'page', pagestr);
			}	
			pagesize = null;
			jumpto = null;
			pagestr = null;
			
		});	
		
		current_table = null;
	}	
};

FFJS.CMS['ToolTip'] = {
	setting: {	
	},
	
	init: function( module_param) {		
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};
		if( module_param.setting.xOffset==undefined )
		{	
			xOffset = 10;
			yOffset = 20;	
			module_param.setting.xOffset = 10;
			module_param.setting.yOffset = 20;
		}else{
			xOffset = module_param.setting.xOffset;
			yOffset = module_param.setting.yOffset;	
		}	;
		FFJS.CMS.ToolTip.setting[div_id] = module_param.setting;
		
		if ( $('body').data( 'ToolTip' ) === true ) {		
			//current_table = null;
			return;
		}else{	
			$('body').data('ToolTip', true );
		}
		// CONFIG 		
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
		// END CONFIG 			

		$('body').delegate('a.tooltip',{
			mouseover : function(e) {
				//e.preventDefault();
				$("#tooltip").detach();				
				if($(this).attr('title')){
					$(this).data("title",$(this).attr('title'))
					$(this).attr('title','');
				}									
				$("body").append("<p id='tooltip'>"+ $(this).data("title") +"</p>");
				
				w = $("#tooltip").width();
				h = $("#tooltip").height();
				if ((e.pageX + yOffset + w)>= document.body.clientWidth){				
                     e.pageX = e.pageX-w;	
					 e.pageY = e.pageY + 30;
					
				}
				if ( (e.pageY - xOffset + h)>=document.body.clientHeight)
                     e.pageY = e.pageY-h;
				
				$("#tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");
				
			},
			mouseout : function(){
				$(this).attr('title',$(this).data("title"));				
				$("#tooltip").detach();
			},
			mousemove : function(e){
				w = $("#tooltip").width();
				h = $("#tooltip").height();
				if ((e.pageX + yOffset + w)>= document.body.clientWidth){				
                     e.pageX = e.pageX-w;
					 e.pageY = e.pageY + 30;
					
				}
				if ( (e.pageY - xOffset + h)>=document.body.clientHeight)
                     e.pageY = e.pageY-h;
				$("#tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px");
			}
		});	

	}	
};

FFJS.CMS['TreeTable'] = {
	setting: {	
	},
	current_tr:null ,
	init: function( module_param) {		
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		};
		FFJS.CMS.TreeTable.setting[div_id] = module_param.setting;
		
		var current_table = $(FFJS.CMS.TreeTable.setting[div_id].currentTable+'>tbody');		
		
		if ( current_table.data( 'TreeTable' ) === true ) {		
			current_table = null;
			return;
		}else{	
			current_table.data('TreeTable', true );
		}
		
		//FFJS.CMS.TreeTable.setDraggable(currentTable);
		//FFJS.CMS.TreeTable.setDroppable(currentTable);
			
	//clone
		//currentList.find('tr.data td a.clone').unbind('click').live('click', function() {	
		current_table.delegate('a.clone','click', function() {		
			var div_id = $(this).parents(".ContentList").attr("name");		
			var parent_tr = $(this).parent().parent().parent().parent();//[0];
			$(FFJS.CMS.TreeTable.setting[div_id].currentTable+'>tbody').find('div.bar_simple_edit').detach();
			
			if(parent_tr.hasClass("clone") || $(FFJS.CMS.TreeTable.setting[div_id].currentTable+'>tbody').find('tr.clone').hasClass("clone") ){
				return FFJS.CMS.TreeTable.checkTask();
			};		
				
			var new_tr = parent_tr.clone();
			var cate_id = new_tr.find('a[name="f_cate_id"]');
			var category_id = new_tr.find('a[name="f_id"]');
			var action_id = new_tr.find('input[name="f_action[]"]');
			var action_id_checked = new_tr.find('input.multi_checkbox');
			var max_cate_id = parent_tr.parent().parent().find('a[name="multi"]');
			category_id.html("0");
			category_id.attr("value",0);
			action_id.attr("value",0);
			action_id_checked.attr("value",0);
			action_id_checked.prop('checked',true);
			max_cate_id.attr("id",parseInt(max_cate_id.attr("id"))+1);
			cate_id.html(max_cate_id.attr("id"));
			cate_id.attr("value",max_cate_id.attr("id"));
			new_tr.attr("id","node-"+cate_id.html());
			new_tr.addClass("child-of-"+parent_tr.attr("id"));
			new_tr.addClass("clone");
			new_tr.addClass("changed");
			
			$(parent_tr).find('a.row_panel').trigger('click.inline-edit');
			new_tr.appendBranchTo(parent_tr[0]);
		
					
			new_tr.find("a.row_panel").attr("name",0);
			new_tr.find("div.bar_row_edit a").attr("name",0);
			FFJS.CMS.InlineEdit.setting[div_id]['row_id'] = 0;
			
			category_id = null;
			action_id = null;
			max_cate_id = null;
			cate_id = null;
			new_tr = null;
			parent_tr = null;
		});	
//cat_delete
		//currentList.find('tr.data td a.cat_delete').unbind('click').live('click', function() {	
		current_table.delegate('a.cat_delete','click', function() {
			var div_id = $(this).parents(".ContentList").attr("name");	
			var module_name = FFJS.CMS.TreeTable.setting[div_id].module_name;
			var parent_tr = $(this).parent().parent().parent().parent();
			
			FFJS.CMS.TreeTable.setCheck(parent_tr[0].id);
			if (confirm('Are you sure to delete these all?')) {					
				var stack=new Array();					
				$(FFJS.CMS.TreeTable.setting[div_id].currentTable+'>tbody').find('input.multi_checkbox').each(function(){
					if($(this).prop('checked')){
						stack.push($(this).attr('value'));
					}
				});
				FFJS.CMS.Form.DeleteMulti(div_id,module_name,stack);
				FFJS.CMS.TreeTable.remove(parent_tr[0].id);
			}else{
				FFJS.CMS.TreeTable.setUnCheck(parent_tr[0].id);			
			}	
			
			stack = null;
			parent_tr = null;
		});	
//cat_up
		//currentList.find('tr.data td a.cat_up').unbind('click').live('click', function() {	
		current_table.delegate('a.cat_up','click', function() {
			var parent_tr = $(this).parent().parent().parent().parent();			
			FFJS.CMS.TreeTable.up(parent_tr);	
			parent_tr = null;
		});	
		
//permission_list
		//currentList.find('tr.data td a.cat_down').unbind('click').live('click', function() {	
		current_table.delegate('a.listview','click', function() {
			$(this).parent().parent().parent().find(".listed").removeClass('listed');
			$(this).parent().parent().addClass('listed');
			var div_id = $('#focuscms_main').find('div.right_layout>div.form').attr("name");

			var rowid = FFJS.CMS.TreeTable.getIdOfClass($(this).parent().parent());
			FFJS.ContentList.setting[div_id].search_list['F'] = '1-'+rowid;
			//alert(rowid);
			FFJS.ContentList.reload(div_id);
		});	
//user_add		
		current_table.delegate('a.user_add','click', function() {
			//$main.find( settings.form ).find( settings.save ).trigger( 'click.column-edit' )
			$(this).parent().parent().parent().parent().parent().find(".listed").removeClass('listed');
			$(this).parent().parent().parent().parent().addClass('listed');
			
			var div_id = $('#focuscms_main').find('div.right_layout>div.form').attr("name");
			
			var current_div = '#content'+div_id;
			var next_div = '#content_next'+div_id;
			var module = 'user2group';
			$('div.table-loader').remove();
			
			FFJS.Div.switch_div(div_id,current_div,next_div);
			FFJS.CMS.load_page(next_div,'module/'+module,'add/0/'+div_id,
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
		});	
//group_update		
		current_table.delegate('a.group_update','click', function() {			
			var div_id = $('#focuscms_main').find('div.right_layout>div.form').attr("name");			
			var current_div = '#content'+div_id;
			var next_div = '#content_next'+div_id;
			var module = 'group';
			//FFJS.Div.switch_div(div_id,current_div,next_div);
			FFJS.CMS.load_page(next_div,'module/'+module,'grp_upd/'+div_id,
				function(response, status, xhr) {							
					if (status == "error") {
						//var msg = "<p class='error'> Sorry ! ";
						//$('#dialog').html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");
						FFJS.Dialog.errorHandler(response, status, xhr);
					}else{						
						//FFJS.Div.switch_div(div_id,current_div,next_div);
						var msg = "<p class='message'> Success ! ";
						$('#dialog').html(msg + response + "</p>");
						//setTimeout("FFJS.Dialog.close();", 200);
					
					}							
				}
			);	
		});		
//permission_add		
		current_table.delegate('a.permission_add','click', function() {
			//$main.find( settings.form ).find( settings.save ).trigger( 'click.column-edit' )
			$(this).parent().parent().parent().parent().parent().find(".listed").removeClass('listed');
			$(this).parent().parent().parent().parent().addClass('listed');
			
			var div_id = $('#focuscms_main').find('div.right_layout>div.form').attr("name");
			
			var current_div = '#content'+div_id;
			var next_div = '#content_next'+div_id;
			var selector = 'permission2role';
			$('div.table-loader').remove();
			
			FFJS.Div.switch_div(div_id,current_div,next_div);
			FFJS.CMS.load_page(next_div,'module/'+selector,'add/0/'+div_id,
				function(response, status, xhr) {	
					if (status == "error") 	FFJS.Dialog.errorHandler(response, status, xhr);
					else setTimeout("FFJS.Dialog.close();", 200);
				});
		});	
		
//permission_file		
		current_table.delegate('a.permission_file','click', function() {			
			var div_id = $('#focuscms_main').find('div.right_layout>div.form').attr("name");			
			var current_div = '#content'+div_id;
			var next_div = '#content_next'+div_id;
			var selector = 'permission2role';
			//FFJS.Div.switch_div(div_id,current_div,next_div);
			FFJS.CMS.load_page(next_div,'module/'+selector,'file/'+div_id,
				function(response, status, xhr) {							
					if (status == "error") {
						//var msg = "<p class='error'> Sorry ! ";
						//$('#dialog').html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");	
						FFJS.Dialog.errorHandler(response, status, xhr);	
					}else{						
						//FFJS.Div.switch_div(div_id,current_div,next_div);
						var msg = "<p class='message'> Success ! ";
						$('#dialog').html(msg + response + "</p>");
						//setTimeout("FFJS.Dialog.close();", 200);
					
					}							
				}
			);	
		});	
		//current_div = null;
		current_table = null;
	},
	
	setDroppable: function(tableid){
			// Configure droppable rows
		$(tableid+" .folder").each(function() {
			$(this).parents(tableid+" tr").droppable({
				accept: ".file, .folder",
				drop: function(e, ui) { 
					var drag_tr = $($(ui.draggable).parents("tr")[0]);
					drag_tr.appendBranchTo(this);
					drag_tr = null;
				},
				hoverClass: "accept",
				over: function(e, ui) {
					  // Make the droppable branch expand when a draggable node is moved over it.
					if(this.id != $(ui.draggable.parents("tr")[0]).id && !$(this).is(".expanded")) {
						$(this).expand();
					}
				}
			});
		});
	},
	
	setDraggable: function(tableid){	
		// Configure draggable nodes
		var dragList = $(tableid+" .file, "+tableid+" .folder");
		dragList.draggable({
		  helper: "clone",
		  opacity: .75,
		  refreshPositions: true, // Performance?
		  revert: "invalid",
		  revertDuration: 300,
		  scroll: true,
			  start:function(e,ui){},        
			  drag:function(e,ui){},        
			  stop:function(e,ui){} 
		});
		dragList = null;
	},
	
	removeChild:function (trid){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){
			 var id = item.id;
			 $(item).remove();
			 FFJS.CMS.TreeTable.removeChild(item.id)
		});
	},
	
	remove:function (currentRow){
		$("#"+currentRow).remove();
		FFJS.CMS.TreeTable.removeChild(currentRow);
	},
	
	setUnCheck:function (currentRow){
		var action_id_checked = $("#"+currentRow).find('input.multi_checkbox');
		action_id_checked.prop('checked',false);
		$("#"+currentRow).removeClass("checked");
		$("#"+currentRow).removeClass("changed");
		FFJS.CMS.TreeTable.setUnCheckChild(currentRow);
		
	},
		
	setUnCheckChild:function (trid){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){
			var action_id_checked = $(item).find('input.multi_checkbox');
			action_id_checked.prop('checked',false);
			$(item).removeClass("checked");
			$(item).removeClass("changed");
			FFJS.CMS.TreeTable.setUnCheckChild(item.id)
		});
	},
	
	setCheck:function (currentRow){
		var action_id_checked = $("#"+currentRow).find('input.multi_checkbox');
		action_id_checked.prop('checked',true);
		$("#"+currentRow).addClass("checked");
		$("#"+currentRow).addClass("changed");
		FFJS.CMS.TreeTable.setCheckChild(currentRow);
		
	},
	
	setCheckChild:function (trid){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){
			var id = item.id;
			var action_id_checked = $(item).find('input.multi_checkbox');
			action_id_checked.prop('checked',true);
			$(item).addClass("checked");
			$(item).addClass("changed");
			FFJS.CMS.TreeTable.setCheckChild(item.id)
		});
	},	

	findAndSetAfterChild:function (trid){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){		 
			$(current_tr).after($(item)[0]); 
			current_tr = $(item)[0];
			FFJS.CMS.TreeTable.findAndSetAfterChild(item.id)	;	
		});
	},	
	
	changeParent:function (trid,new_id){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){		 
			$(item).find("a[name=f_cate_father]").attr("value",new_id).html(new_id);
		});
	},	
	
	changePath:function (trid,old_pa,new_pa){
		($("tr").filter(".child-of-"+trid)).each(function(index,item){		 
			var str = $(item).find("a[name=f_cate_path]").attr("value");
			var newstr = str.replace(old_pa,new_pa);
			$(item).find("a[name=f_cate_path]").attr("value",newstr).html(newstr);
			FFJS.CMS.TreeTable.changePath(item.id,old_pa,new_pa)	;	
		});
	},

	up:function (currentRow){	
		current_tr = $(currentRow)[0]; 
		var parent = FFJS.CMS.TreeTable.parentOf(current_tr);
		var brothers = new Array();
		var current_index = 0;
		var current_id = 0;
		var current_path = '';
		var brother_id = 0;
		var brother_path = '';
		var brother_tr = '';

		($(current_tr).parent().find(".child-of-"+$(parent)[0].id)).each(function(index,item){
			brothers[index] = item.id;
			if(item.id == current_tr.id){
				current_index = index;
			};	
		});
		
		brother_tr = '#'+brothers[current_index-1];
		FFJS.CMS.TreeTable.setCheck(current_tr.id);
		FFJS.CMS.TreeTable.setCheck($(brother_tr)[0].id);
		
  		current_path = $(currentRow).find("a[name=f_cate_path]").attr("value");
		current_id = $(currentRow).find("a[name=f_cate_id]").attr("value");		
		brother_path = $(brother_tr).find("a[name=f_cate_path]").attr("value");
		brother_id = $(brother_tr).find("a[name=f_cate_id]").attr("value");
		
		FFJS.CMS.TreeTable.changeParent(current_tr.id,brother_id);
		FFJS.CMS.TreeTable.changeParent($(brother_tr)[0].id,current_id);
		FFJS.CMS.TreeTable.changePath(current_tr.id,current_path,brother_path);
		FFJS.CMS.TreeTable.changePath($(brother_tr)[0].id,brother_path,current_path);
		$(currentRow).find("a[name=f_cate_id]").attr("value",brother_id).html(brother_id);
		$(currentRow).find("a[name=f_cate_path]").attr("value",brother_path).html(brother_path);
 		
		$(brother_tr).find("a[name=f_cate_id]").attr("value",current_id).html(current_id);
		$(brother_tr).find("a[name=f_cate_path]").attr("value",current_path).html(current_path); 

		
		$(brother_tr).before(currentRow);
		FFJS.CMS.TreeTable.findAndSetAfterChild(current_tr.id);
		
		brother_tr = null;
		current_tr = null;
	},

	parentOf :function (node) {
		var classNames = $(node)[0].className.split(' ');
		
		for(key in classNames) {
		  if(classNames[key].match("child-of-")) {
			return $("#" + classNames[key].substring(9));
		  }
		}
	},
	
	getIdOfClass : function (node) {
		var classNames = node[0].className.split(' ');	   
		for(key in classNames) {
			if(classNames[key].match("row-id-")) {
				return classNames[key].substring(7);
			}
		}
	},
	
	checkTask :function () {
		$('#msgDialog').html('<p>Error: Task not finished! Save first Please!</p>');
	
		FFJS.Dialog.init(500, 200, 'Alert');
		FFJS.Dialog.msg_dialog('#msgDialog');
		return false;
	}	
};

FFJS.CMS['ColumnEdit'] = {
	setting: {	
	},
	
	init: function( module_param) {		
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
		}

		var defaults = {
				display: '.display',
				form: '.form',
				save: '.save',
				cancel: '.cancel',
				edit_now: 'edit_now'
			};
		var settings = $.extend(defaults, module_param.setting);
		settings['self'] = FFJS.ContentList.setting[div_id].target;
		settings['module_name'] = FFJS.ContentList.setting[div_id].moduleName;		
		FFJS.CMS.ColumnEdit.setting[div_id] = settings;

		var current_table = $(FFJS.ContentList.setting[div_id].target);
		
		// Make sure the plugin only get initialized once
		if ( current_table.data( 'column-edit' ) === true ) {
			current_table = null;
			return;
		}else{	
			current_table.data('column-edit', true );
		}

		// Prevent sending form submission
		//$form.bind( 'submit.column-edit', function(){
		current_table.delegate( FFJS.CMS.ColumnEdit.setting[div_id].form,'submit.column-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");
			settings =FFJS.CMS.ColumnEdit.setting[div_id];
			$main = $( settings.self );
			$main.find( settings.form ).find( settings.save ).trigger( 'click.column-edit' );
			$main = null;
			settings = null;		
			return false;
		});
		// Save Actions
		//$save.live( 'click.column-edit', function( event ) {
		current_table.delegate( FFJS.CMS.ColumnEdit.setting[div_id].save,'click.column-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");
			FFJS.CMS.ColumnEdit.save(div_id);
			return false;
		});
		
		// Cancel Actions
		//$cancel.live( 'click.column-edit', function(){	
		current_table.delegate( FFJS.CMS.ColumnEdit.setting[div_id].cancel,'click.column-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");		
			FFJS.CMS.ColumnEdit.cancel(div_id);
			return false;
		});	
		current_table.delegate('span.edit_now>input','change.column-edit', function() {
			//alert($(this).val());
			$(this).parent().parent().parent().addClass("changed");
		});

	//column_edit multi_edit
		//current_div.find('a.column_edit').unbind('click.column-edit').live('click.column-edit', function() {	
		current_table.delegate('a.column_edit','click.column-edit', function() {	
			var div_id = $(this).parents(".ContentList").attr("name");
			var current_table1 = $(FFJS.CMS.ColumnEdit.setting[div_id]['self']);
//console.profile('column_edit Measuring time');
			var name = $(this).attr("name");
			var namestr = '';
			
			if(current_table1.find('tr.clone').hasClass("clone") && name != "multi"){
				return FFJS.CMS.TreeTable.checkTask();
			};
			FFJS.CMS.InlineEdit.cancel(div_id);				
		

			if(name == "multi"){
				current_table1.find('div.col_header span.new').each(function(){
					
					namestr +='a[name='+$(this).parent().find("a.col_panel").attr("name")+'],'
				});

				var column = current_table1.find(namestr).parent();
			}else{
				var column = current_table1.find('a[name='+name+']').parent();
			};	
			
			var cnt =0;
			current_table1.find('input.multi_checkbox').each(function(){
				if($(this).prop('checked')){
					cnt++;
				}
			});
			if (cnt == 0){
				current_table1.find('input.multi_checkbox').prop('checked',true);				
			}
			$(column).each(function(){ 				
				if($(this).parent().find('input.multi_checkbox').prop('checked') ){
					$(this).find('span.inline').show().addClass( 'edit_now' ).html('<input class="text" size=5 type="text" value=\''+$(this).find('a').attr("value")+'\' name=\''+$(this).find('a').attr("name")+'[]\' />');
					$(this).find('a').hide().addClass( 'edit_now' );						
				}					
			});	
			var header2 = $(this).parent().parent();
			header2.addClass('edit_now');
			header2.find('div.bar_col_edit').hide();
			header2.find('span.new').show();		
//console.profileEnd();
			namestr = null;
			name = null;
			column = null;
			header2 = null;
			current_table1 = null;
			return false;
		});
	
	//btn_simple_save
		//current_div.find('a.btn_simple_save').unbind('click.column-edit').live('click.column-edit', function() {	
		current_table.delegate('a.btn_simple_save','click.column-edit', function() {
			var div_id = $(this).parents(".ContentList").attr("name");
			//alert("div_id:"+div_id1);
			var current_table1 = $(FFJS.CMS.ColumnEdit.setting[div_id]['self']);
			if(current_table1.find('tr.clone').hasClass("clone") ){
				return FFJS.CMS.TreeTable.checkTask();
			};
			FFJS.CMS.InlineEdit.cancel(div_id);				
		
			var name = $(this).attr("name");
			var cate_name = $(this).parent().attr("name");
			
			if(name == "multi"){
				var column = current_table1.find('a[name=f_cate_tree],a[name=f_id],a[name=f_cate_id],a[name=f_cate_father],a[name=f_cate_depth],a[name=f_cate_path],a[name=f_cate_hasson],a[name='+cate_name+']').parent();
			}else{
				var column = current_table1.find('a[name='+name+']').parent();
			};	
//alert(FFJS.CMS.ColumnEdit.setting[div_id]['self']);			
			var cnt =0;
			current_table1.find('input.multi_checkbox').each(function(){
				if($(this).prop('checked')){
					cnt++;
				}
			});
			if (cnt == 0){
				current_table1.find('input.multi_checkbox').prop('checked',true);				
			}
			$(column).each(function(){ 
//alert($(this).attr("class"));
				if($(this).hasClass("cate_name") && $(this).parent().find('input.multi_checkbox').prop('checked')){
					$(this).find('span.inline').show().addClass( 'edit_now' )
					.html('<input class="text" type="text"   value=\''+$(this).find('a').attr("value")+'\' name=\''+$(this).find('a').attr("name")+'[]\' />');
					$(this).find('a').hide().addClass( 'edit_now' );						
				}else	
				if($(this).parent().parent().find('input.multi_checkbox').prop('checked') ){
					$(this).find('span.inline').addClass( 'edit_now' )
					.html('<input type="hidden" value=\''+$(this).find('a').attr("value")+'\' name=\''+$(this).find('a').attr("name")+'[]\' />');
//this).find('a').hide().addClass( 'edit_now' );						
				}
				
			});		
			
			var header2 = $(this).parent().parent();
			header2.addClass('edit_now');			
			header2.find('div.col_panel').hide();
			header2.find('span.new').show();
			
			name = null;
			column = null;
			header2 = null;
			current_table1 = null;
			return false;
		});	
			
//col_panel
		//current_div.find('a.col_panel').unbind('mouseover.column-edit').live('mouseover.column-edit', function() {		
		current_table.delegate('a.col_panel','mouseover.column-edit', function() {
			var div_id = $(this).parents(".ContentList").attr("name");
			var name = $(this).attr("name");
			//var current_div = FFJS.CMS.ColumnEdit.setting[div_id]['current_div'];
			//NOTE: there's a bug with jQuery and col_edit_wrap CSS class. sort button, if alone, does not disappear;
			//		However, if "position: absolute" is removed from the styles, then everything works. But styling is scrambled
			
			var sort_edit = '<div class="bar_col_edit"><a class="tooltip btn col_sort" title="Sort this Column" name="'+name+'"></a><a class="tooltip btn column_edit" title="Edit this Column" name="'+name+'"></a></div>';
			var sort_only = '<div class="bar_col_edit"><a class="tooltip btn col_sort" title="Sort this Column" name="'+name+'"></a></div>';
			var edit_only = '<div class="bar_col_edit"><a class="tooltip btn column_edit" title="Edit and Save" name="'+name+'"></a></div>';
			$(FFJS.CMS.ColumnEdit.setting[div_id]['self']).find('div.bar_col_edit').detach();
			if($(this).parent().find('span.new').size()==0 ){
				$(this).parent().append(sort_only);
			}else if($(this).parent().find('a[name=multi]').hasClass("col_panel")){
				$(this).parent().append(edit_only);
			}else{
				$(this).parent().append(sort_edit);
			}
			$(this).parent().find('div.bar_col_edit').delay(3000).hide(0);
			
			name = null;
			sort_edit = null;
			sort_only = null;
			edit_only = null;
			return false;
		});	

	//multi_select
		current_table.delegate('input[name=multi_select]','change',function(){
			var div_id = $(this).parents(".ContentList").attr("name");
			$(FFJS.CMS.ColumnEdit.setting[div_id]['self']).find('a.multi_select').trigger('click.column-edit');
		});

		//current_div.find('a.multi_select').unbind('click.column-edit').live('click.column-edit', function() {	
		current_table.delegate('a.multi_select','click.column-edit', function() {
			var div_id = $(this).parents(".ContentList").attr("name");
			var current_table1 = $(FFJS.CMS.ColumnEdit.setting[div_id]['self']);
		   	if($(this).attr("value") == "check"){
				$(this).attr("value","nocheck");
				$(this).html("Unselect All");
				current_table1.find('input[name=multi_select]').trigger('click.column-edit');//prop('checked',true);
				current_table1.find('input.multi_checkbox').prop('checked',true);
			}else{
				$(this).attr("value","check");
				$(this).html("Select All");
				current_table1.find('input[name=multi_select]').trigger('click.column-edit');
				current_table1.find('input.multi_checkbox').prop('checked',false);
			}		

			current_table1 = null;
			return false;	
		});

	//multi_delete
		//current_div.find('a.multi_delete').unbind('click.column-edit').live('click.column-edit', function() {	
		current_table.delegate('a.multi_delete','click.column-edit', function() {
			if (confirm('Are you sure to delete these all?')) {
				var stack=new Array();				
				var div_id = $(this).parents(".ContentList").attr("name");
				//var code4table = $(FFJS.CMS.ColumnEdit.setting[div_id]['self']).parent().parent().find('div.bar_row_edit').hide().detach();
				//$(FFJS.CMS.ColumnEdit.setting[div_id]['self']).parent().parent().append(code4table);
				
				$(FFJS.CMS.ColumnEdit.setting[div_id]['self']).find('input.multi_checkbox').each(function(){
					if($(this).prop('checked')){
						stack.push($(this).attr('value'));
						$(this).parent().parent().parent().remove();
					}
				});
				var module_name = FFJS.CMS.ColumnEdit.setting[div_id]['module_name'];
				FFJS.CMS.Form.DeleteMulti(div_id,module_name,stack);					
			}
			stack = null;
			return false;
		});	

		settings = null;
		current_table = null;		
	},
	
	save: function(div_id){
		if ($('#msgDialog'+div_id).length > 0) { 
			var msgD = '#msgDialog'+div_id;
		}else{
			var msgD = '#msgDialog';
		}
		settings1 =FFJS.CMS.ColumnEdit.setting[div_id];
//console.log(settings1);
		$main = $( settings1.self );
		$form = $main.find( settings1.form );		 
		$display = $main.find( settings1.display );
							
		$main.find('input.multi_checkbox').each(function(){		
		//alert($(this).parent().parent().parent().hasClass("changed"));
			if($(this).parent().parent().parent().hasClass("changed")){
				
			}else{
				$(this).prop('checked',false);
				$(this).parent().parent().parent().addClass("edit_now");
			};
			//if($(this).prop('checked')){
				
			//}
		});
		
	
		FFJS.CMS.InlineEdit.cancel(div_id);
		
		//alert("after cancel");
		
		if($display.parent().hasClass('edit_now')){
			$display.parent().removeClass('edit_now');

			var options = {
				ajax : {				
					mode : 'post',
					post_to : FFJS.url_root+'module/'+FFJS.CMS.ColumnEdit.setting[div_id]['module_name']+'/multi_edit/'+div_id,
					load_target : FFJS.ContentList.setting[div_id].target+' tbody',
					errorHandler :function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);FFJS.CMS.InlineEdit.cancel(div_id);} ,
					call_back: function(data){
						FFJS.Dialog.errorHandler(data);
						var id = $(data).find('last_id').text();	
						if(id > 0){						
							$(msgD).html('Records  Saved ! ');
							FFJS.Dialog.init(500, 200, 'Message');
							FFJS.Dialog.msg_dialog(msgD);	
							FFJS.ContentList.reload(div_id);
						}					
					}
				}
			};
					
			FormHandler.init('', options);
			FormHandler.checkForm('EditForm_'+div_id);	

			$( settings1.self ).find('td.data span.edit_now').hide().html('').removeClass( 'edit_now' );
			$( settings1.self ).find('td.data a.edit_now').show().removeClass( 'edit_now' );
			$form.hide();
			$display.show();			
		}
		
		settings1 = null;
		$main = null;
		$form = null;
		$display = null;
		return false;
	},
	
	cancel: function(div_id){
		settings = FFJS.CMS.ColumnEdit.setting[div_id];
		$main = $( settings.self );
		$form = $main.find( settings.form );		 
		$display = $main.find( settings.display );
		$main.find('td.data span.edit_now').hide().html('').removeClass( 'edit_now' );
		$main.find('td.data a.edit_now').show().removeClass( 'edit_now' );
		$main.find('input.multi_checkbox').prop('checked',false);
		$form.hide();
		$display.show();	
		
		settings = null;
		$main = null;
		$form = null;
		$display = null;
		return false;
	}
};

FFJS.CMS['InlineEdit'] = {
	setting: {	
	},
	div:null,
	
	init: function( module_param) {	
		if( module_param.selector ==undefined )
		{
			div_id = FFJS.CMS.div_id;
			this.div_id = FFJS.CMS.div_id;
		}else{
			div_id = module_param.selector;
			this.div_id = module_param.selector;
		}
		var defaults = {
				display: '.display',
				form: '.form',	
				save: '.save',
				cancel: '.cancel'
			};
		var settings = $.extend(defaults, module_param.setting);
			
		settings['currentTable'] = FFJS.ContentList.setting[div_id].target;
		settings['module_name'] = FFJS.ContentList.setting[div_id].moduleName;
		settings['row_id'] = 0;		
		FFJS.CMS.InlineEdit.setting[div_id] = settings;
		
		var current_div = FFJS.ContentList.setting[div_id].currentDiv;
		var next_div = FFJS.ContentList.setting[div_id].nextDiv;		
		var current_table = $(FFJS.CMS.InlineEdit.setting[div_id].currentTable+'>tbody');
		var current_head = $(FFJS.CMS.InlineEdit.setting[div_id].currentTable+'>thead');
		
				// Make sure the plugin only get initialized once
		if ( current_table.data( 'inline-edit' ) === true ) {
			current_table = null;
			return;
		}else{	
			current_table.data('inline-edit', true );
		}
		// Prevent sending form submission
		//$form.bind( 'submit.inline-edit', function(){
		current_table.delegate( FFJS.CMS.InlineEdit.setting[div_id].form,'submit.inline-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");
			settings =FFJS.CMS.InlineEdit.setting[div_id];
			
			$( FFJS.CMS.InlineEdit.setting[div_id].currentTable+'>tbody' ).find( settings.form ).find( settings.save ).trigger( 'click.inline-edit' );
			
			settings = null;
			return false;
		});

		// Cancel Actions
		//$cancel.live( 'click.inline-edit', function(){
		current_table.delegate( FFJS.CMS.InlineEdit.setting[div_id].cancel,'click.inline-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");
			FFJS.CMS.InlineEdit.cancel(div_id);
			return false;
		});

		// Save Actions
		//$save.live( 'click.inline-edit', function( event ) {
		current_table.delegate( FFJS.CMS.InlineEdit.setting[div_id].save,'click.inline-edit', function( event ) {
			var div_id = $(this).parents(".ContentList").attr("name");
			FFJS.CMS.InlineEdit.save(div_id);
			return false;
		});
		
				
	//btn_add_root
		//current_div.find('a.btn_add_root').unbind('click.inline-edit').live('click.inline-edit', function() {	
		current_head.delegate('a.btn_add_root','click.inline-edit', function() {
			var div_id = $(this).parents(".ContentList").attr("name");
			var cate_tree_val = $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>thead').find('div.bar_select select.filter option:selected').val();
			if(cate_tree_val == ''){
				$('#msgDialog').html('<p>Please select "Category Tree" first ! Or Create a new category tree for selection.</p>');
				FFJS.Dialog.init(500, 200, 'Alert');
				FFJS.Dialog.msg_dialog('#msgDialog');
				return false;
			}
			var cate_name = $(this).parent().attr("name");
		    var new_tr ='<tr id="node-0" class="data color1 edit_now">'+
							'<td class="virtual" width="15px">'+
								'<input class="multi_checkbox" type="checkbox" value="0" name="f_action_del[]">'+
								'<input type="hidden" name="f_action[]" value="0">'+
							'</td>'+
							'<td class="data cate_name">'+	
									'<a class="text edit_now" name="'+cate_name+'" value="RootName" style="display: none;">RootName</a>'+
									'<span class="inline edit_now" style="">'+
									'<input class="text" type="text" name="'+cate_name+'" value="RootName">'+
									'</span>'+
							'</td>'+
							'<td class="data" width="1px">';	
			var max_cate_id = $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>thead').find('a[name="multi"]');
			max_cate_id.attr("id",parseInt(max_cate_id.attr("id"))+1);
			
			var column = {f_cate_id:max_cate_id.attr("id"),f_cate_father:0,f_cate_path:max_cate_id.attr("id"),f_cate_depth:1,f_cate_hasson:1,f_cate_tree:cate_tree_val,f_online:1,f_id:0};
			$.each(column,function(key,value){
				new_tr += '<div class="field"><a class="hidden" name="'+key+'" value="'+value+'"></a>'+
							'<span class="inline edit_now"><input type="hidden" name="'+key+'" value="'+value+'"></span></div>';			
			});
			new_tr += '</td><td><span class="new" style=""><a class="tooltip send" title="Save"></a><a class="tooltip stop" title="Cancel"></a></span></td></tr>';
			
			$(new_tr).prependTo( $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>tbody'));	
			FFJS.CMS.InlineEdit.setting[div_id]['row_id'] = 0;
			
			new_tr = null;
			column = null;
			cate_tree_val = null;
			max_cate_id = null;
		});	
		
	//row_panel
		//current_table.find('a.row_panel').unbind('click.inline-edit').live('click.inline-edit', function() {
		current_table.delegate('a.row_panel','click.inline-edit', function() {		
			var div_id = $(this).parents(".ContentList").attr("name");		
			if( $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>tbody').find('tr.clone').hasClass("clone") ){
				if($(this).parent().parent().parent().hasClass("clone")){
				
				}else{
					return FFJS.CMS.TreeTable.checkTask();
				}
			};
				
			if($(this).parent().find('div.bar_row_edit').size() > 0){
				$(this).parent().find('div.bar_row_edit').detach();
				return false;			
			}
			
			FFJS.CMS.ColumnEdit.cancel(div_id);
			FFJS.CMS.InlineEdit.cancel(div_id);

			//var rowid = $(this).parent().find('input.multi_checkbox').attr("value");
			var rowid = $(this).attr("name");
			$(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>tbody').find('div.bar_row_edit').detach();			
			var code4table = $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']).parent().find('div.bar_row_edit').clone();
			
			//alert($(code4table).attr("class"));
			$(code4table).show().find('a').attr("name",rowid);
			$(this).parent().append(code4table);
		
			code = null;
			code2 = null;
			rowid = null;
			return false;
		});
		
		//pic_edit	
		//current_div.find('tr.data td  a.pic_edit').unbind('click.inline-edit').live('click.inline-edit', function() {
		current_table.delegate('a.pic_edit','click.inline-edit', function() {	
			var div_id = $(this).parents(".ContentList").attr("name");
			var module_name = FFJS.CMS.InlineEdit.setting[div_id]['module_name'];

			FFJS.CMS.load_page(next_div, 'module/'+module_name, 'edit/'+$(this).attr("name")+'/'+div_id,
				function(response, status, xhr) {					
					if (status == "error") {
						//var msg = "<p class='error'> Sorry ! ";
						//$('#dialog').html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");	
						FFJS.Dialog.errorHandler(response, status, xhr);
					}else{						
						FFJS.Div.switch_div(div_id,current_div,next_div);
						setTimeout("FFJS.Dialog.close();", 200);												
					}
				}			
			);			
			return false;
		});	
		
		//copy
		//current_div.find('div.bar_row_edit a.copy').unbind('click.inline-edit').live('click.inline-edit', function() {
		current_table.delegate('div.bar_row_edit>a.copy','click.inline-edit', function() {
			var div_id = $(this).parents(".ContentList").attr("name");
			var module_name = FFJS.CMS.InlineEdit.setting[div_id]['module_name'];
			FFJS.CMS.load_page(next_div, 'module/'+module_name, 'copy/'+$(this).attr("name")+'/'+div_id,
				function(response, status, xhr) {							
					if (status == "error") {
						//var msg = "<p class='error'> Sorry ! ";
						//$('#dialog').html(msg + xhr.status + " " + xhr.statusText + " : "+ response + "</p>");		
						FFJS.Dialog.errorHandler(response, status, xhr);
					}else{						
						FFJS.Div.switch_div(div_id,current_div,next_div);
						setTimeout("FFJS.Dialog.close();", 200);
					
												
					}
				}			
			);
			return false;
		});	
		
	//inline_edit			
		//current_div.find('div.bar_row_edit a.inline_edit').unbind('click.inline-edit').live('click.inline-edit', function() {
		current_table.delegate('div.bar_row_edit>a.inline_edit','click.inline-edit', function() {
			// FFJS.CMS.ColumnEdit.cancel(div_id);
			// FFJS.CMS.InlineEdit.cancel(div_id);
			var div_id = $(this).parents(".ContentList").attr("name");
		
			FFJS.CMS.InlineEdit.setting[div_id]['row_id'] = $(this).attr("name");
			
			var parent_tr = $(this).parent().parent().parent().parent();
			parent_tr.find('td.data a.edit_now').show().removeClass( 'edit_now' );
			parent_tr.find('td.data span.edit_now').hide().html('').removeClass( 'edit_now' );
			parent_tr.parent().find('tr.edit_now a.row_panel').show().removeClass( 'edit_now' );
			parent_tr.parent().find('tr.edit_now span.new').hide().removeClass( 'edit_now' );
							
			parent_tr.addClass('edit_now');
			parent_tr.find('input.multi_checkbox').hide();
			parent_tr.find('a.row_panel').hide();
			parent_tr.find('span.new').show();	
			parent_tr.find('div.bar_row_edit').hide();	
			
			parent_tr.find('td.cate_name span.inline').show().addClass( 'edit_now' )
				.html('<input class="text" type="text"  value=\''+parent_tr.find('td.cate_name a').attr("value")+'\' name=\''+parent_tr.find('td.cate_name a').attr("name")+'\' />');
			parent_tr.find('td.cate_name a').hide().addClass( 'edit_now' );
			
			
			var namestack=new Array();
			$(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>thead').find('div.col_header span.new').each(function(){					
				namestack.push($(this).parent().find("a.col_panel").attr("name"));
			});
							
			$(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>tbody').find('.selected td.data').each(function(){	
				if(  $.inArray($(this).find('a').attr("name"),namestack) > -1){
					$(this).find('a').hide().addClass( 'edit_now' );
					$(this).find('span.inline').show().addClass( 'edit_now' ).html('<input class="text" type="text" value=\''+$(this).find('a').attr("value")+'\' name=\''+$(this).find('a').attr("name")+'\' />');
				}
			});
						
			$(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']+'>tbody').find('.selected div.field').each(function(){	
				$(this).find('span.inline').show().addClass( 'edit_now' ).html('<input type="hidden" value=\''+$(this).find('a').attr("value")+'\' name=\''+$(this).find('a').attr("name")+'\' />');
			});	
			parent_tr = null;
			namestack = null;
		});

	//pic_delete
		//current_div.find('a.pic_delete').click(function(){
		//currentList.find('tr.data td a.pic_delete').unbind('click.inline-edit').live('click.inline-edit', function() {
		current_table.delegate('a.pic_delete','click.inline-edit', function() {		
			if (confirm('Are you sure to delete ?')) {	
				var div_id = $(this).parents(".ContentList").attr("name");
				var module_name = FFJS.CMS.InlineEdit.setting[div_id]['module_name'];
				//var code4table = $(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']).parent().find('div.bar_row_edit').hide().detach();
				//$(FFJS.CMS.InlineEdit.setting[div_id]['currentTable']).parent().append(code4table);
				FFJS.CMS.Form.DeleteOne(div_id,module_name,$(this).attr('name'));	
			}
			return false;
		});
				
		settings = null;
		defaults = null;
		//current_div = null;
		current_table = null;
		current_head = null;	

	},
	save: function(div_id){
		if ($('#msgDialog'+div_id).length > 0) { 
			var msgD = '#msgDialog'+div_id;
		}else{
			var msgD = '#msgDialog';
		}
		settings =FFJS.CMS.InlineEdit.setting[div_id];
		$main = $( FFJS.CMS.InlineEdit.setting[div_id].currentTable+'>tbody' );
		
		$main.find( settings.form ).hide();
		var options = {
			ajax : {				
				mode : 'post',
				post_to : FFJS.url_root+'module/'+FFJS.CMS.InlineEdit.setting[div_id]['module_name']+'/save/'+FFJS.CMS.InlineEdit.setting[div_id]['row_id']+'/'+div_id,
				load_target : FFJS.ContentList.setting[div_id].target+' tbody',
				errorHandler :function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);} ,
				call_back : function(data) {
						FFJS.Dialog.errorHandler(data);
						var id = $(data).find('last_id').text();	
						if(id > 0){						
							$(msgD).html('Record [ '+id+' ] Saved ! ');
							FFJS.Dialog.init(500, 200, 'Message');
							FFJS.Dialog.msg_dialog(msgD);	
							FFJS.ContentList.reload(div_id);
						}
					}
			}
		};
				
		FormHandler.init('', options);
		FormHandler.checkForm('EditForm_'+div_id);	
		$main.find('td.data span.edit_now').hide().html('').removeClass( 'edit_now' );
		$main.find('td.data a.edit_now').show().removeClass( 'edit_now' );
		settings = null;	
		main = null;
		return false;
	},
	cancel: function(div_id){		
		$main = $( FFJS.CMS.InlineEdit.setting[div_id].currentTable+'>tbody' );

		$main.find('tr.edit_now .new').hide();
		$main.find('tr.edit_now a.row_panel').show();
		$main.find('tr.edit_now td.data span.edit_now').hide().html('');
		$main.find('tr.edit_now td.data a.edit_now').show();
		$main.find('tr.edit_now input.multi_checkbox').show().prop('checked',false);
		$main.find('tr.edit_now').removeClass('edit_now');
			
		$main = null;
		return false;
	}
};

// uploader
FFJS.CMS['Uploader'] = {
	post_name : null,
	post_base : null,	
	loading_html : '<img src="images/loading.gif" style="display: block; margin-left: auto; margin-right: auto;"><div style="font-size:14px; text-align: center;">Loading.....</div>',

	init : function( element_val,width_val, height_val, title_val ) {
		this.element = element_val;
		//$(this.element).attr('style', 'text-align:left; display:none;');
		//$(this.element).dialog("destroy");

		if (width_val != undefined) {			
			this.width_val = width_val;
		}
		
		if (height_val != undefined) {
			this.height_val = height_val;
		}
		
		if (title_val != undefined) {
			this.title_val = this.title_val + ' - ' + title_val;
		}
	},
	
	showUpload : function( post_name,table_name ) {
		if(table_name == undefined){
			table_name = FFJS.CMS.page_section;
		}
		FFJS.CMS.Uploader.hideUpload();
		FFJS.CMS.Uploader.post_name = post_name;
		FFJS.CMS.Uploader.post_base = 'module/'+table_name+'/';		
		FFJS.CMS.Uploader.bind_action(post_name);
		FFJS.CMS.Uploader.load_list(post_name);
		var w = 650;
		var h = 350;
		//alert(w+' '+h);
		$('#file-uploader').dialog({
									title : 'Focus CMS - File Uploader',
									width: w,
									minWidth: 650,
									height: h,
									close: function(ev, ui) {$(this).dialog('destroy');},									
									minHeight: 350					
									//position: [x, y],
									});
													
	},

	hideUpload : function() {
		$('#file-uploader').dialog('close');
		//$('#file-uploader').dialog('destroy');		
		$('div.img_selector_parent').attr('style', '');	
	},
	
	bind_action : function(post_name) {
		var code = '<input type="file" name="fupload_'+post_name+'" id="fupload_'+post_name+'" style="position: relative; left:15px; top:10px;"/>';
		$('#image_upload_panel').html(code);
		
		$('#fupload_'+post_name).bind('change', function() {
			$('#dialog').html(FFJS.CMS.loading_html);
			
			FFJS.Dialog.modal_val = true;
			FFJS.Dialog.init(32, 32);
			FFJS.Dialog.blank_dialog('#dialog');				
			
			FFJS.CMS.Uploader.do_upload( post_name );
		});
	},
	
	load_list : function( post_name ) {	
		$('#file_list').load(
			FFJS.CMS.url_root+FFJS.CMS.Uploader.post_base+'load_files/',
			{ field : post_name },
			function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);}			
		);
	},
	
	do_upload : function( post_name ) {
		$.ajaxFileUpload({
			url : FFJS.CMS.url_root+FFJS.CMS.Uploader.post_base+'handle_upload/'+post_name,
			secureuri :false,
			fileElementId: 'fupload_'+post_name,
			dataType: 'xml',
			success: function(data, status) {			
				//$('#fupload_'+post_name).parent().next().html('');						
				if ($(data).find('error').length > 0) {
					FFJS.Dialog.errorHandler(data);	
				}
				else {
					FFJS.CMS.Uploader.load_list(post_name);
					FFJS.CMS.Uploader.bind_action(post_name);					
					setTimeout("FFJS.Dialog.close();", 200);	
				}							
			},			
			// Exception Only
			error: function (response, status, xhr) {
				FFJS.Dialog.errorHandler(response, status, xhr); 
			}
		});
	},
	
	do_delete : function(post_name, file_name, ext) {
		var input = $('input.afile_upload');
		var delete_file = file_name+'.'+ext;
		var used = false;
		
		for (var i = 0 ; i < input.length ; i++) {				
			if (input.eq(i).val() == delete_file) {
				used = true;
			}
		}
		
		if (!used) {			
			$.post(
				FFJS.CMS.url_root+FFJS.CMS.Uploader.post_base+'handle_delete/',
				{ file : file_name, extension : ext },
				function() {}
			).success(function(data) {					
				if ($(data).find('error').length > 0) {
					FFJS.Dialog.errorHandler(data);	
				}else {					
					FFJS.CMS.Uploader.load_list(post_name);	
				}				
			})
			.error(function(response, status, xhr) {FFJS.Dialog.errorHandler(response, status, xhr);});
		}else {
			$('#msgDialog').html('<p>File is already use by one of the fields! It cannot be deleted.</p>');			
			FFJS.Dialog.init(200, 250, 'Alert');
			FFJS.Dialog.msg_dialog('#msgDialog');				
		}
	}
};
	
	
FFJS.CMS['ImageUpload'] = {
	update_field_value : function(filename, obj) {
		var post_name = FFJS.CMS.Uploader.post_name;

		$('input[name='+post_name+']').val(filename);
		$('#img_'+post_name).attr('src' , $(obj).attr('src'));			
		FFJS.CMS.Uploader.hideUpload();
	}
};
	
FFJS.CMS['ImageListDesc'] = {
	sort_image : function(post_name) {
		FFJS.CMS.ImageListDesc.update_text_value(post_name);
	},
	
	update_text_value : function(post_name) {
		var ckb = $(':input[name='+post_name+'_del[]]');
		var tbox = $(':input[name='+post_name+'_text[]]');
		var new_val = '';
				
		for (var i = 0 ; i < ckb.length ; i++) {
			new_val += ckb.eq(i).val()+'|'+tbox.eq(i).val();
			
			if (i+1 != ckb.length) {
				new_val += "\n";
			}		
		}
		
		$('#hidden_'+post_name).val(new_val);
	},
	
	update_field_value : function(filename, obj) {
		var post_name = FFJS.CMS.Uploader.post_name;			
		var tar_obj = $(':input[name='+post_name+']');
		var c_value = tar_obj.val();
		var n_value = c_value;
		
		if ( c_value != '' ) {
			var arr_value = c_value.split("\n");				
			var used = false;
			
			var temp = '';
			var img_val = new Array();
			for (var i = 0 ; i < arr_value.length ; i++) {
				temp = arr_value[i].split('|');
				
				img_val.push(temp);
			}
			
			for (var i = 0 ; i < img_val.length ; i++) {
				if (img_val[i] == filename) {
					used = true;
				}
			}
			
			if (!used) {
				FFJS.CMS.ImageListDesc.prepend_img(post_name, obj, filename);
				n_value = filename+'|'+"\n"+c_value;
			}
			else {
				$('#msgDialog').html('<p>Image Used Already</p>');
			
				FFJS.Dialog.init(500, 200, 'Alert');
				FFJS.Dialog.msg_dialog('#msgDialog')	
			}
		}
		else {
			FFJS.CMS.ImageListDesc.prepend_img(post_name, obj, filename);
			n_value = filename+'|';
		}
		
		tar_obj.val(n_value);
	},
	
	prepend_img : function(post_name, obj, filename) {
		var code = '';
		
		code += '<div class="focuscms-image-holder">';
			code += '<img src="'+$(obj).attr('src')+'"/>';
			code += '<input type="text" post_name="'+post_name+'" class="focuscms-imagedesc-box" style="width:100px;" name="'+post_name+'_text[]" value="">';
			code += '<input type="checkbox" name="'+post_name+'_del[]" style="display:none;" value="'+filename+'">';
		code += '</div>';
		
		$('#list_data_'+post_name).prepend(code);
		bind_tbox();
	}
};
	
FFJS.CMS['ImageList'] = {
	sort_image : function(post_name) {			
		var ckb = $(':input[name='+post_name+'_del[]]');
		var new_val = '';
				
		for (var i = 0 ; i < ckb.length ; i++) {
			new_val += ckb.eq(i).val();
			
			if (i+1 != ckb.length) {
				new_val += "\n";
			}		
		}
		
		$('#hidden_'+post_name).val(new_val);
	},
	
	update_field_value : function(filename, obj) {
		var post_name = FFJS.CMS.Uploader.post_name;			
		var tar_obj = $(':input[name='+post_name+']');
		var c_value = tar_obj.val();
		var n_value = c_value;

		if ( c_value != '' ) {
			var arr_value = c_value.split("\n");
			var used = false;
			
			for (var i = 0 ; i < arr_value.length ; i++) {
				if (arr_value[i] == filename) {
					used = true;
				}
			}
			
			if (!used) {
				FFJS.CMS.ImageList.prepend_img(post_name, obj, filename);
				n_value = filename+"\n"+c_value;
			}
			else {
				$('#msgDialog').html('<p>Image Used Already</p>');
			
				FFJS.Dialog.init(500, 200, 'Alert');
				FFJS.Dialog.msg_dialog('#msgDialog')	
			}
		}
		else {
			FFJS.CMS.ImageList.prepend_img(post_name, obj, filename);
			n_value = filename;
		}
		
		tar_obj.val(n_value);
	},
	
	prepend_img : function(post_name, obj, filename) {
		var code = '';
		
		code += '<div class="focuscms-image-holder">';
		code += '<img width="100" height="100" src="'+$(obj).attr('src')+'"/>';
		code += '<input type="checkbox" style="display:none;" name="'+post_name+'_del[]" value="'+filename+'"/>';
		code += '<input type="hidden" name="'+post_name+'_ids[]" value="'+$(obj).parent().attr('name')+'"/>';
		code += '</div>';
		
		$('#list_data_'+post_name).prepend(code);
	}
};
	
FFJS.CMS['FileUpload'] = {
	update_field_value : function(filename, obj) {
		var post_name = FFJS.CMS.Uploader.post_name;

		$('input[name='+post_name+']').val(filename);
		$('#filename-'+post_name).html(filename);
		FFJS.CMS.Uploader.hideUpload();
	}
};
// end uploader
