
if(typeof(Droselia) == 'undefined')
	Droselia = {};

var canada 	= 40;
var us		= 63;
/**
 * 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;

	// number of videos
	var nb = document.getElementById('nb_of_selected_videos');

	// message no videos selected
	var no_videos_selected =  document.getElementById('no_videos_selected');

	var check_nb_videos = (elements != '') ? elements.split(',').length : 0;

	nb.innerHTML = check_nb_videos;

	if (0 == check_nb_videos){
		no_videos_selected.style.display = "";
	}else{
		no_videos_selected.style.display = "none";
	}

}

function showFHGSeparator (show)
{
	if (show)
		$('csv_separator').show();
	else
		$('csv_separator').hide();
}


/**
 * compare old video selected id with the new one
 * if there is any difference display the generate button for new feeds
 * otherwise display the feeds already generated
 *
 * @param elements	// selected video
 * @return
 */
function checkStatusVideos(elements){

	var old_video_ids = document.getElementById('old_video_ids');


	if((old_video_ids.value == undefined || old_video_ids.value == null || old_video_ids.value == '') || (elements == '')){

		// generate new feeds button (ids videos are changed)

	}else if(old_video_ids.value == elements){

		// nothing was changed (for ex a video selected with same id)
		$('videos-codes').style.display = '';

		// case when the video code was not yet generated
		var empty_videos_code = $('videos-codes').innerHTML;

		if (empty_videos_code.empty()){
			$('generate-feeds-button').style.display = 'block';
		}else{
			$('generate-feeds-button').style.display = 'none';
		}

	}

	else{
		var url = 'index.php?module=smartmovies_mb&view=check_selected_videos&old_videos=' + old_video_ids.value + '&new_videos=' +  elements;
		AjaxGetData(url, resultAjaxVideoCheck);
	}

}

function resultAjaxVideoCheck(data){

	if ( "OK" == data ){

		// display feeds already generated
		$('videos-codes').style.display = '';
		$('generate-feeds-button').style.display = 'none';

	}else{

		// generate new feeds button (ids videos are changed)
		$('videos-codes').style.display = 'none';
		$('generate-feeds-button').style.display = '';
	}

}

/**
 *  verify and update ids of old videos to be able to check them later
 * @param elements // selected video
 * @return
 */
function updateOldVideo(elements){
	var old_videos = document.getElementById('old_video_ids');
	old_videos.value = elements;
}

/**
 * add dinamically event onchange for language select
 * @return
 */
function addEventOnChangeForLanguage(){
	var el = document.getElementById('language_selector');
	el.setAttribute("onchange","document.getElementById('submit_status').value='';promoChanged()");
}

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 resolutionChanged()
{
	var res_selector	= $('res_id');

	var res_is_nan		= isNaN(parseInt(res_selector.value))

	if (res_is_nan)
	{
		$('custom_resolution_container').style.display = 'block';
	} else
	{
		$('custom_resolution_container').style.display = 'none';
	}

	var width = parseInt($('custom_resolution_width').value);

	if (width == 0 || isNaN(width))
	{
		width = res_selector.options[0].value.split("x")[0];
	}

	if (width > 1920)
	{
		width = 1920;
	}

	$('custom_resolution_width').value = width;

	var height = Math.round(width * 9 / 16 * 1.125) || 0;

	$('custom_resolution_height').innerHTML = height;
}


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]));
	}
}

/**
 *
 * update scripts for banners with selected document id
 *
 * @param url
 * @param doc_id
 *
 */
function updateDocumentBannerLink(url, doc_id){
	var codes = document.getElementsByClassName('generated-code');

	for(var i = 0 ; i < codes.length ; i++){
		var tmp = codes[i].id.split('_');
		generateBannerLink(url, doc_id, tmp[1]);
	}
}

function updateLibidoBannerLink(url, doc_id){
	var codes = document.getElementsByClassName('generated-code');

	for(var i = 0 ; i < codes.length ; i++){
		var tmp = codes[i].id.split('_');
		generateLibidoBannerLink(url, doc_id, tmp[1]);
	}
}

