
/**
 * Helper for document.getElementById
 * 
 * @param domid
 * @return
 */
function $(domid) {
	return document.getElementById(domid);
}

/**
 * ajoute un événement sans écraser l'existant.
 * 
 * @param obj
 * @param evType
 * @param fn
 * @param capt
 * @return
 */
function addEvent(obj, evType, fn, capt) {

	if (!obj) {
		return false;
	}

	if (obj.addEventListener) { // NS6+
		obj.addEventListener(evType, fn, capt);
	} else {
		if (obj.attachEvent) {
			obj.attachEvent("on" + evType, fn) // IE 5+
		} else {
			return false;
		}
	}
}

/**
* Makes the links ajax calls for the documents 'Vidéos de votre choix' in the edit videos mode
* @return
*/
function ajaxifyLinksEditVideos() {
	elements = document.getElementsByTagAndClassName('A', 'ajaxifyEditVideos');

	for (i = 0; i < elements.length; i++) 
	{	
		elements[i].onclick = captureAjaxifiedLinkEditVideos;
	}
}


/**
* Function triggered when a link is clicked in the edit videos mode
* of the documents 'Vidéos de votre choix'
*/
function captureAjaxifiedLinkEditVideos(e) {
	el = getSourceFromEvent(e);
	target = 'default_ajax_container';
	url = '';

	if (el && el.tagName == 'IMG') {
		el = el.parentNode;
	}

	if (el && el.tagName == "A") {
		url = el.href;
		if (el.rel) {
			target = el.rel;
		}
	}

	if (url.indexOf('?') != -1) {
		url += '&ajax=1';
	} else {
		url += '?ajax=1';
	}
	
	captureSelectedVideos();
	
	url = url + "&selected_ids=" + getSelectedIds();
	
	AjaxGetData(url, receive_ajax, $(target));

	return false;
}


function setElementClass(element, class_name, is_on)
{
	
	if ((is_on && element.className.indexOf(class_name) == -1) || (is_on && element.className.indexOf(class_name) >= 1) )
	{
		element.className = element.className + ' ' + class_name;
	} else
	{
		var classes = element.className.split(' ');
		var newClasses = "";
		
		for (var i = 0; i < classes.length; i++)
		{
			if (classes[i] != class_name)
			{
				newClasses += classes[i] + " ";
			}
			
			element.className = newClasses;
		}
	}
}

function checkSelectedVideos ()
{
	var tags = document.getElementsByName('selected_id');
	
	for (var i = 0; i < tags.length; i++) 
	{
		if (!isNaN(tags[i].value) && selected_video_ids[tags[i].value])
		{
			setElementClass($('td_' + tags[i].value), 'selected', true);
			tags[i].setAttribute('checked', 'true');
		}
	}
}

function captureSelectedVideos(e)
{
	if (typeof selected_video_ids == 'undefined')
	{
		selected_video_ids = new Array();
	}
	
	var tags = document.getElementsByName('selected_id');
	
	for (var i = 0; i < tags.length; i++) 
	{
		if (!isNaN(tags[i].value))
		{
			selected_video_ids[tags[i].value] = tags[i].checked;
		}
	}
}

function getSelectedIds()
{
	captureSelectedVideos();
	var str = '';

	for (var i in selected_video_ids)
	{
		if (selected_video_ids[i] === true)
		{
			str += i + ',';
		}
	}
	
	return str.substr(0, str.length - 1);
}

function processVideoIds (elements)
{
	var ids = document.getElementById('video_ids');
	ids.value = elements;
	
	var nb = document.getElementById('nb_of_selected_videos');
	nb.innerHTML = (elements != '') ? elements.split(',').length : 0;
}


 /**
 * Returns the elements associated to a class
 * 
 * @param string tag name
 * @param string class name
 * @return array
 */
document.getElementsByTagAndClassName = function(tagName, className) {
	var retnode = [];
	var myclass = new RegExp('\\b' + className + '\\b');
	var elem = this.getElementsByTagName(tagName);

	for ( var i = 0; i < elem.length; i++) {
	var classes = elem[i].className;
	if (myclass.test(classes)) {
		retnode.push(elem[i]);
	}
	}
	return retnode;
}

