/**
 * AS4WidgetsLayoutEditor Class
 *
 * Behaviours for the channel component's widgets layout editor
 */

var widgetsLayoutEditor;
var resourceLibrary;

document.observe('dom:loaded', function() {
	
	
	if(AS4ResourceLibrary)
	{
		resourceLibrary = new AS4ResourceLibrary();
	
		if(Prototype.Browser.IE && typeof(widgetsLayoutEditor) != 'undefined')
		{
			resourceLibrary.onResourceClicked = widgetsLayoutEditor.onResourceSelected.bind(widgetsLayoutEditor);
		}
		

		// Override the resource library's success callback to make each resource a selectable
		// thing
		resourceLibrary.onFetchResourcesSuccess = function(transport, target)
		{
			// Ignore exceptions
			if(transport.headerJSON && transport.headerJSON.exception)
				return;
		}
	}

    if(AS4WidgetsLayoutEditor)
    {
        widgetsLayoutEditor = new AS4WidgetsLayoutEditor();
    }

}); 

window.onbeforeunload = function(e) 
{
	if(widgetsLayoutEditor && widgetsLayoutEditor.is_dirty)
	{
	var e = e || window.event;

	if(e)
		e.returnValue = 'You have not saved the current layout. Are you sure you want to leave this page? (Unsaved changes will be lost)';

	return 'You have not saved the current layout. Are you sure you want to leave this page? (Unsaved changes will be lost)';
	}
};