function updateLibidoCatcherCode(url, doc_id){
	var codes = document.getElementsByClassName('generated-code');

	for(var i = 0 ; i < codes.length ; i++){
		var tmp = codes[i].id.split('_');
		generateLibidoCatcherCode(url, doc_id, tmp[1]);
	}
}

function updateLibidoPDVCode(url, doc_id){
	var codes = document.getElementsByClassName('generated-code');
	for(var i = 0 ; i < codes.length ; i++){
		var tmp = codes[i].id.split('_');
		generateLibidoPDVCode(url, doc_id, tmp[1]);
	}
}

/**
 *
 * create script for each banner
 *
 * @param url
 * @param doc_id
 * @param id_img
 *
 */
function generateBannerLink(url, doc_id, id_img){

	var src = document.getElementById('img_' + id_img).src;

	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=' + id_img;

		var newCode = '<pre>&lt;a href="' + newUrl + '"&gt;&lt;img src="' + src + '" /&gt;&lt;/a&gt;</pre>';

		document.getElementById("div_" + id_img).innerHTML = newCode;
	}
}

function generateLibidoBannerLink(url, doc_id, id_img){
	var src = document.getElementById('img_' + id_img).src;

	var newUrl = url + '?banner_id=' + id_img + '&tracker_id=' + doc_id;

	var newCode = '<pre>&lt;a href="' + newUrl + '"&gt;&lt;img src="' + src + '" /&gt;&lt;/a&gt;</pre>';

	document.getElementById("div_" + id_img).innerHTML = newCode;

}

function generateLibidoCatcherCode(url, doc_id, id_img){
	var src = document.getElementById('img_' + id_img).src;

	var newUrl = url + '?catcher_id=' + id_img + '&tracker_id=' + doc_id;

	var newCode = '<pre>&lt;script src="' + newUrl + '"&gt;&lt;/script&gt;</pre>';

	document.getElementById("div_" + id_img).innerHTML = newCode;

}

function generateLibidoPDVCode(url, doc_id, id_img){
	var src = document.getElementById('img_' + id_img).src;

	var newUrl = url + id_img + '/?tracker_id=' + doc_id;

	var newCode = '<pre>'+newUrl+'</pre>';

	document.getElementById("div_" + id_img).innerHTML = newCode;

}
// 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(el) {

	if(el == 1){

		showhideByClass('txt subedit',	'');

	} else {

		showhideByClass('txt subedit',	'none');

		// delete company name
		$('company_name').value = '';
	}
}

/**
 * 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= '';
	}
}

/**
 * display <li id="states"> if its Canada (id = 40) or US (id = 63)
 **/
function changeWebmasterCountry(value) {
	if (value == canada){
		$('states_canada').style.display = '';
		$('states_us').style.display = 'none';
	}
	else if(value == us){
		$('states_canada').style.display = 'none';
		$('states_us').style.display = '';

	}else{
		$('states_canada').style.display = 'none';
		$('states_us').style.display = 'none';
	}
	return false;
}


/**
 * display <li id="states"> if its Canada (id = 40) or US (id = 63)
 **/
function changeWebmasterBankCountry(value) {

	if (value == canada){
		$('bank_states_canada').style.display = '';
		$('bank_states_us').style.display = 'none';
	}
	else if(value == us){
		$('bank_states_canada').style.display = 'none';
		$('bank_states_us').style.display = '';

	}else{
		$('bank_states_canada').style.display = 'none';
		$('bank_states_us').style.display = 'none';
	}

	return false;
}


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 (var i = 0; i < elements.length; i++) {

		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;
}


/**
 * 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 = $('single_code_doc_url').value + url;
	$('preview_url_displayed').innerHTML 	= url;
	$('preview_url_link').href 				= url;
}


function addDynamicEvent(){

	// — get all the input elements in the document
	var x = document.getElementsByTagName('input');
	var y = document.getElementsByTagName('select');

	for (i=0; i<x.length; i++) {

		if (x[i].getAttribute('type') == 'radio') {
			addEvent(x[i], 'click', showValidation);
		}
	}

	for (j=0; j<y.length; j++) {
		addEvent(y[j], 'change', showValidation);
	}

}

/**
 * shows / hides the content feeds against button to generate feeds
 * @return
 */