function checkUncheckAllVideos(value)
{
	var tags = document.getElementsByName('selected_id');
	
	if (false ==  value){
		
		for (var i = 0; i < tags.length; i++) 
		{
			setElementClass($('td_' + tags[i].value), 'selected', false);
			tags[i].setAttribute('checked', 'false');
			tags[i].checked = false;
		}
	}else{
		
		for (var i = 0; i < tags.length; i++) 
		{	
			setElementClass($('td_' + tags[i].value), 'selected', true);
			tags[i].setAttribute('checked', 'true');
			tags[i].checked = true;
		}
	}
	
}


function promoRefreshCategories()
{
	if(categoriesBox.disabled == false || typeof categoriesBox.disabled == 'undefined'){
		archiveId = document.getElementById('archives_box').value;
		categoriesBox = document.getElementById('cat_select');
		AjaxGetData("index.php?module=smartmovies_flashplayer&view=get_categs&archive_id="+ archiveId + "&ajax=1", receive_ajax, categoriesBox);
	}
}

function promoSetCategoriesEnabled()
{
	typesBox = document.getElementById('types_box');
	categoriesBox = document.getElementById('categories_box');
	
	if (typesBox.value == "random")
		categoriesBox.disabled = false;
	else
		categoriesBox.disabled = true;
}

function confirmAndGo(message, url)
{
	// TODO: would be nicer to be able to pass post parameters, because some actions like
	// deleting an item change the state of the database

	if (confirm(message))
		window.location = url;
}

function prepareFormOnLoad()
{
	// adjust some inputs that are not directly read from the back end... Ex. type de vente is a dropdown
	// with "abonnement" and "abonnement et micropaiement" but in fact it is received as two hidden inputs "is_subscribe" and "is_micropayment"
	if (document.form.is_censored.value == 1)
		document.getElementById('censored_check').checked = true;

	var linktypevalue;
	if (document.form.is_link_selcat.value == 1)
		linktypevalue = "selcat,";
	else
		linktypevalue = "txtcat,";
	if (document.form.is_link_selpage.value == 1)
		linktypevalue += "selpage";
	else
		linktypevalue += "txtpage";
	
	document.getElementById('link_type').value = linktypevalue;
}

function prepareFormOnSubmit()
{

	// force to send a value even if a checkbox is unchecked
	if (document.getElementById('censored_check').checked)
		document.form.is_censored.value = 1;
	else
		document.form.is_censored.value = 0;
	
	// convert the select into 4 hidden inputs for link type	
	var linktype = document.getElementById('link_type').value;

	if (linktype.match(/selcat/))
	{
		document.form.is_link_selcat.value = 1;
		document.form.is_link_txtcat.value = 0;
	}
	else
	{
		document.form.is_link_selcat.value = 0;
		document.form.is_link_txtcat.value = 1;
	}

	if (linktype.match(/selpage/))
	{
		document.form.is_link_selpage.value = 1;
		document.form.is_link_txtpage.value = 0;
	}
	else
	{
		document.form.is_link_selpage.value = 0;
		document.form.is_link_txtpage.value = 1;
	}
}

function previewDocument(mb_url)
{
	document.form.action = mb_url + "index.php?module=videos&view=preview_doc";
	document.form.submit();
}

