/*
 * Copyright (c) 2009 ReactivOn SAS
 * All rights reserved.
 * 
 * Author: Guillaume BERNARD
 * Date: 2 juin 2009
 * 
 * Box-Over-All
 */

// Variables utilisées pour prévenir des erreurs Javascript avant que le contenu ne soit chargé
var BOA_WIDTH = 0;
var BOA_HEIGHT = 0;
var BOA_onEscapeHandle;



/**
 * Contruction d'une Box-Over-All à partir d'une URL
 */
function BOA_openUrl(url) {
	var queryString = url.match(/\?(.+)/)[1];
	var params = parse_query_string(queryString);
	
	// Si la taille de la BOA n'est pas fixee alors on indique une valeur par defaut
	// Positionne une valeur par defaut correspondant a la moyenne des BOA
	// = eviter une erreur de positionnement trop importante le temps que BOA_reposition soit appele
	if(typeof(params['width']) == "undefined") {
		params['width'] = "no";
	}
	if(typeof(params['height']) == "undefined") {
		params['height'] = "no";
	}
	
	// Création du Box-over-all
	BOA_create((params['width'] * 1) + 30, (params['height'] * 1), 'blue', 0.3, BOA_removeIfLoaded);

	// Création de la BOX de chargement
	if (!$("BOA_load")) {
		new Element('div').setProperty('id', 'BOA_load').injectInside(document.body);
		$('BOA_load').innerHTML = "<div style=\"padding-top:30px;\"><img src=\"/img/loading.gif\" border=\"0\"></div>";
		BOA_load_position();
	}

	// Fonction appelée lorsque le contenu AJAX de la BOX aura été correctement retourné (4 paramètres par défaut en sortie de REQUEST)
	var handlerFunc = function(responseTree, responseElements, responseHTML, responseJavaScript) {
		$("BOA_ajaxContent").set('html', responseHTML);

		var boa_window = $("BOA_window");
		
		// Set title if any
		if ($('content_title') && boa_window) {
			var title = $('content_title').get('html');
			$('content_title').destroy();
			
			boa_window.innerHTML = '<div id="BOA_title" class="boa_title_blue">' + title + '</div>' + boa_window.innerHTML;
		}
		
		// Build bottom if any
		if ($('content_submit_zone') && boa_window) {
			var content = $('content_submit_zone').get('html');
			$('content_submit_zone').destroy();
			
			boa_window.innerHTML += '<div id="BOA_bottom"><div id="BOA_closeAjaxWindow">' +
				content + '</div></div>';
		}

		BOA_position();
		BOA_showWindow();
		
		// Modifie les inputs a styliser
		initFormStyled();
	};
	
	// Récupération via AJAX du contenu pointé par le LIEN
	new Request.HTML({
		method : 'get',
		onSuccess : handlerFunc,
		onFailure : BOA_requestFailure
	}).get(url);
}


/**
 * Display a box-over-all error message about a failure ajax request. This
 * function is intended to be called by onFailure event of Request object.
 */
function BOA_requestFailure(xhr) {
	var msg;
	if (xhr.status == 401) {
		// Must reconnect
		var boamsg_reconnect = $('boamsg_reconnect');
		if (boamsg_reconnect != null) {
			msg = boamsg_reconnect.get('text');
		} else {
			msg = lang['extranet_sess_expired'];
		}
		
		var reconnect_func = function() {
			BOA_remove;
			location.replace('/index.php');
		};
		BOA_msg({
			width : 300,
			height : 50,
			buttons : [ 'OK' ],
			defaultButton: 0,
			onClick : reconnect_func,
			onEscape : reconnect_func,
			content : msg
		});
	} else {
		// An other error
		var boamsg_fail = $('boamsg_fail');
		if (boamsg_fail != null) {
			msg = boamsg_fail.get('text');
		} else {
			msg = lang['error_request_detail'];
		}
		msg += ' ' + xhr.statusText + '.';
		
		BOA_msg({
			width : 300,
			height : 50,
			color : 'red',
			title : lang['error_request_title'],
			buttons : [ 'OK' ],
			defaultButton: 0,onClick : BOA_remove,
			onEscape : BOA_remove,
			content : msg
		});
	}
}


/**
 * Display the box-over-all with a specified content.
 * 
 * @param args Object which can contain the following options:<ul>
 * <li>width - (required) Width of the window</li>
 * <li>height - (required) Height of the window</li>
 * <li>content - (required) HTML content to display</li>
 * <li>title - Optional title of the window</li>
 * <li>color - Box-Over-All color, either 'blue' or 'red' (default is
 * 'blue')</li>
 * <li>buttons - Array of button labels</li>
 * <li>defaultButton - Index of default button, null for none</li>
 * <li>onClick - Handle to call when a button is clicked. Two arguments are
 * given to the handle, which is the index of the clicked button and the user
 * parameter.</li>
 * <li>onEscape - Handle to call when the escape key is pressed or the user has
 * clicked outside the window. The one argument is the user parameter.</li>
 * <li>userParam - Optional, user parameter to provide to onClick handler</li>
 * </ul>
 */