function showValidation() {
	if (document.getElementById('generate-feeds-button').style.display == 'none') {

		document.getElementById('generate-feeds-button').style.display = 'block';
		document.getElementById('feed-code-container').style.display = 'none';
	}
}

/**
 * Function tests to see if all parameter are valid before sending the form
 * @return
 */
function submitTransferForm(form_obj)
{
	//temp
	document.getElementById('message_space').style.display = 'block';
	document.getElementById('message_space').innerHTML = 'WAITING....';

	//check if a webmaster has been validated
	wm_transfer = document.getElementById('webmaster_to_id').value;

	if (isNaN(wm_transfer) || 0 >= wm_transfer)
	{
		document.getElementById('message_space').innerHTML = 'Login not validated';
		return false;
	}

	//check if the amount is greater than 0, and less than the displayed amount
	max_amount = document.getElementById('max_amount').value;
	trn_amount = document.getElementById('transfer_amount').value;

	if (isNaN(trn_amount) || 10 > parseFloat(trn_amount) || parseFloat(max_amount) < parseFloat(trn_amount))
	{
		document.getElementById('message_space').innerHTML = 'Invalid Amount';
		return false;
	}

	//check if the reason is entered
	if ("" == document.getElementById('transfer_reason').value)
	{
		document.getElementById('message_space').innerHTML = 'Invalid Reason';
		return false;
	}

	//if all good, proceed with the submit
	form_obj.submit();
}


/**
 *
 * @param string r_fn 	// webmaster first name
 * @param string r_ln	// webmaster last name
 * @param string r_d	// current date
 *
 * @return scr
 */
function checkContractRequiredFields(r_fn, r_ln, r_dt){

	var filed_fn = $('contract_first_name');
	var filed_ln = $('contract_last_name');
	var filed_dt = $('contract_date');


	if(r_fn.toLowerCase() == filed_fn.value.toLowerCase() && r_ln.toLowerCase() == filed_ln.value.toLowerCase() && r_dt == filed_dt.value)
	{
		//hide the text, show the button
		$('sign-infos').hide();
		$("contract_signed_image").show();
	}
	else
	{
		//hide the button, show the text
		$('sign-infos').show();
		$("contract_signed_image").hide();
	}

	return false;
}

//given an element and a max limit, restircts the number of characters entered into the text element
function restrictTextMaxCharacters(txt_element, char_limit)
{
	if(txt_element.value.length > char_limit)
	{
		txt_element.value = txt_element.value.substr(0,char_limit);
	}
}

function openSimpleAdvanceModalWindow(modal_window, site_id, document_type_id)
{
	//close the document selection menu, and put back the button for new doc
	$('group'+site_id).down('div div.menu').hide();
	$('group'+site_id).down('div div.selector').show();

	//reset the link hrefs
	var url_params = "&document_type=" + document_type_id + "&site_id=" + site_id
	$('simple_doc_creation_link').href = $('simple_base_url').value + url_params;
	$('advanced_doc_creation_link').href = $('advanced_base_url').value + url_params;

	//open the modal window
	modal_window.open();
}


function openAddEditGroupWindow(modal_window, param_site_id)
{
	var site_id   = "new";
	var site_name = "";
	var site_url  = "";
	var window_title = "Nouveau <span>groupe</span>";

	if (0 < param_site_id)
	{
		site_id   = param_site_id;
		site_name = $('tab-group'+param_site_id).down('a').innerHTML;
		site_url  = $('group'+param_site_id).down('h3 a').innerHTML;
		window_title = "Éditer un <span>groupe</span>";
	}

	$('add_group_form').down('input#title').value = site_name;
	$('add_group_form').down('input#url').value  = site_url;
	$('add_group_form').down('input#id').value = site_id;
	$('addedit_group_window_title').innerHTML = window_title;

	$('add_edit_group_error').hide();
	modal_window.open();
}