function updateColorTextfield(elmt) {
	if(elmt!=undefined){
		if (elmt.value.match(/^#[0-9|a-f|A-F]{6}$/)) elmt.style.backgroundColor = elmt.value;
		else elmt.style.backgroundColor = '#ffffff';
	}

}

function loadColor(colorFieldsTab) {
	for (i = 0; i < colorFieldsTab.length; i++) {
		updateColorTextfield(document.getElementById(colorFieldsTab[i]));
	}
}

function displayBanners(url, size){

	var divs = document.getElementsByClassName('divSize');
	var browser = navigator.appVersion;
	var isIE6 = browser.indexOf('MSIE 6.0');
	var isOtherIE = browser.indexOf('compatible; MSIE 7.0');
	
	for(var i = 0 ; i < divs.length ; i++){
		if(divs[i].id == 'div_' + size){
			// For IE6, resize the div's height
			// TODO : Needs to be changed when the banners will be set from the Intranet
			if(isIE6 > -1 && !isOtherIE){
				switch(size){
					case '120-600' :
						document.getElementById('page').style.height = '1610px';
					break;
					
					case '120-60' :
						document.getElementById('page').style.height = '100%';
					break;
					
					case '480-60' :
					default:
						document.getElementById('page').style.height = '1470px';
					break;
				}
			}
			document.getElementById(divs[i].id).style.display = 'block';
		}else{
			document.getElementById(divs[i].id).style.display = 'none';
		}
	}
	
	// Updates hte links
	var doc_id = document.getElementById('document_id').value;
	generateBannerLink(url, doc_id);
}

function generateBannerLink(url, doc_id){
	// function modified to rely on an array that is created at runtime from the xml
	// so that we can figure out what kind of document we are creating a banner for:
	//   nurl = the non mb url to use for links
	//   mburl = the mb url to use for links
	//   document_types[] is an associative array of id->type pairs
	//   	document_types['d-12'] = 8 -- is an example of a redirection document.
	//   
	var selectedSize = document.getElementById('banners_sizes').value;
	var tmp = selectedSize.split('-');
	
	if(tmp.length > 1){
		var width = tmp[0];
		var codes = document.getElementsByClassName('generated-code size-' + width);
		
		for(var i = 0 ; i < codes.length ; i++){
			var tmp = codes[i].id.split('_');
			var bannerId = tmp[1];
			var imgId = 'img_' + bannerId;
			var src = document.getElementById(imgId).src;
			var code = codes[i].innerHTML;
			
			if(doc_id == 'none'){
				alert('Veuillez sélectionner un document');
				return(false);
			}else{
				if(document_types['d-' + doc_id] == 8) {
					//redirection document, use the regular url
					url = nurl;
				} else {
					url = mburl;
				}
				var url2 = url.replace('\/d1\/', '\/d' + doc_id + '\/');
				var newUrl = url2 + '?banner_id=' + bannerId;
			}
			
			var newCode = '<pre>&lt;a href="' + newUrl + '"&gt;&lt;img src="' + src + '" /&gt;&lt;/a&gt;</pre>';
			
			document.getElementById(codes[i].id).innerHTML = newCode;
		}
	}
}

function openDocumentForm(module, site_id, document_id, document_type, form_type){
	self.parent.document.location = 'index.php?module=' + module + '&view=addedit_document_' + form_type + '&site_id=' + site_id + '&document_id=' + document_id + '&document_type=' + document_type;
	self.parent.tb_remove();
}

function showHideDocs(id, site_id, url_base){
	var display = document.getElementById(id).style.display;
	
	if(display == 'none'){
		document.getElementById(id).style.display = 'block';
		document.getElementById('btn_close_group_' + site_id).src = url_base + 'images/webmasters/gestion/close-group-idle.png';
	}else{
		document.getElementById(id).style.display = 'none';
		document.getElementById('btn_close_group_' + site_id).src = url_base + 'images/webmasters/gestion/open-group-idle.png';
	}
}

// toggle visibility of an element by its class name
function showhideByClass(classname, display) {
	node = document;
	tag = '*';
	var classElements = new Array();
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)" + classname + "(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];

			if(display != null) {
				els[i].style.display=display;
			} else {
				if(els[i].style.display=='none') {
					 els[i].style.display='';
				} else {
					els[i].style.display='none';
				}
			}
			
			j++;
		}
	}
}

/**
 * Show an hidden element or hide a displayed element
 * 
 * @param DOMelement element
 */
function toggleVisibility(element) {
	
	if(element.style && element.style.display == 'none') {
		show(element);
	} else {
		hide(element);
	}
}

/**
 * Show a DOM element
 * 
 * @param DOMelement e
 */
function show(e){
	if(e && e.style) e.style.display="block";
}

/**
 * Hide a DOM element
 * 
 * @param DOMelement e
 */
function hide(e){
	if(e && e.style) e.style.display="none";
}

/**
 * Show or hide the parameters for Individuals or Companies
 */
function toggleCompany_Individual() {
	if($('is_company').checked) {
		showhideByClass('individual_details',	'none');
		showhideByClass('company_details',		'');
	} else {
		if(document.getElementById('first_name').value == 'Aucun'){
			document.getElementById('first_name').value = '';
		}
		if(document.getElementById('last_name').value == 'Aucun'){
			document.getElementById('last_name').value = '';
		}
		showhideByClass('individual_details',	'');
		showhideByClass('company_details',		'none');
	}
}



/**
 * function used to restore the default value 
 * for coulours in thumb personalisation
 *
 */
function restoreInput(element, defaultValue) {
    if (element.value == '')
	element.value = defaultValue;
}

