/**
 * Javascript code for handling the personalization options.
 *	
 * @author lwielink<lwielink@refdag.nl>
 * @date 2009/06/27
 * @lastchanged 2009/10/13
 */			 			 			 			 	    	
var Personalization = {


	/**
	 * Config items
	 */				 				
	config			: {
		'selectedItemsContainer'	: 'div.select_wrapper',
		'warningsPrefDivId'			: 'div#warnings_pref_div_id',
		'successPrefDiv'			: 'success_pref_div_id',
		'ajaxServer'				: '/ajax',
		'buttons'					: {
			'move_up'	: 'move_up_buttton.gif',
			'move_down' : 'move_down_button.gif',
			'delete	'	: 'delete_button.gif'
		},
		'successSaveWarningHideInterval' : 5000
	},
	
	warnings	: {
		'save_succesfull' 					: {
			'homepage' 	: 'Uw voorkeuren zijn succesvol opgeslagen',
			'newsletter': 'U ontvangt vanaf vandaag elke werkdag uw aangepaste nieuwsbrief van het Reformatorisch Dagblad'
		},
		'no_items_selected' 				: 'U dient wel een rubriek te selecteren',
		'not_possible_remove_static_options': 'Het is niet mogelijk om deze rubriek te verwijderen',
		'not_possible_to_move' : 'Het is niet mogelijk deze rubriek van positie te veranderen',
		'not_possible_to_move_up' : 'Het is niet mogelijk om deze categorie verder naar boven te verplaatsen'
	},
	
	/* the selected category id */
	selectedCategoryId	: null,
	
	/* the rel of the selected category */
	selectedCategoryRel : null,
	
	/* the selected category classname */
	selectedCategoryClassName : null,
	
	/* detect if the user has already clicked */
	clicked				: false,
	
	/* not movable categories */
	notMovableCategories : [
		"hoofdpunten"
	],
	
	/** 
	 * Active selected category id
	 * 
	 * @id
	 */				 				 				 				
	selectedCategoryId	: null,
	
	/**
	 * Get a config item from the config attribute object
	 * 
	 * @return string or object
	 */				 				 				 				
	getConfigItem	: function(element) {
		if (arguments.length == 2)
			return this.config[element][arguments[1]];
		return this.config[element];
	},
	
	
	/**
	 * Initialize the whole personalization application
	 * - set on all checkboxes on the left side an onclick event
	 * - set the onclicks events on the buttons on the right side				 				 
	 * 
	 * @return
	 */
	 
	init			: function() {
		var pObject = this;	
		jQuery('table.categories_wrapper input[type="checkbox"]').each(function(it, element) {
			jQuery(element).bind('click', function() {
				if (this.checked && !pObject.clicked) {
					pObject.clicked = true;
					var element = this;
		     		// we can create an element in the box of step2 where the user can define the priority of this element
		     		if (jQuery(pObject.getConfigItem('selectedItemsContainer')).html().search('Selecteer een rubriek') > 0)
		     			jQuery(pObject.getConfigItem('selectedItemsContainer')).html("<ol></ol>");
					jQuery(pObject.getConfigItem('selectedItemsContainer') + ' ol').append('<li id="list_item_' + element.id.replace('add_id_','') + '"><a id="'+element.id.replace('add','select') +'" href="#" onclick="return Personalization.selectItemForSort(this);" >' + element.title + '</a></li>');
					pObject.fixItemsHeight();
					pObject.clicked = false;
					this.disabled = 'disabled';
				} else {
					return false;
				}
			});
		});
		
		// set the onclicks events on the buttons on the right side
		jQuery('div.sort_wrapper img').each(function(it, element) {
			jQuery(this).bind('click', function() {
				var listSize = jQuery(pObject.getConfigItem('selectedItemsContainer') + ' ol li').size();
				if (pObject.selectedCategoryId == null || parseInt(pObject.selectedCategoryId) < 0) {
					/* no categories selected. Give a warning */
					return pObject.displayWarning(pObject.warnings.no_items_selected);
				}
				var id = this.id;
				if(id == 'up' || id == 'down') {
					if (listSize < 2) // there's only one item. Nothing to re-order
						return false;
					/* check if item may moved */
					if (jQuery.inArray(pObject.selectedCategoryRel, pObject.notMovableCategories) != -1) {
						return pObject.displayWarning(pObject.warnings.not_possible_to_move);
					}
					// define current place in the list
					jQuery(pObject.getConfigItem('selectedItemsContainer') + ' ol li').each(function(iteration) {
						var currentIndex = 0;
						if (this.id.replace('list_item_','') == pObject.selectedCategoryId.replace('select_id_','')) {
							currentIndex = iteration+1;
							if (id == 'up') {
								if (currentIndex == 1)  // listitem already on the top of the list
									return false;
								// insert the item before the parent..check if the parent may be moved to one item below
								if (jQuery.inArray(jQuery(this).prev().find('a').attr('rel').toLowerCase(), pObject.notMovableCategories) != -1) {
									return pObject.displayWarning(pObject.warnings.not_possible_to_move_up);
								} 
								jQuery(this).prev().before(this);
							} else if (	id == 'down') {
								if (currentIndex == listSize)  // listitem already on the bottom of the list
									return false;
								// insert the item after the nextSibling
								jQuery(this).next().after(this);	
							}
						}
					});
				} else if (this.id == 'delete') {
					// it's not possible no remove one of the static categories which are defined in CM
					if (pObject.selectedCategoryClassName == "pref_static_option")
						return pObject.displayWarning(pObject.warnings.not_possible_remove_static_options);
					jQuery('a#' + pObject.selectedCategoryId).parent().remove();
					// uncheck the appropriate button
					jQuery('input#' + pObject.selectedCategoryId.replace('select','add')).attr({'checked':false, 'disabled':false});
					// set active categoryId to null
					pObject.selectedCategoryId  = null;
					// set text if needed
					if (jQuery(pObject.getConfigItem('selectedItemsContainer') + ' ol li').size() < 1) 
						jQuery(pObject.getConfigItem('selectedItemsContainer')).html('<p>Selecteer een rubriek</p><ol></ol>');
				}
				return false;
			});
		});
		
	},
	
	/**
	 * Fix the height of the two different columns
	 * 
	 * @return boolean
	 */
	fixItemsHeight		: function() {		
		if(jQuery('div.step_one_categories').height() > jQuery('div.step_twothree_categories').height())
			return jQuery('div.step_twothree_categories').css('height', jQuery('div.step_one_categories').height()-7);
		return jQuery('div.step_one_categories').css('height', jQuery('div.step_twothree_categories').height());
	},
	
	/**
	 * Select the selected category so that the category can be managed
	 * 
	 * @return
	 */
	selectItemForSort	: function(element) {
		jQuery(this.getConfigItem('selectedItemsContainer') + ' ol li').attr('class','in_active');
		jQuery(element.parentNode).attr('class', 'active');
		this.selectedCategoryId = element.id;
		this.selectedCategoryClassName = element.className;
		this.selectedCategoryRel = jQuery(element).attr('rel').toLowerCase();
		return false;
	},
	
	
	/**
	 * Save the selected and ordered categories
	 * 
	 * @return
	 */				 				 				 				
	save				: function(wpref)
	{
		var selectedIds = [];

		jQuery(this.getConfigItem('selectedItemsContainer') + ' ol li').each(function(it, el) {
			selectedIds.push(el.id.replace('list_item_', ''));
		});
		if (selectedIds.length > 0) {
			var pObject = this;
			var dObject;
			
			dObject = "action=updateUser&personalHome=true&homePref=" + selectedIds.join(',').replace(/-/g,'.');
			if (wpref == 'newsletter_prefs') {
				dObject = "action=updateUser&personalNews=true&newsPref=" + selectedIds.join(',').replace(/-/g,'.');
			}
			jQuery.ajax(
				{
		   			type: "POST",
			   		url: pObject.getConfigItem('ajaxServer'),
			   		data: dObject,
			   		success: function(msg) {
			     		// save succesfully'
						if (wpref == 'homepage_prefs')
							return pObject.displayWarning(pObject.warnings.save_succesfull.homepage);
						return pObject.displayWarning(pObject.warnings.save_succesfull.newsletter);
				   } 
				 }
			);
		}
		return false;
	},
	
	/**
	 *  Display a warning which informs the visitor about his action
	 */
	displayWarning	: function(text)
	{
		var succesWDiv = '<div id="'+this.getConfigItem('successPrefDiv')+'">'+text+'</div>';
		jQuery(this.getConfigItem('warningsPrefDivId')).show('fast');
		jQuery(this.getConfigItem('warningsPrefDivId')).html(succesWDiv);
		setTimeout(function() {
			jQuery('div#'+Personalization.getConfigItem('successPrefDiv')).hide('fast');
		}, Personalization.getConfigItem('successSaveWarningHideInterval'));
		return false;
	}
	
};