function BOA_msg(args) {
	
	var color = (args.color != undefined) ? args.color : 'blue';
	
	// Creation de la zone Box-over-all
	BOA_create(
			args.width,
			args.height,
			color,
			0.3,
			(args.onEscape != undefined) ? args.onEscape : null);
	
	var boa_window = $("BOA_window");

	// Set content
	$("BOA_ajaxContent").set('html', args.content);
	
	// Set title
	if (boa_window && args.title != undefined) {
		var boa_title = new Element('div', {
			'id': 'BOA_title',
			'class': 'boa_title_' + color
		});
		boa_title.set('html', args.title);
		boa_title.inject(boa_window, 'top');
	}
	
	// Set buttons
	var div_buttons = new Array();
	if (args.buttons != undefined) {
		for (var i = (args.buttons.length - 1); i >= 0; i--) {
			var div_btn = new Element('div');
			if (i == args.defaultButton) {
				div_btn.addClass('boa_default_button');
			} else {
				div_btn.addClass('boa_button');
			}
			// Affecte pour chaque bouton la valeur du ONCLICK
			BOA_setOnClickHandler(div_btn, args.onClick[i], i, args.userParam);
			div_btn.set('text', args.buttons[i]);
			div_buttons.push(div_btn);
		}
	}
	
	// Set user area if defined
	var content_submit_area = $('content_submit_zone');

	// Add bottom area in content
	if (boa_window && (content_submit_area || div_buttons.length > 0)) {
		var boa_bottom = new Element('div', { 'id': 'BOA_bottom' });
		var boa_closeAjaxWindow = new Element('div', { 'id': 'BOA_closeAjaxWindow' });
		
		if (content_submit_area) {
			content_submit_area.inject(boa_closeAjaxWindow);
		}
		for (var i = 0; i < div_buttons.length; i++) {
			div_buttons[i].inject(boa_closeAjaxWindow);
		}
		
		boa_closeAjaxWindow.inject(boa_bottom);
		boa_bottom.inject(boa_window);
	}
	
	BOA_position();
	BOA_showWindow();
}

function BOA_setOnClickHandler(element, handler, index, userParam) {
	element.addEvent('click', function () {
		if (typeof handler == 'string') {
			eval(handler)(index, userParam);
		} else {
			handler(index, userParam);
		}
	});
}


/**
 * Création du Box-Over-All. Peut être détruit avec BOA_remove().
 * 
 * @param width Width of box-over-all window content, in pixels
 * @param height Height of box-over-all window content, in pixels
 * @param color Box-Over-All color, either 'blue' or 'red'
 * @param opacity Overlay opacity, value between 0 and 1
 * @param onEscape Handle to call when the escape key is pressed or the user has
 * clicked outside the window. No arguments are given to the handle.
 */
function BOA_create(width, height, color, opacity, onEscape) {
	
	// Pour les smartphones, la boxoverall reste en haut de la page alors repositionnement Safari en haut de page
	if( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) ) {
		window.scrollTo(0, 1);
	}
	
	var width_name2choose = "width";
	var height_name2choose = "height";
	
	if (width == undefined) {
		width = 400;
		width_name2choose = "min-width";
	}
	if (height == undefined) {
		height = 100;
		height_name2choose = "min-height";
	}
	
	if (color != 'blue' && color != 'red') {
		color = 'blue';
	}
	
	BOA_WIDTH = width + 38;
	BOA_HEIGHT = height + 70;
	

	/* Création du Overlay */
	if (!$("BOA_overlay")) {
		new Element('div').setProperty('id', 'BOA_overlay').injectInside(document.body);
		$('BOA_overlay').fade('hide'); // Immediate hidden
		BOA_overlaySize(); // Détermine la taille du OVERLAY pour qu'il recouvre l'intégralité de la page
	}
	
	// Overlay opacity
	if (opacity > 0) {	
		// Définition des paramètre de l'animation associée à l'apparition du fond 'grisé'
		$('BOA_overlay').set('tween', {
			duration : 300
		});
		$('BOA_overlay').fade(opacity);
	}
	
	// Quand l'utilisateur clique sur le fond 'grisé'
	/*if (BOA_onEscapeHandle != null) {
		$("BOA_overlay").removeEvent('click', BOA_onEscapeHandle);
	}
	BOA_onEscapeHandle = onEscape;
	if (BOA_onEscapeHandle != null) {
		$("BOA_overlay").addEvent('click', BOA_onEscapeHandle);
	}*/
	
	
	/* Création de la fenetre principale */
	
	var boa_window = $("BOA_window");
	if (boa_window) {
		boa_window.dispose();
	}
	boa_window = new Element('div', { id : 'BOA_window', 'class' : 'boa_window_' + color });
	boa_window.injectInside(document.body);
	boa_window.fade('hide');
	
	// Construction de la structure du contenu
	var width_modif = width + 8;	// MAJ GB pour centrage du contenu de la box
	var box_content = "<div id='BOA_ajaxContent' style='" + width_name2choose + ":" + width_modif + "px;" + height_name2choose + ":" + height + "px;'></div>";
	boa_window.innerHTML = box_content;
	
	// Lorsque la taille de la fenêtre du navigateur est modifiée >> Correction de la position de la BOX et de la taille du OVERLAY
	window.removeEvent('resize', BOA_resize); // to delete a possible existing event
	window.addEvent('resize', BOA_resize);
	
	// Action lors de l'appui sur Escape
	document.removeEvent('keyup', BOA_onEscape); // to delete a possible existing event
	document.addEvent('keyup', BOA_onEscape);
}