/**
 * function used to clean the default value 
 * for coulours in thumb personalisation
 *
 */
function cleanInput(element, defaultValue) {
    if (element.value == defaultValue)
	element.value = '';

}

/**
 * function used to empty the field for colors 'Ecrivez votre code ici'
 * thumbs in Droselia3
 */
function emptyField(field){
	document.getElementById(field). value = '';
}

/**
 * checks if a color was choose 
 * if not restore the value by default
 * clean the sample color if there is any
 */
function checkSelection(field){
	if(document.getElementById(field). value == ''){
		// default value for this field "Ecrivez votre code ici"
		document.getElementById(field). value = 'Ecrivez votre code ici';
	}

}

/**
 * Used in the droselia3 profil form the are some special conditions
 * when a change his country
 */

function change_country() { 

	document.getElementById('country_changed').value= 1;
	
	if (   document.getElementById('payment_method').value 	     != 'transfer'
		&& document.getElementById('webmaster_country_id').value != '40'     ){
			//force payment_method to transfer if the country is not CANADA
			
			document.getElementById('payment_method').value= 'transfer';
	}else{
		if (null!=document.getElementById('bank_country_id'))
			document.getElementById('bank_country_id').value=document.getElementById('webmaster_country_id').value;
		if (null!=document.getElementById('webmasterbank_bank_name'))
			document.getElementById('webmasterbank_bank_name').value= '';
	}
} 
function previewDocumentMB(form, url) {
	
	oldaction = form.action;
	
	form.action	= url;
	form.target	= '_target';
	form.submit();

	form.action	= oldaction;
	form.target	= '';
	
	return false;
}

/**
 * Catches the browser's events
 * 
 * @return DOM Element
 */
function getSourceFromEvent(e) {
	if (e && e.target) {
		// Not IE
		return e.target;
	} else {
		// IE
		return window.event.srcElement;
	}
}

/**
 * Remove focus from the element that fired the event
 */
function removeFocus(e) {
	el = getSourceFromEvent(e);
	if (el.blur) {
		el.blur();
	}
}

/**
 * Switch image to 'over' mode (for rollover effects)
 */
function imageIdleToOver(e) {
	el = getSourceFromEvent(e);

	if (el && (el.tagName == "IMG" || el.tagName == "INPUT")
			&& el.src.indexOf('-idle') != -1) {
		el.src = el.src.replace('-idle', '-over');
	}

}

/**
 * Switch image to 'idle' mode (for rollover effects)
 */
function imageOverToIdle(e) {
	el = getSourceFromEvent(e);

	if (el && (el.tagName == "IMG" || el.tagName == "INPUT")
			&& el.src.indexOf('-over') != -1) {
		el.src = el.src.replace('-over', '-idle');
	}
}

/**
 * Get all IMG and INPUT elements with class 'rollover' and set the proper events on them
 * to have rollover effects 
 */
function initRollover() {
	elements = document.getElementsByTagAndClassName('IMG', 'rollover');

	for (i = 0; i < elements.length; i++) {
		
		addEvent(elements[i], "mouseover", imageIdleToOver);
		addEvent(elements[i], "mouseout", imageOverToIdle);
		
		if (elements[i].parentNode && elements[i].parentNode.tagName == 'A') {
			addEvent(elements[i].parentNode, "focus", removeFocus);
		}
	}

	elements = document.getElementsByTagAndClassName('INPUT', 'rollover');

	for (i = 0; i < elements.length; i++) {
		
		addEvent(elements[i], "mouseover", imageIdleToOver);
		addEvent(elements[i], "mouseout", imageOverToIdle);
		
		if (elements[i].parentNode && elements[i].parentNode.tagName == 'A') {
			addEvent(elements[i].parentNode, "focus", removeFocus);
		}
	}
}

/**
 * Resets the 'is_preview_enabled' flag for the currently logged on webmaster
 */
function resetIsPreviewEnabled()
{
	var url = 'index.php?module=smartmovies_mb&view=ajax_result&action=reset_is_preview_enabled';
	var where = document.getElementById('ajaxResult');
	
	AjaxGetData(url, receive_ajax, where);
}