var AS4WidgetsLayoutEditor = Class.create({

	/**
	 * @type {Element} Cache the root element that contains the widget-sortables
	 */
	sortables_container: null,

	/**
	 * @type {Boolean} Indicate if the widgets layout editor is currently saving the page layout
	 */
	isSaving: null,

	/**
	 * @type {integer} Store a reference to the current channel id
	 */
	channel_id: null,

	/**
	 * @type {AS4ResourceLibrary} The local resource library instance for selecting resources
	 */
	resource_library: null,

	/**
	 * @type {Hash} The current channel_widgets_id and options_id into which a selected resource will be injected
	 */
	selected_option: null,

	/**
	 * @type {Boolean} Indicate if the current layout is dirtied and requires saving
	 */
	is_dirty: false,

	/**
	 * @type {Boolean} Indicate if the current layout is dirtied and requires saving
	 */
	updateFlag: false,	
	
	/**
	 * Create a widgets layout editor for the given element. The element should contain
	 * an array of widget_column elements
	 *
	 * @param {Element} The root element for the widgets layout editor
	 */
	create:function(element)
	{
		this.sortables_container = $(element);
		this._createSortables();
		
		this.isSaving = false;
		this.is_dirty = false;

		if(resourceLibrary && AS4ResourceLibrary)
			resourceLibrary.onResourceClicked = this.onResourceSelected.bind(this);

		// Trigger unload warnings
		var self = this;
	},

	/**
	 * Return the containment elements for draggables
	 *
	 * @return Array
	 */
	_containmentElements: function()
	{
		columns = this.sortables_container.select('.widget_column', '.widget_column_primary_editable', '.widget_column_secondary_editable', '.widget_column_tertiary_editable' );
		columns.invoke('identify');

		containment = columns.clone();
		containment.push('widget_header');
		containment.push('widget_footer');

		return containment;
	},


	/**
	 * Private method to create the sortables in the current
	 * sortables_container
	 */
	_createSortables: function()
	{
		columns = this.sortables_container.select('.widget_column', '.widget_column_primary_editable', '.widget_column_secondary_editable', '.widget_column_tertiary_editable' );
		columns.invoke('identify');

		// Fix IE6's buggy drag-dropping
		Position.includeScrollOffsets = true;	

		var sortable_options = {
			tag: 'div',
			//only: 'widget',
			handle: ['toolbar'],
			constraint: null,
			hoverclass: 'active_drop',
			dropOnEmpty: true,
			scroll: window,
			containment: this._containmentElements(),
			onChange: this.onPanelDragged.bind(this),
			onUpdate: this.onPanelDropped.bind(this)
		}
        
		columns.each(function(column) {
			Sortable.destroy(column.identify());
			Sortable.create(column.identify(), sortable_options);
		});

		// Create header and footer sortables
		Sortable.destroy('widget_header');
		Sortable.destroy('widget_footer');

		Sortable.create('widget_header', sortable_options);
		Sortable.create('widget_footer', sortable_options);
	},
	
	/**
	 * Returns all the sortable (droppable) elements as an array
	 *
	 * @return {Array}
	 */
	_getSortableElements: function()
	{
		sortables = this.sortables_container.select('.widget_column', '.widget_column_primary_editable', '.widget_column_secondary_editable', '.widget_column_tertiary_editable' );

		sortables.push($('widget_header'));
		sortables.push($('widget_footer'));

		return sortables;
	},

	/**
	 * Display an inline resource selector to allow the user
	 * to select a resource to be associated to the widget
	 * 
	 * @param {integer} channel_widgets_id The channel_widgets_id that will receive the selected resource
	 * @param {integer} options_id The option identifier within the channel widget
	 * @param {Array} [resource_types] Optional array of the resource types that the media selector will show. Default is an empty array (all resource types)
	 * @param {Array} [updateFlag] Triggers callback to concat mutliple resource selectors in widget options

	 */
	showResourceSelector: function(channel_widgets_id, options_id, resource_types)
	{
		var resource_types = (resource_types ? resource_types : $A());

		/**
		this.resourceValueTarget = target.down('div.current_value');
		this.resourceValueHTML = target.down('input.'+target.down('input.metaType').value);
		this.resourceValueHolder = target.down('div.current_item');
		*/

		resourceLibrary.searchTypes = resource_types;
		resourceLibrary.cwid = channel_widgets_id;
		resourceLibrary.opid = options_id;
		
		this.selected_option = {
			channel_widgets_id: channel_widgets_id,
			options_id: options_id
		};

		AS4Shell.getInstance().showLightbox({
			callback: this.onShowResourceSelector.bind(this),
			width: 613,
			height: 645
		});
	},
	
	showIntroSelector: function(channel_widgets_id, options_id, resource_types)
	{
		var resource_types = (resource_types ? resource_types : $A());

		/**
		this.resourceValueTarget = target.down('div.current_value');
		this.resourceValueHTML = target.down('input.'+target.down('input.metaType').value);
		this.resourceValueHolder = target.down('div.current_item');
		*/

		resourceLibrary.searchTypes = resource_types;
		
		this.selected_option = {
			channel_widgets_id: channel_widgets_id,
			options_id: options_id
		};

		AS4Shell.getInstance().showLightbox({
			callback: this.onShowIntroSelector.bind(this),
			width: 613,
			height: 645
		});
	},

	/**
	 * Callback for the resource selector lightbox
	 */
	onShowResourceSelector: function()
	{
		var url = '/channel/resource_selector_lightbox';

		var params = {
			renderMode: 'lightbox',
			folder_id: this.channel_id
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_container', $A([this.onImagesSelectorShown.bind(this)]), {showIndicator: false});
		
		return	'<div id="add_panel_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
	},
	/**
	 * Callback for the resource selector lightbox
	 */
	onShowIntroSelector: function()
	{
		var url = '/channel/resource_selector_lightbox';

		var params = {
			renderMode: 'lightbox',
			folder_id: this.channel_id
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_container', $A([this.onIntroSelectorShown.bind(this)]), {showIndicator: false});
		
		return	'<div id="add_panel_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
	},

	/**
	 * Trigger a load of the resource selector once it is loaded into the lightbox!
	 */
	onResourceSelectorShown: function(transport, target)
	{
		resourceLibrary.channelId = AS4ResourceBrowser.MY_RESOURCES_PATH;

		// Bind lightbox interface
		if($('ml_search_terms'))
			$('ml_search_terms').observe('keyup', function(e) {
				resourceLibrary.searchTerms = $F(this);
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.startSearch.bind(resourceLibrary, $F(this)).delay(2); // Delay the search by 2 seconds, allowing typing to catch up
			});

		// Smart folder filters
		if($('smart_folder'))
		{
			$('smart_folder').observe('change', function(e) {
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.currentFolderId = $F(this);
				resourceLibrary.fetchResources();
			});

			
			// Default search should match the current selection
			resourceLibrary.currentFolderId = $F('smart_folder');
		}
		
		resourceLibrary.setResourcesPage(1, {refresh: false});
		resourceLibrary.searchTerms = '';

		// Run a search
		resourceLibrary.fetchResources();
	},
	
	/**
	 * Display an inline resource selector to allow the user
	 * to select images for the slide show panel
	 * 
	 * @param {integer} channel_widgets_id The channel_widgets_id that will receive the selected resource
	 * @param {integer} options_id The option identifier within the channel widget
	 * @param {Array} [resource_types] Optional array of the resource types that the media selector will show. Default is an empty array (all resource types)
	 *
	 */
	showImagesSelector: function(channel_widgets_id, options_id, resource_types)
	{
		var resource_types = (resource_types ? resource_types : $A());

		/**
		this.resourceValueTarget = target.down('div.current_value');
		this.resourceValueHTML = target.down('input.'+target.down('input.metaType').value);
		this.resourceValueHolder = target.down('div.current_item');
		*/

		resourceLibrary.searchTypes = resource_types;
		resourceLibrary.multiple = true;
				
		
		this.selected_option = {
			channel_widgets_id: channel_widgets_id,
			options_id: options_id
		};

		AS4Shell.getInstance().showLightbox({
			callback: this.onShowImagesSelector.bind(this),
			width: 415,
			height: 335
		});
	},

	/**
	 * Callback for the resource selector lightbox
	 */
	onShowImagesSelector: function()
	{
		var url = '/channel/resource_selector_lightbox';

		var params = {
			renderMode: 'lightbox',
			folder_id: this.channel_id
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_container', $A([this.onImagesSelectorShown.bind(this)]), {showIndicator: false});
		
		return	'<div id="add_panel_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
	},

	/**
	 * Trigger a load of the resource selector once it is loaded into the lightbox!
	 */
	onImagesSelectorShown: function(transport, target)
	{
		resourceLibrary.channelId = AS4ResourceBrowser.MY_RESOURCES_PATH;

		// Bind lightbox interface
		if($('ml_search_terms'))
			$('ml_search_terms').observe('keyup', function(e) {
				resourceLibrary.searchTerms = $F(this);
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.startSearch.bind(resourceLibrary, $F(this)).delay(2); // Delay the search by 2 seconds, allowing typing to catch up
			});

		// Smart folder filters
		if($('smart_folder'))
		{
			$('smart_folder').observe('change', function(e) {
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.currentFolderId = $F(this);
				resourceLibrary.fetchResources();
			});

			
			// Default search should match the current selection
			resourceLibrary.currentFolderId = $F('smart_folder');
		}
		
		resourceLibrary.setResourcesPage(1, {refresh: false});
		resourceLibrary.searchTerms = '';

		// Run a search
		resourceLibrary.fetchResources();
	},	
	
	/**
	 * Trigger a load of the resource selector once it is loaded into the lightbox!
	 */
	onIntroSelectorShown: function(transport, target)
	{
		resourceLibrary.channelId = AS4ResourceBrowser.MY_RESOURCES_PATH;

		// Bind lightbox interface
		if($('ml_search_terms'))
			$('ml_search_terms').observe('keyup', function(e) {
				resourceLibrary.searchTerms = $F(this);
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.startSearch.bind(resourceLibrary, $F(this)).delay(2); // Delay the search by 2 seconds, allowing typing to catch up
			});

		// Smart folder filters
		if($('smart_folder'))
		{
			$('smart_folder').observe('change', function(e) {
				resourceLibrary.setResourcesPage(1, {refresh: false});
				resourceLibrary.currentFolderId = $F(this);
				resourceLibrary.fetchResources();
			});

			
			// Default search should match the current selection
			resourceLibrary.currentFolderId = $F('smart_folder');
		}
		
		resourceLibrary.setResourcesPage(1, {refresh: false});
		resourceLibrary.searchTerms = '';
		resourceLibrary.onResourceClicked = widgetsLayoutEditor.onIntroSelected.bind(widgetsLayoutEditor);
		
		// Run a search
		resourceLibrary.fetchResources();
	},
	
	/**
	 * Adds the selection of widgets from a lightbox to the
	 * current page
	 * 
	 */
	addSelectedWidgets: function()
	{
		var checked = $('available_widgets_form').getInputs('checkbox', 'selected_widgets[]').findAll(function(item) {
	 		return item.checked; 
		}).pluck("value");

		var url = '/channel/add_widgets_to_layout';
		var params = {
			channel_id: this.channel_id,
			widget_ids: checked.toJSON()
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onAddSelectedWidgets.bind(this)]));

		// Close the lightbox
		AS4Shell.getInstance().closeLightbox();
	},

	onAddSelectedWidgets: function(transport, target)
	{
		AS4Shell.getInstance().reload();	
	},

	/**
	 * Perform an AJAX copy of the channel's parent widget layout schema into this channel's
	 * widget schema
	 */
	copyParentChannelWidgetsLayout: function()
	{
		var url = '/channel/copy_parent_channel_widget_schema';
		var params = {
			channel_id: this.channel_id
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onCopyParentChannelWidgetsLayout.bind(this)]), {message: 'Copying...'});
	},

	/**
	 * Show the add widgets lightbox
	 */
	showAddWidgets: function()
	{
		var params = {
			renderMode: 'lightbox'
		}

		AS4Shell.getInstance().showLightbox({
			callback: this.onShowWidgetsSelector.bind(this),
			width: 415,
			height: 335
		});
	},

	/**
	 * Callback for the widget selector lightbox
	 */
	onShowWidgetsSelector: function()
	{
		var url = '/channel/widget_selector_lightbox';

		var params = {
			renderMode: 'lightbox'
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_container', $A([this.onResourceSelectorShown.bind(this)]), {showIndicator: false});
		
		return	'<div id="add_panel_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
	},


	/**
	 * Perform an AJAX delete of the channel's widget layout schema
	 */
	deleteChannelWidgetsLayout: function()
	{
		if(!confirm('Are you sure you want to delete this channel\'s layout? This cannot be undone'))
			return;

		var url = '/channel/delete_channel_widget_schema';
		var params = {
			channel_id: this.channel_id
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onDeleteChannelWidgetsLayout.bind(this)]), {message: 'Deleting...'});
	},

	onDeleteChannelWidgetsLayout: function(transport, target)
	{
		this.onCopyParentChannelWidgetsLayout(transport, target);
	},

	onCopyParentChannelWidgetsLayout: function(transport, target)
	{
		if(transport.headerJSON.exception)
			return;

		AS4Shell.getInstance().reload();
	},

	/**
	 * Perform an AJAX save of a channel's widget layout schema
	 */
	saveChannelWidgetsLayout: function()
	{
			
		if(this.isSaving)
			return;

		var element = $(this.sortables_container);
		var serialized = $A();

		columns = this.sortables_container.select('.widget_column', '.widget_column_primary_editable', '.widget_column_secondary_editable', '.widget_column_tertiary_editable' );
		
		var count = 0;
		columns.each(function(column) {
				serialized.push(Sortable.sequence(column));
		});

		// Append any widgets in the header and footer columns
		schema = $H({
			columns: serialized,
			header: Sortable.sequence('widget_header'),
			footer: Sortable.sequence('widget_footer')
		});

		var url = '/channel/save_channel_widget_schema'; 

		var params = {
			channel_id: this.channel_id,
			schema: schema.toJSON()
		};

		this.isSaving = true;
		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onSaveChannelWidgetsLayoutComplete.bind(this)]), {message: 'Saving...'});
	},

	onSaveChannelWidgetsLayoutComplete: function(transport, target)
	{
		this.isSaving = false;
		this.is_dirty = false;
	},
	
	/**
	 * Perform an AJAX save of a channel_widget's options
	 *
	 * @param {Element(Form)} form The form element containing the channel_widget's options
	 */
	saveChannelWidgetOptions: function(strform, channel_widgets_id)
	{
		var form = $(strform);
		
		var url = '/channel/save_channel_widget_options';
		var opts = $H();
		var params = form.serialize();
		
		jQuery.noConflict();
		//channel_widgets_id = jQuery("#"+strform).children("#channel_widgets_id").attr("value");
			
		thisClass = this; //because this get overwritten by jQuery
		
		 jQuery.ajax({
		   type: "POST",
		   url: url,
		   data: params,
		   success: function(msg){
		   	
		   	if(msg != '')
		   	{
		     	var jsonT = eval('('+ msg +')');
		     	channel_widgets_id = jsonT.channel_widgets_id;
		     
		    	var url = '/channel/load_channel_widget';
				
				var params = {
					renderMode: 'update',
					channel_widgets_id: channel_widgets_id
				};

				element = $('channel_widgets_' + channel_widgets_id); // The widget's panel to be replaced

				AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([thisClass.onReloadWidgetComplete.bind(thisClass)]));
		   	}
		   }
		 });

		
	//	AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onSaveChannelWidgetOptionsComplete.bind(this)]), {message: 'Saving...',	method: 'post'});
	},

	/**
	 * Ajax callback for the saveChannelWidgetOptions method
	 *
	 */
	onSaveChannelWidgetOptionsComplete: function(transport, target)
	{
		// Chained AJAX request to now go and load in the widget's new content!
		var url = '/channel/load_channel_widget';
		var channel_widgets_id = transport.headerJSON.channel_widgets_id;

		var params = {
			renderMode: 'update',
			channel_widgets_id: channel_widgets_id
		};

		element = $('channel_widgets_' + channel_widgets_id); // The widget's panel to be replaced

		AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([this.onReloadWidgetComplete.bind(this)]));
	},

	/**
	 * Ajax callback to rebuild sortables onces a widget has been reloaded
	 *
	 */
	onReloadWidgetComplete: function(transport, target)
	{
		this._createSortables();
				
	},

	/**
	 * Remove a channels_widget from the page schema
	 *
	 * @param {integer} channel_widgets_id The id of the channel_widget to remove
	 */
	removeWidget: function(channel_widgets_id)
	{
		if(!confirm("Are you sure you want to remove this panel?\n\n (This cannot be undone)"))
			return;

		var url = '/channel/remove_channel_widget';

		var params = {
			channel_widgets_id: channel_widgets_id
		};

		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onRemoveWidgetComplete.bind(this)]));
	},

	/**
	 * Callback for the removeWidget AJAX method
	 */
	onRemoveWidgetComplete: function(transport, target)
	{
		$('channel_widgets_' + transport.headerJSON.channel_widgets_id).remove();
		this._updateBlankColumns();
	},

	/**
	 * Toggle the display of a widget's control panel
	 *
	 * @param {integer} channel_widgets_id The id of the channel_widget to toggle
	 */
	toggleWidgetOptions: function(channel_widgets_id)
	{
		/*
		element = $('channel_widgets_' + channel_widgets_id_container); // The widget's content

		element.down('.toolbar').toggle();
		if(element.down('.widget_content'))
			element.down('.widget_content').toggle();
		element.down('form.options_panel').toggle();
		*/
		
		e = jQuery('#widget_options_' + channel_widgets_id + '_container');
		if(jQuery(e).is(":hidden"))
			jQuery(e).slideDown();
		else
			jQuery(e).slideUp();
			
		c = jQuery('#channel_widgets_' + channel_widgets_id + ' .widget_content');
		if(jQuery(c).is(":hidden"))
			jQuery(c).slideDown();
		else
			jQuery(c).slideUp();
	},

	
	/**
	 * Toggle the display of a widget's control panel
	 *
	 * @param {integer} channel_widgets_id The id of the channel_widget to toggle
	 */
	toggleOptionsTabs: function(active_tab,channel_widgets_id)
	{	
		if(active_tab != ''){
			e = jQuery('#widget_options_' + channel_widgets_id + '_container span');
				jQuery(e).hide();
				
				jQuery('#widget_options_' + channel_widgets_id + '_container .tab_container').children("a").each(function(i, ele)
					{
						if(jQuery(ele).attr("class") == 'active_options_tab'){
							jQuery(ele).attr("class","button");	
						}
					}); 
				
			n =	jQuery('#widget_options_' + channel_widgets_id + '_container #' + active_tab + '_button');
				jQuery(n).attr("class","active_options_tab");
				
				
			t = jQuery('#widget_options_' + channel_widgets_id + '_container span.' + active_tab);
				jQuery(t).show();	
		}
	},	
	
	/**
	 * Callback occurs when a Sortable drag causes a reordering
	 *
	 * @param {Element} container The sortable container
	 */
	onPanelDragged: function(container)
	{
		this._updateBlankColumns(container);
	},

	/**
	 * Callback occurs when a Sortable element is changed
	 * @param {Element} container The sortable container
	 */
	onPanelDropped: function(container)
	{
		this._updateBlankColumns(container);
		this.is_dirty = true;

		// Save the channel widgets layout
		this._createSortables();
		this.saveChannelWidgetsLayout();
	},

	_updateBlankColumns: function(container)
	{
		var container = $(container);

		sortables = this._getSortableElements();
		sortables.each(function(container) {
			// Update any empty containers
			if(container.select('.panel').length == 0)
			{
				if(!container.hasClassName('blank_column')) 
					container.addClassName('blank_column');
			}
			else 
				container.removeClassName('blank_column');
		});
	},

	/**
	 * Event triggered by a resource being selected in the 
	 *
	 * options can be 
	 * {
	 *  title: string Title of the selected resource
	 *  [type]: {string} One of 'resource' or 'folder'. Default is resource.
	 * }
	 * @param {integer} id Id of the resource to insert
	 * @param {Hash} type Type of the resource, either 'resource' or 'folder'. Default is 'resource'.
	 */

	onResourceSelected: function(id, options)
	{     
		
		
		var resourceTitle = options.title;
		
		options = Object.extend({
			title: null,
			type: 'resource',
      event: null
		}, options || {});

    var event = options.event;

		if(resourceLibrary.multiple == true)
		{
			// We need to be selecting multiple images here and adding the names to the select box and the ids to the hidden field in a pipe seperated list.
			var opt = document.createElement('option');
		      opt.text = options.title;
		      opt.value = id;
		        
          // Check that the image hasn't been added already
          if($("images_id_list").value.indexOf(id) == -1)
          {
            $("images_id_list").value = $("images_id_list").value + "|" + id;
            $("images_list").options.add(opt);

            if(event)
            {
              var element = $(event.element());
              element.src = '/app/common/assets/images/icons/14/selected.png';
            }
          }
          else
            alert("The selected image has already been added to the slide show.");
		}
		else
		{
			AS4Shell.getInstance().closeLightbox();

			// Request that server sends us the HTML to insert for this resource
			// Determine the element into which the selected resource will be set
			
			if(this.selected_option)
			{
				var cwid = this.selected_option.channel_widgets_id;
				var opid = this.selected_option.options_id.toString();
			}
			else
			{
				var cwid = resourceLibrary.cwid;
				var opid = resourceLibrary.opid;
			}
				
			$('widget_options_' + cwid).down('input[id="resource_title_' + opid +'"]').value = (options.title || '');
			$('widget_options_' + cwid).down('input[id="options[' + opid +']"]').value = id;

            var url = '/channel/update_multilang_folder_filter';
            var params = {
                resource_id:id,
                channel_widgets_id:cwid
            };
            AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onUpdateMultilangFolderFilterComplete.bind(this)]));

			if(this.updateFlag != false){
				jQuery(".options_"+cwid+"_"+this.updateFlag).attr("value",jQuery("form#widget_options_" + cwid +" span#scanner input").serialize());	
			}
					
			// if the opid includes '_intro_webpage' then we want to run the update function for this channel widget
			if(opid.indexOf("_intro_webpage") != -1)
			{
				this.updateFormIntroduction(cwid, opid.replace("_intro_webpage", ""), id, resourceTitle);
			}
			else
			{
				$('widget_options_' + cwid).down('input[id="resource_title_' + opid +'"]').value = (options.title || ''); 
				$('widget_options_' + cwid).down('input[id="options[' + opid +']"]').value = id; 
			}
		}
	},

	/**
	 * Event triggered by a resource being selected in the 
	 *
	 * options can be 
	 * {
	 *  title: string Title of the selected resource
	 *  [type]: {string} One of 'resource' or 'folder'. Default is resource.
	 * }
	 * @param {integer} id Id of the resource to insert
	 * @param {Hash} type Type of the resource, either 'resource' or 'folder'. Default is 'resource'.
	 */

	onIntroSelected: function(id, options)
	{     
		var resourceTitle = options.title;
		
		options = Object.extend({
			title: null,
			type: 'resource',
      		event: null
		}, options || {});

		
		
   		var event = options.event;

		AS4Shell.getInstance().closeLightbox();

		// Request that server sends us the HTML to insert for this resource
		// Determine the element into which the selected resource will be set
		var cwid = this.selected_option.channel_widgets_id;
		var opid = this.selected_option.options_id.toString();
			
		opid = opid.replace("_intro_webpage", "");
		//$('widget_options_' + cwid).down('input[id="options[73]_webpage"]').value = (options.title || '');
		//$('widget_options_' + cwid).down('input[id="options[' + opid +']"]').value = id;
		
		jQuery("#channel_widgets_"+cwid+" #resource_title_"+opid+"_intro_webpage").attr("value", options.title);
		jQuery("#channel_widgets_"+cwid+" #options_"+opid+"_webpage_"+cwid).attr("value", id);
		
		widgetsLayoutEditor.updateFormIntroduction(cwid, opid, id, options.title);
	},

    onUpdateMultilangFolderFilterComplete:  function(transport, target)
    {
        var folder_id = transport.headerJSON.folder_id;
        var folder_name = transport.headerJSON.folder_name;
        var folder_path = transport.headerJSON.folder_path;
        var section_ids= transport.headerJSON.section_ids;
        var language_id= transport.headerJSON.language_id;
        var channel_widget_id= transport.headerJSON.channel_widget_id;
        
        var widgetOptionSelects = jQuery("#widget_options_"+channel_widget_id+" select");
        
            widgetOptionSelects.each(function(i, ele)
            {
                for(var j=0;j<section_ids.length;j++)
                {
                if(ele.id =="related_resourcs_language_section_folder_filter["+section_ids[j]+"]")
                {
                    var select_id = ele.id;
                    for (var i=0;i<folder_id.length;i++)
                        {
                        document.getElementById(select_id).options[i]=new Option(folder_name[i],folder_id[i],true,false);
                        }
                }
                }

            });
            
        var lang_tabs = jQuery("#channel_widgets_"+channel_widget_id+" .lang_tab");
        lang_tabs.each(function(i, lang_tab)
        {
            $(lang_tab.id).style.fontWeight = "normal";
            $(lang_tab.id).style.backgroundColor  = "white";

        });
        var currentID = "RD"+language_id;
        $(currentID).style.fontWeight = "bold";
        $(currentID).style.backgroundColor  = "#ceceff";

        var lang_sections = jQuery("#channel_widgets_"+channel_widget_id+" .lang_section");
        lang_sections.each(function(i, lang_section)
        {
            $(lang_section.id).style.display = "none";

        });
        var currentID1 = "language_sections"+language_id;
         $(currentID1).style.display = "block";
         
    },

    /**
     * Change language tab
     **/
    change_language_tab: function (channel_widget_id,language_id)
    {  
    	
    	
    	
        var lang_tabs = jQuery("#channel_widgets_"+channel_widget_id+" .lang_tab");
     
        lang_tabs.each(function(i, lang_tab)
        { 
            $(lang_tab.id).style.fontWeight = "normal";
            $(lang_tab.id).style.backgroundColor  = "white";
          
        });
        var currentID = "RD"+$(language_id);
        $(currentID).style.fontWeight = "bold";
        $(currentID).style.backgroundColor  = "#ceceff";

        var lang_sections = jQuery("#channel_widgets_"+channel_widget_id+" .lang_section");
        lang_sections.each(function(i, lang_section)
        {
            $(lang_section.id).style.display = "none";

        });
        var currentID1 = "language_sections"+language_id;
         $(currentID1).style.display = "block";
    },

    /**
     * Remove section
     **/
    remove_section: function (channel_widget_id,section_id,language_id)
    {
		var url = '/channel/remove_section';
		var params = {
                section_id:section_id,
                channel_widget_id:channel_widget_id,
                language_id:language_id
            };
        AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onRemoveSectionComplete.bind(this)]));
        
    },

    onRemoveSectionComplete :function (transport,target)
    {
        var channel_widget_id = transport.headerJSON.channel_widget_id;
        var language_id = transport.headerJSON.language_id;
        var section_id = transport.headerJSON.section_id;

        var url = '/channel/load_channel_related_resource_widget';
        
		var params = {
					renderMode: 'update',
					channel_widget_id: channel_widget_id,
                    section_id: section_id,
                    language_id: language_id
				};
        element = $("channel_widgets_"+channel_widget_id);
		//var element = $('channel_widgets_' + channel_widget_id); // The widget's panel to be replaced

	    AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([this.onReloadRelatedResourceWidgetComplete.bind(this)]));
                
    
        /*var lang_allsections = jQuery("#channel_widgets_"+channel_widget_id+" ."+"language"+language_id+"_all_sections");
        console.log(lang_allsections);
        lang_allsections.each(function(i, lang_allsection)
        {
            console.log(i);
            if (i==0)
                {
                    $(lang_allsection.id).style.display = "none";
                }
                else if (i==1)
                    {
                         $(lang_allsection.id).style.display = "block";
                    }
                    else
                        {
                             $(lang_allsection.id).style.display = "none";
                        }

        });*/

    },

    onReloadRelatedResourceWidgetComplete: function(transport, target)
    {
  
        var channel_widget_id = transport.headerJSON.channel_widget_id;
        var language_id = transport.headerJSON.language_id;
        
        e = jQuery('#widget_options_' + channel_widget_id + '_container');
		if(jQuery(e).is(":none")||jQuery(e).is(":hidden"))
			jQuery(e).slideDown();
		else
			jQuery(e).slideUp();

        var lang_tabs = jQuery("#channel_widgets_"+channel_widget_id+" .lang_tab");
        lang_tabs.each(function(i, lang_tab)
        {
            $(lang_tab.id).style.fontWeight = "normal";
            $(lang_tab.id).style.backgroundColor  = "white";

        });
        var currentID = "RD"+language_id;
        $(currentID).style.fontWeight = "bold";
        $(currentID).style.backgroundColor  = "#ceceff";

        var lang_sections = jQuery("#channel_widgets_"+channel_widget_id+" .lang_section");
        lang_sections.each(function(i, lang_section)
        {
            $(lang_section.id).style.display = "none";

        });
        var currentID1 = "language_sections"+language_id;
         $(currentID1).style.display = "block";

    },

     /**
     * Add section
     **/
    add_section: function(channel_widget_id,language_id) 
    {
        var url = '/channel/add_section';
		var params = {
                channel_widget_id:channel_widget_id,
                language_id:language_id
            };
        AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onAddSectionComplete.bind(this)]));
    },

    onAddSectionComplete :function (transport,target)
    {
        var channel_widget_id = transport.headerJSON.channel_widget_id;
        var language_id = transport.headerJSON.language_id;
        var section_id = transport.headerJSON.section_id;

        var url = '/channel/load_channel_related_resource_widget';

		var params = {
					renderMode: 'update',
					channel_widget_id: channel_widget_id,
                    section_id: section_id,
                    language_id: language_id
				};
        element = $("channel_widgets_"+channel_widget_id);

	    AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([this.onReloadRelatedResourceWidget_addsectionComplete.bind(this)]));
    },

    onReloadRelatedResourceWidget_addsectionComplete: function(transport, target)
    {
        var channel_widget_id = transport.headerJSON.channel_widget_id;
        var language_id = transport.headerJSON.language_id;
        var section_id = transport.headerJSON.section_id;

        
        e = jQuery('#widget_options_' + channel_widget_id + '_container');
		if(jQuery(e).is(":none")||jQuery(e).is(":hidden"))
			jQuery(e).slideDown();
		else
			jQuery(e).slideUp();


        var lang_tabs = jQuery("#channel_widgets_"+channel_widget_id+" .lang_tab");
        lang_tabs.each(function(i, lang_tab)
        {
            $(lang_tab.id).style.fontWeight = "normal";
            $(lang_tab.id).style.backgroundColor  = "white";

        });
        var currentID = "RD"+language_id;
        $(currentID).style.fontWeight = "bold";
        $(currentID).style.backgroundColor  = "#ceceff";

        var lang_sections = jQuery("#channel_widgets_"+channel_widget_id+" .lang_section");
        lang_sections.each(function(i, lang_section)
        {
            $(lang_section.id).style.display = "none";

        });
        var currentID1 = "language_sections"+language_id;
         $(currentID1).style.display = "block";

         
        var lang_allsections = jQuery("#channel_widgets_"+channel_widget_id+" ."+"language"+language_id+"_all_sections");

        lang_allsections.each(function(i, lang_allsection)
        {

            if (i==lang_allsections.length-1)
                $(lang_allsection.id).style.display = "block";
            else
                $(lang_allsection.id).style.display = "none";

        });

    },

    /**
     * previous_section
     **/
    previous_section: function(channel_widget_id,pre_section_id,language_id)
    {
        var lang_allsections = jQuery("#channel_widgets_"+channel_widget_id+" ."+"language"+language_id+"_all_sections");

        lang_allsections.each(function(i, lang_allsection)
        {

            if (lang_allsection.id=="section_"+pre_section_id)

                $(lang_allsection.id).style.display = "block";
            else
                $(lang_allsection.id).style.display = "none";

        });
    },
    
    /**
     * previous_section
     **/
    next_section: function(channel_widget_id,next_section_id,language_id)
    {
        var lang_allsections = jQuery("#channel_widgets_"+channel_widget_id+" ."+"language"+language_id+"_all_sections");

        lang_allsections.each(function(i, lang_allsection)
        {
            
            if (lang_allsection.id=="section_"+next_section_id)
                $(lang_allsection.id).style.display = "block";
            else
                $(lang_allsection.id).style.display = "none";

        });
    },

    /**
     *  Save RelatedResourcesChannelWidgetOption
     **/

    saveRelatedResourcesChannelWidgetOption: function(channel_widget_id,resource_widget_option_id)
    {
        if (document.getElementById("resource_title_"+$(resource_widget_option_id)).value=="(No resource selected)")
            alert("Please select a resource.");
        else
            {
                
                var form = $("widget_options_"+channel_widget_id);

                var url = '/channel/save_related_resources_channel_widget_option';

                var params = form.serialize();
                
               

                jQuery.noConflict();
                thisClass = this;
                 jQuery.ajax({
                   type: "POST",
                   url: url,
                   data: params,
                   success: function(msg){

                       if(msg != '')
                           {
                               var jsonT = eval('('+ msg +')');

                               var url = '/channel/load_channel_widget';
                               channel_widget_id = jsonT.channel_widget_id;

                                var params = {
                                    renderMode: 'update',
                                    channel_widgets_id: channel_widget_id
                                };

                                element = $('channel_widgets_' + channel_widget_id); // The widget's panel to be replaced

                                AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([thisClass.onReloadWidgetComplete.bind(thisClass)]));
                           }
                   }
                 });

            }
    },

    /**
     * Update panel(self + related resources panels)
     **/
    update_panel: function(channel_widget_id, language_id, resource_id, widget_name, channel_id)
    {
    	
    	switch(widget_name)
    	{
    		case "web_page":
    	
        		var url = '/channel/update_panel';
				var params = {
		                channel_widget_id:channel_widget_id,
		                language_id:language_id,
		                resource_id:resource_id
		            };
        		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onUpdatePanelComplete.bind(this)]));
        	break;
    		case "media_item":
    	
        		var url = '/channel/update_panel';
				var params = {
		                channel_widget_id:channel_widget_id,
		                language_id:language_id,
		                resource_id:resource_id
		            };
        		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onUpdatePanelComplete.bind(this)]));
        	break;
    		case "slide_show":
    	
        		var url = '/channel/update_panel';
				var params = {
		                channel_widget_id:channel_widget_id,
		                language_id:language_id,
		                resource_id:resource_id
		            };
        		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onUpdatePanelComplete.bind(this)]));
        	break;
    		case "news_headlines":
    	
        		var url = '/widget/index/';

				
				var language = language_id;
					
				var params = {
					renderMode: 'update',
					channel_widgets_id: channel_widget_id,
					id: channel_id,
					language: language
				};

				
				AS4Shell.getInstance().ajaxUpdate(url, params, $('news_headlines_'+channel_widget_id), null, {showIndicator: false});
        	break;
    		case "all_resources":
    	
        		var url = '/widget/index/';

				
				var language = language_id;
					
				var params = {
					renderMode: 'update',
					channel_widgets_id: channel_widget_id,
					id: channel_id,
					language: language
				};

				
				AS4Shell.getInstance().ajaxUpdate(url, params, $('all_resources_'+channel_widget_id), null, {showIndicator: false});
        	break;
    		case "whats_new":
    	
        		var url = '/widget/index/';

				
				var language = language_id;
					
				var params = {
					renderMode: 'update',
					channel_widgets_id: channel_widget_id,
					id: channel_id,
					language: language
				};

				
				AS4Shell.getInstance().ajaxUpdate(url, params, $('whats_new_'+channel_widget_id), null, {showIndicator: false});
        	break;
    		case "whats_popular":
    	
        		var url = '/widget/index/';

				
				var language = language_id;
				
				var params = {
					renderMode: 'update',
					channel_widgets_id: channel_widget_id,
					id: channel_id,
					language: language
				};

				
				AS4Shell.getInstance().ajaxUpdate(url, params, $('whats_popular_'+channel_widget_id), null, {showIndicator: false});
        	break;
    	}
    },
    
    onUpdatePanelComplete: function (transport)
    {
        var all_updated_channel_widget_ids = transport.headerJSON.all_updated_channel_widget_ids;
        var translated_resource_id = transport.headerJSON.translated_resource_id;
     
     // console.log(all_updated_channel_widget_ids.length);
     //   for (var i in all_updated_channel_widget_ids)
        for (i = 0; i < all_updated_channel_widget_ids.length; i++)
        {
        	all_updated_channel_widget_id = all_updated_channel_widget_ids[i];
        	
           // element = $('channel_widgets_' + all_updated_channel_widget_ids[i]); // The widget's panel to be replaced
            element = $('channel_widgets_' + all_updated_channel_widget_id); // The widget's panel to be replaced
            var url = '/channel/load_channel_widget';
            var params = {
                renderMode: 'update',
                //channel_widgets_id: all_updated_channel_widget_ids[i]
                channel_widgets_id: all_updated_channel_widget_id,
                translated_resource_id: translated_resource_id
            };
            AS4Shell.getInstance().ajaxUpdate(url, params, element, $A([this.onReloadWidgetComplete.bind(this)]));
        }
    },

	/**
	* Remove the selected images from the slide show image list. Also remove them from the hidden id list
	**/
	removeOptions: function()  
	{
		var i;
		var selectbox = $("images_list");

			
		for(i=selectbox.options.length-1;i>=0;i--)
		{
			if(selectbox.options[i].selected)
			{
				
				selectedId = selectbox.options[i].value;
				$("images_id_list").value = $("images_id_list").value.replace(eval("/"+selectedId+"/gi"),'');
				$("images_id_list").value = $("images_id_list").value.replace("||",'|');
				selectbox.remove(i);
			}
		}
	},
	

	/**
	*	Add new filter type 
	**/
	
	addFilterType: function(widget_id)
	{

		jQuery("#selected_resource_filters_" + widget_id).attr("value","");
		jQuery("#filter_selector_list_" + widget_id + " option").each(function(i, opt)
		{
			
			if(jQuery(opt).attr("selected") == true)
			{
				
				selectedId = jQuery(opt).attr("value");
				if(selectedId > "0")
				{
					jQuery("#selected_resource_filters_" + widget_id).attr("value",jQuery("#selected_resource_filters_" + widget_id).attr("value")+"|"+selectedId);
				}
			}
		});
		var inputString = jQuery("#selected_resource_filters_" + widget_id).attr("value");
		if(inputString)
			jQuery("#selected_resource_filters_" + widget_id).attr("value",inputString.substr(1,inputString.length));
	},
	/**
	*	Add new folder to rss list 
	**/
	
	addRSSFolder: function(widget_id)
	{

		jQuery("#rss_folders_" + widget_id).attr("value","");
		jQuery("#rss_folders_list_" + widget_id + " option").each(function(i, opt)
		{
			
			if(jQuery(opt).attr("selected") == true)
			{
				
				selectedId = jQuery(opt).attr("value");
				if(selectedId > "0")
				{
					jQuery("#rss_folders_" + widget_id).attr("value",jQuery("#rss_folders_" + widget_id).attr("value")+"|"+selectedId);
				}
			}
		});
		var inputString = jQuery("#rss_folders_" + widget_id).attr("value");
		if(inputString)
			jQuery("#rss_folders_" + widget_id).attr("value",inputString.substr(1,inputString.length));
	},	
	
	/**
	*	Add new folder to rss list 
	**/
	
	addRSSFolder: function(widget_id)
	{

		jQuery("#rss_folders_" + widget_id).attr("value","");
		jQuery("#rss_folders_list_" + widget_id + " option").each(function(i, opt)
		{
			
			if(jQuery(opt).attr("selected") == true)
			{
				
				selectedId = jQuery(opt).attr("value");
				if(selectedId > "0")
				{
					jQuery("#rss_folders_" + widget_id).attr("value",jQuery("#rss_folders_" + widget_id).attr("value")+"|"+selectedId);
				}
			}
		});
		var inputString = jQuery("#rss_folders_" + widget_id).attr("value");
		if(inputString)
			jQuery("#rss_folders_" + widget_id).attr("value",inputString.substr(1,inputString.length));
	},	
	
	/**
	*	Add new filter type 
	**/
	
	addSelectedFolder: function(cwid)
	{
		
		jQuery("#selected_channels_" + cwid).attr("value","");
		jQuery("#channel_selector_list_" + cwid + " option").each(function(i, opt)
		{
			
			if(jQuery(opt).attr("selected") == true)
			{
				
				selectedId = jQuery(opt).attr("value");
				if(selectedId > "0")
				{
					jQuery("#selected_channels_" + cwid).attr("value",jQuery("#selected_channels_" + cwid).attr("value")+"|"+selectedId);
				}
			}
		});
		var inputString = jQuery("#selected_channels_" + cwid).attr("value");
		if(inputString)
			jQuery("#selected_channels_" + cwid).attr("value",inputString.substr(1,inputString.length));

	},
	
	updateFormIntroduction: function(cwid, opid, value, resourceTitle)
	{
		//opid = opid.replace("_intro_webpage", "");
		//$('widget_options_' + cwid).down('input[id="options[' + opid +']"]').value = id;
		
		var title = $("options_"+opid+"_title_"+cwid);
		var intro_text = jQuery("#options_"+opid+"_intro_text_"+cwid);
		var webpage = jQuery("#options_"+opid+"_webpage_"+cwid);
		var resource_title = jQuery("#resource_title_"+opid+"_intro_webpage_"+cwid);
		var option = jQuery("#options_"+opid+"_"+cwid);
		
		
		if(value != false) 
			webpage.attr("value", value);
		
		if(resourceTitle != false) 
			resource_title.attr("value", resourceTitle);
		
		var optionValue = '{"title":'+JSON.stringify(title.value)+', "intro_text":'+JSON.stringify(intro_text.val())+',"webpage":"'+webpage.attr("value")+'"}';
		
		option.attr("value", optionValue);
		
		
	},
	
	updateSectionsShown: function(opid, cwid)
	{
		var option = $("widget_options_3911_general options["+opid+"]");
		
		option = jQuery("#options_"+opid+"_"+cwid);
		
		option.attr("value", "");
		
		var newvalue = "";
		
		$j("input.showFormSection"+opid+"_"+cwid).each(function(i, ele)
		{
			if(ele.checked)
			{
				newvalue += ele.value+","; 
				
			}
		});
		
		option.attr("value", newvalue);
	},
	
	updateFormEmailOption: function(cwid, opid)
	{
		
		var option = jQuery("#options_"+opid+"_"+cwid);
		var subject = jQuery("#options_"+opid+"_subject_"+cwid);
		var address = jQuery("#options_"+opid+"_address_"+cwid);
		var message = jQuery("#options_"+opid+"_message_"+cwid);
		
		option.attr("value", "");
		
		var optionValue = '{"subject":'+JSON.stringify(subject.attr("value"))+', "message":'+JSON.stringify(message.attr("value"))+',"address":'+JSON.stringify(address.attr("value"))+'}';
		
		option.attr("value", optionValue);
	},
	
	updateConfirmationOption: function(cwid, opid)
	{
		var option = jQuery("#options_"+opid+"_"+cwid);
		var option1 = $("options_"+opid+"_conoption_message_"+cwid);
		var option2 = $("options_"+opid+"_conoption_redirect_"+cwid);
		var message = jQuery("#options_"+opid+"_message_"+cwid);
		var url = jQuery("#options_"+opid+"_url_"+cwid);

		option.attr("value","");

		if(option1.checked === true)
		{
			option.attr("value", '{"option":"1", "value":'+JSON.stringify(message.attr("value"))+'}'); 
		}
		else if(option2.checked === true)
		{
			option.attr("value", '{"option":"2", "value":'+JSON.stringify(url.attr("value"))+'}'); 
		}
	},
	
	updateFormDateOption: function(cwid, opid)
	{
		var option = $("options_"+opid+"_"+cwid);
		var creation = $("options_"+opid+"_usedate_creation_"+cwid);
		var publish = $("options_"+opid+"_usedate_publish_"+cwid);
		var display = $("options_"+opid+"_display_"+cwid);
		var text = $("options_"+opid+"_text_"+cwid);
		
		var textpositiontop = $("options_"+opid+"_textposition_top_"+cwid);
		var textpositionright = $("options_"+opid+"_textposition_right_"+cwid);
		var textpositionbottom = $("options_"+opid+"_textposition_bottom_"+cwid);
		var textpositionleft = $("options_"+opid+"_textposition_left_"+cwid);
		
		var datepositionbefore = $("options_"+opid+"_dateposition_before_"+cwid);
		var datepositionafter = $("options_"+opid+"_dateposition_after_"+cwid);
				
		
		if(display.checked === true)
		{
			var displaydate = "true";
		}
		else
		{
			var displaydate = "false"
		}
		
		if(creation.checked === true)
		{
			var usedate = "creation";
		}
		else if(publish.checked === true)
		{
			var usedate = "publish";
		}
		
		
		if(textpositiontop.checked === true)
		{
			var textposition = "top";
		}
		else if(textpositionright.checked === true)
		{
			var textposition = "right";
		}
		else if(textpositionbottom.checked === true)
		{
			var textposition = "bottom";
		}
		else if(textpositionleft.checked === true)
		{
			var textposition = "left";
		}
		
		
		if(datepositionbefore.checked === true)
		{
			var dateposition = "before";
		}
		else if(datepositionafter.checked === true)
		{
			var dateposition = "after";
		}
		
		var value = '{"date":"'+usedate+'", "display":"'+displaydate+'", "text":'+JSON.stringify(text.value)+', "text_position": "'+textposition+'", "date_position": "'+dateposition+'"}';
		
		option.value = value;	
	},
	
	updateFormRecordCountOption: function(cwid, opid)
	{
		var option = $("options_"+opid+"_"+cwid);
		
		var display = $("options_"+opid+"_display_"+cwid);
		var show_pagination = $("options_"+opid+"_show_pagination_"+cwid);
		var records_per_page = $("options_"+opid+"_records_per_page_"+cwid);
		var text = $("options_"+opid+"_text_"+cwid);
		
		var textpositiontop = $("options_"+opid+"_textposition_top_"+cwid);
		var textpositionright = $("options_"+opid+"_textposition_right_"+cwid);
		var textpositionbottom = $("options_"+opid+"_textposition_bottom_"+cwid);
		var textpositionleft = $("options_"+opid+"_textposition_left_"+cwid);
		
		var countpositionbefore = $("options_"+opid+"_countposition_before_"+cwid);
		var countpositionafter = $("options_"+opid+"_countposition_after_"+cwid);
				
		
		if(display.checked === true)
		{
			var displaycount = "true";
		}
		else
		{
			var displaycount = "false"
		}
		
		if(show_pagination.checked === true)
		{
			var show_pagination = "true";
		}
		else
		{
			var show_pagination = "false"
		}
		
		
		
		if(textpositiontop.checked === true)
		{
			var textposition = "top";
		}
		else if(textpositionright.checked === true)
		{
			var textposition = "right";
		}
		else if(textpositionbottom.checked === true)
		{
			var textposition = "bottom";
		}
		else if(textpositionleft.checked === true)
		{
			var textposition = "left";
		}
		
		
		if(countpositionbefore.checked === true)
		{
			var countposition = "before";
		}
		else if(countpositionafter.checked === true)
		{
			var countposition = "after";
		}
		
		var value = '{"display":"'+displaycount+'", "text":'+JSON.stringify(text.value)+', "text_position": "'+textposition+'", "count_position": "'+countposition+'", "show_pagination":"'+show_pagination+'", "records_per_page":"'+records_per_page.value+'"}';
		
		option.value = value;	
	},
		
	removeIntroWebpage: function(thisele)
	{
		$j(thisele).next().val(""); // select the input with th4e webpage id
		$j(thisele).val("No Webpage selected"); 
		
		
	},
	
	displayWidgetOptionTab: function(className, selectedId, tab)
	{
		jQuery(".widget_options_tabs li").removeClass("selected");
		jQuery(tab).addClass("selected");
		
		$j("."+className).hide("fast");
		
		$j("#"+selectedId).show("fast");
	}
});


AS4WidgetsLayoutEditor.WIDGETS_HEADER_COLUMN_INDEX = 10;
AS4WidgetsLayoutEditor.WIDGETS_FOOTER_COLUMN_INDEX = 20;