/**
 * Resize the box-over-all window.
 */
function BOA_resize(event) {
	BOA_position();
	BOA_load_position();
	BOA_overlaySize();
}

/**
 * Remove on escape key event.
 */
function BOA_onEscape(event) {
	if (BOA_onEscapeHandle != null) {
		var event = new Event(event);
		if (event.code == 27) {
			BOA_onEscapeHandle();
		}		
	}
}


function BOA_showWindow() {
	$('BOA_window').fade('show'); // Immediate visible
	if ($('BOA_load')) {
		$('BOA_load').dispose();
	}
}

/**
 * Used by BOA_openUrl(), close BOA only if window is loaded.
 */
function BOA_removeIfLoaded() {
	if (!$('BOA_load')) {
		BOA_remove();
	}
}

/**
 * Destructeur de la BOX over ALL
 */
function BOA_remove() {
	
	if($("BOA_window")) {
		if (BOA_onEscapeHandle != null) {
			$("BOA_overlay").removeEvent('click', BOA_onEscapeHandle);
			BOA_onEscapeHandle = null;
		}
	
		if ($('BOA_closeWindowButton')) {
			$("BOA_closeWindowButton").removeEvent('click', BOA_remove);
		}
	
		$('BOA_window').dispose();
	
		$('BOA_overlay').set('tween', {
			duration : 200,
			onComplete : function() {
				$('BOA_overlay').dispose();
			}
		});
		$('BOA_overlay').fade('out');
		
		if ($('BOA_load')) {
			$('BOA_load').dispose();
		}
	
		window.removeEvent('resize', BOA_resize);
		document.removeEvent('keyup', BOA_onEscape);
	}
}


/**********
* Positionnement dynamique de la BOA par rapport au contenu ou aux tailles fixees
**********/
function BOA_position() {
	var boa_window = $('BOA_window');
	var window_size = window.getSize();
	var boa_size = boa_window.getSize();
	
	// La Box est positionne au centre de la page sauf si la box est plus grande = se bloque en haut a gauche
	var pos_left_boa = ((window_size.x - boa_size.x) > 10) ? window_size.x - boa_size.x : 10;
	var pos_right_boa = ((window_size.y - boa_size.y) > 10) ? window_size.y - boa_size.y : 10;
	boa_window.setStyles({
		"left" : (pos_left_boa / 2) + 'px',
		"top" : (pos_right_boa / 2) + 'px'
	});
}


/**
* Changer le style d'une propriete CSS d'un element lie a un ID
* Utilise pour adapter BOA au contenu affiche
**/
function BOA_change_style(div_id,name_property,value) {
	var boa_div_id = $(div_id);

	boa_div_id.setStyle(name_property,value);
}


/**
 * MAJ de la dimension du OVERLAY (zone 'grisée' en fonction du navigateur)
 */
function BOA_overlaySize() {
	
	var nu = navigator.userAgent;			
	if( (nu.match(/iPhone/i)) || (nu.match(/iPod/i)) || (nu.match(/iPad/i)) ) {
		var className = defineOrientation();
		
		if (className=="paysage") {
			var height_boa_overlay = document.body.clientHeight;
		} else {
			var width_boa_overlay = document.body.clientWidth+30;
		}
		
	} else {
		var window_size = window.getSize();
		var height_boa_overlay = window_size.y;
		var width_boa_overlay = window_size.x;
	}
	
	$("BOA_overlay").setStyles({
		"height" : '0px',
		"width" : '0px',
		"height" : height_boa_overlay + 'px',
		"width" : width_boa_overlay + 'px'
	});
}

function BOA_load_position() {
	var boa_load = $("BOA_load");
	if (boa_load) {
		var window_size = window.getSize();
		boa_load.setStyles({
			"left" : ((window_size.x - 100) / 2) + 'px',
			"top" : ((window_size.y - 100) / 2) + 'px',
			display : "block"
		});
	}
}


/**
 * A partir d'une URL, cette fonction retourne les différents paramètres dont elle est constituee
 */
function parse_query_string(query) {
	if (!query)
		return {}; // Si la chaine est vide alors on renvoit un objet vide

	var params = {};

	// Découpage de la chaine lorsqu'un & est rencontré
	var pairs = query.split(/[;&]/);
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split('='); // Positionne une variable lorsque une affectation de paramètre est trouvée

		if (!pair || pair.length != 2)
			continue; // Sinon on stoppe la recherche en cours et on continue la recherche du prochain paramètre

		// unescape la clé et la valeur associée + remplacement du '+' par un espace
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
	}
	return params;
}





function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  
  return [ scrOfX, scrOfY ];
}