function previewMode(modeID)
{
	switch (modeID)
	{
		case 'off':
			document.getElementById('qp-frame').style.display = 'none';
			break;		
		case 'minimized':
			document.getElementById('qp-frame').style.display = '';
			document.getElementById('cmd-bar').style.display = '';
			document.getElementById('fullpv-btn').style.display = 'none';
			document.getElementById('close-btn').style.display = 'none';
			document.getElementById('minimise-btn').style.display = 'none';
			document.getElementById('open-btn').style.display = '';
			document.getElementById('new-user').style.display = 'none';
			document.getElementById('qp-window').style.display = 'none';
			break;
		case 'minimized-first':
			document.getElementById('qp-frame').style.display = '';
			document.getElementById('cmd-bar').style.display = '';
			document.getElementById('fullpv-btn').style.display = 'none';
			document.getElementById('close-btn').style.display = 'none';
			document.getElementById('minimise-btn').style.display = 'none';
			document.getElementById('open-btn').style.display = '';
			document.getElementById('new-user').style.display = '';
			document.getElementById('qp-window').style.display = 'none';
			break;
		case 'expanded':
			document.getElementById('qp-frame').style.display = '';
			document.getElementById('cmd-bar').style.display = '';
			document.getElementById('fullpv-btn').style.display = '';
			document.getElementById('close-btn').style.display = '';
			document.getElementById('minimise-btn').style.display = '';
			document.getElementById('open-btn').style.display = 'none';
			document.getElementById('new-user').style.display = 'none';
			document.getElementById('qp-window').style.display = '';
			break;
	}
}

function updateView()
{
	if (document.getElementById('templatename'))
	{
		switch (document.getElementById('templatename').value)
		{
			case 'simpleview':
			{
				var colors = new Array('', 'blue', 'marine', 'turquoise', 'green', 'lime', 'twilight', 'cayenne', 'pink', 'candy', 'violet', 'urban', 'dark');
				var colorPicker = document.getElementsByName('document_model');
				
				for(var i = 0; i < colorPicker.length; i++) 
				{	
					if(colorPicker[i].checked) 
					{
						document.getElementById('qp-frame').className = colors[colorPicker[i].value-1];
						break;
					}
				}
			}
			break;
			case 'advancedview':
			{
				document.getElementById('qp-frame').className = '';
		
				color_link = isValidRGB(document.getElementById('color_link').value);										
				color_alink = isValidRGB(document.getElementById('color_alink').value);
				color_vlink = isValidRGB(document.getElementById('color_vlink').value);									
				color_selected_link = isValidRGB(document.getElementById('color_selected_link').value);										
				color_title = isValidRGB(document.getElementById('color_title').value);					
				color_description = isValidRGB(document.getElementById('color_description').value);							
				color_important_text = isValidRGB(document.getElementById('color_important_text').value);					
				color_other_text = isValidRGB(document.getElementById('color_other_text').value);					
				color_background = isValidRGB(document.getElementById('color_background').value);							
				color_background_title_tabs = isValidRGB(document.getElementById('color_background_title_tabs').value);		
				color_background_tabs = isValidRGB(document.getElementById('color_background_tabs').value);
				color_outline_tabs =isValidRGB( document.getElementById('color_outline_tabs').value);				

				changeLinkGroupColor(color_link, color_alink, 'pv_link');
				applyColorToElementName(color_vlink, 'pv_vlink');
				applyColorToElementName(color_selected_link, 'pv_selected_link');
				document.getElementById('pv_title').style.color = color_title
				document.getElementById('pv_title').style.background = color_background_title_tabs;
				applyColorToElementClass(color_description, 'description');
				applyColorToElementClass(color_important_text, 'important');
				applyColorToElementName(color_other_text, 'pv_others');
				document.getElementById('qp-window').style.background = color_background;
				applyBackgroundColorToElementClass(color_background_title_tabs, 'box-mb paging');
				applyBackgroundColorToElementClass(color_background_tabs, 'box-mb');
				applyBorderColorToElementClass(color_outline_tabs, 'box-mb');
				applyBorderColorToElementClass(color_outline_tabs, 'maincat center');
				applyBorderColorToElementClass(color_outline_tabs, 'title');
				document.getElementById('pv_sep').style.borderColor = color_outline_tabs;
			}
			break;
		}
	}
	setTimeout('updateView()', 250); 
}