//function checks if something is entered for the URL, and verifies it with an Ajax call if there is
function validateAddEditGroupForm()
{
	$('add_edit_group_error').hide();

	//check if url is empty
	if ("" == $('add_group_form').down('input#url').value)
	{
		validateAddEditGroupFormReturn("URL :  Ce champ ne peut être vide.");
	}
	else
	{
		var url = $('verify_url_address').value + "&url=" + $('add_group_form').down('input#url').value;
		//run an Ajax call to verify the url
		AjaxGetData(url, validateAddEditGroupFormReturn)

	}

	return false;
}

//display errors if the title is empty, or if the url is not valid.
function validateAddEditGroupFormReturn(data)
{
	//if everything checks out, and there is a title submit the form
	if ("OK" == data && "" != $('add_group_form').down('input#title').value)
	{
		$('add_group_form').submit();
	}
	else
	{
		//otherwise, display an error for the url
		var error = ("OK" == data) ? "" : data;
		if ("" == $('add_group_form').down('input#title').value)
		{
			error = "Titre :  Ce champ ne peut être vide.<br/>" + error
		}

		$('add_edit_group_error').innerHTML = error;
		$('add_edit_group_error').show();
	}


}

/**
 * Genereic function for the add edit document forms
 * checks if all fields marked required have something in them
 */
function addEditDocumentCheckRequiredFields()
{
	//control vars for the function
	var form_valid = true;
	var row_valid = true;
	var num_required = 0;
	var row_inputs = null;

	//get all the required fields
	var required_rows = $('addedit_document_form').select('td.required_value');

	//loop through the rows
	required_rows.each(
		function(row)
		{
			//reset the row flag
			row_valid = true;
			//get all the required inputs for the rows
			row_inputs = row.select("input.required_field, textarea.required_field");

			//loop through the required input.
			row_inputs.each(
				function(input)
				{
					//if it is empty, set the flag to false and break from the loop
					if (input.value == "")
					{
						row_valid = false;
						return;
					}//end if
				}
			);

			//if the row flag is set to false, set the flag for the form, and increment the counter
			if (false === row_valid)
			{
				num_required++;
				form_valid = false;
			}
		}
	);

	//once all the rows have been looped through, check if the form is valid or not
	if (false === form_valid)
	{
		//form isn't valid
		//hide active preivew and submit buttons
		if (null != $('preview_button_active'))
		{	$('preview_button_active').hide();	}
		$('validate_button_active').hide();

		//show disabled buttons
		if (null != $('preview_button_disabled'))
		{	$('preview_button_disabled').show();	}
		$('validate_button_disabled').show();

		//set the number of fields remaining in the template
		$('num_required_fields').innerHTML = num_required;

		//display required fields message
		$('required_field_error_message').show();

		//return false
		return false;
	}
	else
	{
		//form is valid
		//hide active preivew and submit buttons
		if (null != $('preview_button_active'))
		{	$('preview_button_active').show();	}
		$('validate_button_active').show();

		//show disabled buttons
		if (null != $('preview_button_disabled'))
		{	$('preview_button_disabled').hide();	}
		$('validate_button_disabled').hide();

		//display required fields message
		$('required_field_error_message').hide();

		//return true
		return true;
	}
}



function createColorPickerObjects(element_ids)
{
	for (var i = 0; i < element_ids.size(); i++)
	{
		//picker control
		new Control.ColorPicker(element_ids[i]+"_hidden",
			{
				"swatch" : element_ids[i]+"_img",
				IMAGE_BASE : color_picker_image_path,
				onUpdate: function (param) { var base_id = this.field.id; updateColorPickerElements(base_id.replace("_hidden", ""), false) }
			}
		);

		//remove the background styles added by creating the tool
		$(element_ids[i]+"_img").style.cssText = "";
	}

	return true;
}

function _(s) {
	if (typeof(i18n)!='undefined' && i18n[s]) {
		return i18n[s];
	}
	return s;
}


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


/*******************************
 * End Of File                 *
 * NO code after this point !! *
 *******************************/