function changeLinkGroupColor(linkColorValue, hoverColorValue, elementId)
{
	var all = document.getElementsByName(elementId);
	var storedId = document.getElementById('storedid').value;
	
	for(var i=0; i<all.length; i++)
	{
		if (all[i].id != storedId)
		{
			all[i].style.color = linkColorValue;
		}
		else
		{
			all[i].style.color = hoverColorValue;
		}					
	}				
}

function applyColorToElementName(colorValue, elementName)
{
	var all = document.getElementsByName(elementName);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.color = colorValue;
	}
}

function applyColorToElementClass(colorValue, className)
{
	var all = document.getElementsByClassName(className);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.color = colorValue;
	}
}

function applyBackgroundColorToElementClass(colorValue, className)
{
	var all = document.getElementsByClassName(className);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.background = colorValue;
	}
}

function applyBackgroundColorToElementName(colorValue, elementName)
{
	var all = document.getElementsByName(elementName);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.background = colorValue;
	}
}

function applyBorderColorToElementClass(colorValue, className)
{
	var all = document.getElementsByClassName(className);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.borderColor = colorValue;
	}
}

function applyBorderColorToElementName(colorValue, className)
{
	var all = document.getElementsByClassName(className);
	
	for(var i=0; i<all.length; i++)
	{
		all[i].style.borderColor = colorValue;
	}
}

function checkTemplateConflicts(fromTemplateSelect) {
	
	selectObj = $('template_id');
	
	// in case there's an error when we call this function
	if (typeof selectObj == 'undefined') {
		
		return false;
	}
	
	//variables - get the radio buttons for thumbs and columns
	sm_thumbs = document.getElementById("thumbs_size_small");
	md_thumbs = document.getElementById("thumbs_size_medium");
	lg_thumbs = document.getElementById("thumbs_size_large");
	nb_col_1 = document.getElementById("num_columns_1");
	nb_col_2 = document.getElementById("num_columns_2");
	
	
	var cols_available = (null == nb_col_1) ? false : true;
	
	//get the current selected template
	selectedTemplate = selectObj[selectObj.selectedIndex].value;

	// custom templates don't have rules like the predefined ones
	if (typeof templates_rules[selectedTemplate] == 'undefined') {
		//no rules, disable everything, set to 1 column, medium thumbs
		sm_thumbs.disabled = true;
		md_thumbs.disabled = false;
		lg_thumbs.disabled = true;
		md_thumbs.checked  = true;
		
		if (true == cols_available)
		{
			nb_col_1.disabled = false;
			nb_col_2.disabled = true;
			nb_col_1.checked  = true;
		}
		
		//return false to get out now
		return false;
	}
	else
	{
		//rules are defined, it is a predefined template, enable the radio buttons
		sm_thumbs.disabled = false;
		md_thumbs.disabled = false;
		lg_thumbs.disabled = false;
		
		if (true == cols_available)
		{
			nb_col_1.disabled = false;
			nb_col_2.disabled = false;
		}				
	}
	
	//default vars
	num_columns = 1;
	thumbs_size = 'medium';

	//put the thumbs and column elements into array so we can use them in the loops
	thumbs_elements			= new Array(sm_thumbs, md_thumbs, lg_thumbs);
	num_columns_elements	= new Array(nb_col_1, nb_col_2);
	
	//enable / disable thumbs according to rules
	if (null != templates_rules[selectedTemplate]['thumbs'])
	{
		sm_thumbs.disabled = (1 == templates_rules[selectedTemplate]['thumbs'][sm_thumbs.value]) ? false : true;
		md_thumbs.disabled = (1 == templates_rules[selectedTemplate]['thumbs'][md_thumbs.value]) ? false : true;
		lg_thumbs.disabled = (1 == templates_rules[selectedTemplate]['thumbs'][lg_thumbs.value]) ? false : true;	
	}

	//loop through the thumbs, and get the selected
	//if the checked on is disabled, set it to medium
	for (i in thumbs_elements) 
	{

		if (thumbs_elements[i].checked) 
		{
			if (true == thumbs_elements[i].disabled)
			{
				md_thumbs.checked = true;
				thumbs_size = 'medium'
			}
			else
			{
				thumbs_size = thumbs_elements[i].value;
			}
		}
	}	

	
	//now we take care of the number of columns
	if (true == cols_available && null != templates_rules[selectedTemplate]['2_cols'])
	{
		//do we allow 2 columns of not
		// Either 2_cols is an array with the font sizes or it equals 0	
		if (isNaN(templates_rules[selectedTemplate]['2_cols'][thumbs_size]))
		{
			//2 columns enabled
			nb_col_2.disabled = false;
			//if the call came from the template select, check off 2 colummns
			if (true == fromTemplateSelect)
			{
				nb_col_2.checked = true;
			}			
			
		}
		else
		{
			//disable 2 columns
			nb_col_2.disabled = true;
			//select 1 column
			nb_col_1.checked = true;
		}
		
		//one final check, if 2 columns is checked, do we disable any thumbs
		if (true == nb_col_2.checked)
		{
			sm_thumbs.disabled = (isNaN(templates_rules[selectedTemplate]['2_cols'][sm_thumbs.value])) ? false : true;
			md_thumbs.disabled = (isNaN(templates_rules[selectedTemplate]['2_cols'][md_thumbs.value])) ? false : true;
			lg_thumbs.disabled = (isNaN(templates_rules[selectedTemplate]['2_cols'][lg_thumbs.value])) ? false : true;				
		}
	}

	
	

	if (null != templates_rules[selectedTemplate]['thumbs'] && templates_rules[selectedTemplate]['links']['min'] <= templates_rules[selectedTemplate]['links']['max']) {
		
		resizeDropdown($('size_link'), templates_rules[selectedTemplate]['links']['min'], templates_rules[selectedTemplate]['links']['max'], 1);
		resizeDropdown($('size_title'), templates_rules[selectedTemplate]['links']['min'], templates_rules[selectedTemplate]['links']['max'], 1);
		resizeDropdown($('size_description'), templates_rules[selectedTemplate]['links']['min'], templates_rules[selectedTemplate]['links']['max'], 1);
		resizeDropdown($('size_important_text'), templates_rules[selectedTemplate]['links']['min'], templates_rules[selectedTemplate]['links']['max'], 1);
		resizeDropdown($('size_other_text'), templates_rules[selectedTemplate]['links']['min'], templates_rules[selectedTemplate]['links']['max'], 1);
	}
	
	if(null != $('num_video_page')){
		resizeDropdown($('num_video_page'), num_columns, 15, num_columns);
	}
	
	// To keep a memory of the new selected parameters;
	oldSelectedTemplate = selectedTemplate;
	oldSize = newSize;
}

/**
 * Sets the variable changeSize to know if we have to check default values
 */
function setChangeSize(elt, value, fromRadio){
	changeSize = value;
	
	if(fromRadio){
		newSize = elt.value;
	}
}

function resizeDropdown(selectObj, min, max, increment) {
	
	if(null != selectObj){
		var selectPrevious = false;
		var newDoc = false;
		
		if($('name').value == ''){
			newDoc = true;
		}
		
		// If we change the template's properties
		if(newDoc || changeSize){
			var tmp = selectObj.id.split('_');
			var eltName = tmp[1];
			var stop = false;
			
			// As some elts don't exist or are mispelled, we check if they are right
			if(eltName == 'link'){
				eltName = 'links';
			}else if(eltName != 'title' && eltName != 'description' && eltName != 'important' && eltName != 'other'){
				var stop = true;
			}
			
			if(!stop){
				// Check if we are in a 2 columns case
				nb_col_2 = document.getElementById("num_columns_2");
				
				if(null != nb_col_2 && nb_col_2.checked == true){
					var sizeCase = '2_cols';
				}else{
					var sizeCase = 'defaults';
				}
				//alert(sizeCase);
				
				//Checks if the old selected values correspond to the default ones and switch to the new default ones.
				if(null != templates_rules[oldSelectedTemplate] && null != templates_rules[oldSelectedTemplate][sizeCase][oldSize][eltName]){
					var oldDefault = templates_rules[oldSelectedTemplate][sizeCase][oldSize][eltName];
				}else{
					var oldDefault = -1;
				}
				//alert(selectObj[selectObj.selectedIndex].value +'=='+ oldDefault + ' ' + oldSelectedTemplate + ' ' + oldSize + ' ' + newSize + ' ' + eltName + ' ' + sizeCase);
				if(newDoc || oldDefault == -1 || selectObj[selectObj.selectedIndex].value == oldDefault){
					// If the size exists for the selected template
					if(null != templates_rules[selectedTemplate][sizeCase][newSize][eltName]){
						var newDefault = templates_rules[selectedTemplate][sizeCase][newSize][eltName];
						//alert(newDefault);
						
						var selectedSize = newDefault;
					}else{
						selectPrevious = true;
					}
				}else{
					selectPrevious = true;
				}
			}else{
				selectPrevious = true;
			}
		}else{
			selectPrevious = true;
		}
		
		// If we have to select the previous value
		if(selectPrevious){
			var selectedSize = selectObj[selectObj.selectedIndex].value;	//the currently selected font size
		}
		var newIndex = 0;
		var counter = 0;
		
		//clear the select box
		selectObj.length = 0;
		
		//loop the the range, incrementing by 0.5, and add the values to the font size select box
		for(var size = min; size <= max; size += increment)
		{
			selectObj.length++;					//add and item to the select box
			selectObj[counter].value	= size;	//add the value
			selectObj[counter].text		= size;	//add the text
			
			//check if current option is equal to the previously selected font size 
			if (size == selectedSize) {
				
				newIndex = counter;
			}
			
			//increment the counter
			counter++;
		}
	
		//set the new selected index
		selectObj.selectedIndex = newIndex;
	}
}

function setIframeDimension(width, height) {

	width = 1 * width;
	height = 1 * height;
	
	elements = document.getElementsByTagAndClassName('DIV', 'generated-code');
	
	var regX = new RegExp('width="([0-9]+|NaN)"', "g");
	var regY = new RegExp('height="([0-9]+|NaN)"', "g");
	
	for (i in elements) {
		
		elements[i].innerHTML = elements[i].innerHTML.replace(regX, 'width="'+width+'" ');
		elements[i].innerHTML = elements[i].innerHTML.replace(regY, 'height="'+height+'" ');
	}
	
}

function initOpenLinksNewWindows() {

	elements = document.getElementsByTagAndClassName('A', 'new_window');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = captureOpenLinkNewWindow;
	}
}

function captureOpenLinkNewWindow (e) {
	el = getSourceFromEvent(e);

	if (el && el.tagName == "A" && el.href) {
		
		url = el.href;
		
		window.open(url);

		return false;
	}
}

function repositionQuickPreview(position)
{
	stylecontent = 'width:380px; top:5px; left:5px; bottom:auto; right:auto;';
	
	switch(position)
	{
		case 'top-left':
			stylecontent = 'width:380px; top:5px; left:5px; bottom:auto; right:auto;';
			document.getElementById('qp-window').style.padding = 0;
			break;
		case 'top-right':
			stylecontent = 'width:380px; top:5px; left:auto; bottom:auto; right:5px;';
			document.getElementById('qp-window').style.padding = 0;
			break;
		case 'bottom-left':
			stylecontent = 'width:380px; top:auto; left:5px; bottom:5px; right:auto;';
			document.getElementById('qp-window').style.padding = 0;
			break;
		case 'bottom-right':
			stylecontent = 'width:380px; top:auto; left:auto; bottom:5px; right:5px;';
			document.getElementById('qp-window').style.padding = 0;
			break;
		case 'top-center':
			stylecontent = 'width:100%; top:0px; left:0px; bottom:auto; right:auto;';
			document.getElementById('qp-window').style.paddingLeft = '28%';
			document.getElementById('qp-window').style.paddingRight = '28%';
			break;
	}
	document.getElementById('qp-frame').style.cssText = stylecontent;
}

/**
 * initialisation
 * 
 * !!!! THIS HAS TO BE AT THE VERY END OF THE FILE !!!!
 */
addEvent(window, "load", initRollover);
addEvent(window, "load", initOpenLinksNewWindows);

/**
 * allow to fill into a text field only numbers
 * ex: telephone number, allopass code
 * 
 * @param evt
 * $return boolean
 */
 function numeralsOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

/**
 * allow to fill into a text field only letters
 * ex: nom, prenom
 * 
 * @param evt
 * $return boolean
 */
function lettersOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
    if (charCode > 32 && (charCode < 65 || charCode > 90) && 
        (charCode < 97 || charCode > 122)) {
        return false;
    }
    return true;
}

function changeDocumentSelectedInfo(elem)
{
	var url = (elem.value != 0) ? '/' + elem.value : '';
	url = $('span_preview_url').innerHTML + url;
	$('preview_url_displayed').innerHTML 	= url;
	$('iframe-preview').src 				= url;
	$('preview_url_link').href 				= url;
}

