/**
 * @version 1.0
 *
 * @copyright Copyright 2009 WnG Solutions Sàrl, all rights reserved
 * @author Dorian Villet <dorian.villet AT wng DOT ch>
 * @package jtcamp
 */


/*
 * CONTENT UPDATES
 */

/**
 * Rafraichissements de zones de contenus
 *
 * @param string contentID Files name from "ajax" folder to load
 * @param function callback Fonction à exécuter après les animations
 * @return void
 */
function loadContent(contentID, callback) {
		
	// On effectue la requête AJAX pour récupérer le contenu
	$.ajax({
		type: 'POST',
		url: 'ajax/' + contentID + '.ajax.php',
		beforeSend: function() {
			$('#' + contentID).show().addClass('loading');
		},
		success: function(content) {
			$('#' + contentID).hide().removeClass('loading').html(content).fadeIn('slow', callback);
		}
	});
}

/**
 * Prépare et écrit le message de notification d'une opération
 *
 * @param object xml XML contenant les paramètres "result" et "message"
 * @param string id ID du div où écrire le résultat
 * @return void
 */
function updateNotification(xml, id, callback, waitBeforeCallback) {

	// Si le message de notification était visible, on le cache rapidement, sinon on l'affiche
	if ($('#' + id).is(':visible')) {
		$('#' + id).slideUp('slow', function() {
			displayNotification(xml, id, callback, waitBeforeCallback);
		});
	} else {
		displayNotification(xml, id, callback, waitBeforeCallback);
	}
}
function displayNotification(xml, id, callback, waitBeforeCallback) {

	// Gestion du résultat
	if ($(xml).find('result').text() == '1') {
	
		// Tout s'est bien passé
		$('#' + id).html($('<p></p>')
			.html($(xml).find('message').text())
			.addClass('notification success')
		);
		
	} else {
		
		// On ajoute le <ul>
		$('#' + id).html($('<ul></ul>').addClass('notification'));
		
		// On ajoute les <li>
		$(xml).find('message').each(function() {
			$('#' + id + ' ul.notification').append($('<li></li>')
				.html($(this).text())
				.addClass('error')
			);
		});
	}
	
	// On gère le callback
	if (typeof(callback) == 'function') {
	
		// On affiche le résultat, on attends et on exécute le callback
		$('#' + id).slideDown('slow').wait(waitBeforeCallback).slideUp(0, callback);
		
	} else {
	
		// On affiche le résultat
		$('#' + id).slideDown('slow');
	}
}

/**
 * Destroy the dialog box
 *
 * @param string boxID
 * @return boolean
 */
function destroyDialog(boxID) {

	// On vérifie si la box est fermée
	if (!$('#' + boxID).dialog('isOpen')) {
		
		// On supprime la box
		$('#' + boxID).dialog('destroy');

		// On supprime le timeout
		clearTimeout(contentModalTimer);
		
		// On réinitialise la variable
		contentModalTimer = false;
		
		// On retourne true
		return true;
	}
	
	// On retourne false
	return false;
}

/**
 * Active le calendrier pour toute sorte de situation (DOM chargé ou pas, etc)
 */
function applyDatepicker(selector, params) {

	// On définit le datepicker, et au click, on change les paramètres
	$(selector).datepicker().live('click', function() {
		
		// Modification des paramètres et focus
		$(this).datepicker(params).focus();
	});
}

/**
 * Affiche/cache les champs en fonction du choix du select
 *
 * @param string value Valeur du champ select
 * @param string zone Champs à modifier (arrival / departure)
 * @param int accordionID ID du formulaire
 * @return void
 */
function updateInfluencedFields(value, zone, accordionID) {

	// Vitesse de l'animation
	var flightID = '#' + zone + '_flightZone_' + accordionID;
	var originID = '#' + zone + '_originZone_' + accordionID;
	var animationSpeed = 'slow';
	
	// On vérifie qu'on ait sélectionné un choix ayant de l'influence
	if (value == 'Zurich Airport' || value == 'Chur CFF Railway') {
		
		// On affiche
		$(originID).slideDown(animationSpeed);
	
		// On gère le champ "flight number"
		if (value == 'Zurich Airport') {
			$(flightID).slideDown(animationSpeed);
		} else {
			$(flightID).slideUp(animationSpeed);
		}
		
	} else {
	
		// On cache tout
		$(originID + ', ' + flightID).slideUp(animationSpeed);
	}
}


/*
 * FORMULAIRES
 */

/**
 * Gestion des formulaires dans les étapes
 *
 * @param void
 * @return void
 */
function getDefaultFormsValues() {
	
	// Formulaires par défaut
	return {
		
		// Formulaires après le chargement du contenu AJAX et avant le changement d'étape, ainsi que les erreurs
		before: new Array(),
		after: new Array(),
		errors: new Array(),
		
		// Itérateurs
		beforeIterator: 0,
		afterIterator: 0,
		errorsIterator: 0
	};
}

/**
 * Gestion des formulaires - suppression du "after"
 *
 * @param object object Object à modifier
 * @param string toReset "after", "before", "all"
 * @return void
 */
function resetFormsValues(object, toReset) {

	// On gère le before
	if (toReset == 'before' || toReset == 'all') {
		object.before = new Array();
		object.beforeIterator = 0;
	}

	// On gère le after
	if (toReset == 'after' || toReset == 'all') {
		object.after = new Array();
		object.afterIterator = 0;
	}
	
	// On gère les erreurs
	object.errors = new Array();
	object.errorsIterator = 0;
	
	// On retourne l'objet
	return object;
}

/**
 * Gestion du bouton "sauver" dans les steps
 *
 * @param object caller
 * @param string action "enable" / disable"
 * @return void
 */
function enableSaveButton(caller) {
	$('.accordion form#' + $(caller).parents('form').attr('id') + ' .saveButton').removeClass('disabled');
}


/*
 * DISPLAYS
 */

/*
 * Gestion du hover
 */
function hoverUp(element) {
		
	// Classe temporaire
	$(element).addClass('tempHover');
	
	// On boucle sur tous les td de la ligne
	$('table tbody tr.tempHover td:not(.actions)').each(function() {
		$(this).css('background-color', '#F8D14D');
	});
}
function hoverDown(element) {
	
	// On boucle sur tous les td de la ligne
	$('table tbody tr.tempHover td:not(.actions)').each(function() {
		$(this).css('background-color', '#FBE8A6');
	});
	
	// Classe temporaire
	$(element).removeClass('tempHover');
}


/*
 * EMAIL SPAM PROTECTION
 */

/**
 * Gestion des emails
 *
 * @author Kasper Skaarhoj
 * @see TYPO3
 */
function decryptCharcode(n,start,end,offset) {
	n = n + offset;
	if (offset > 0 && n > end)	{
		n = start + (n - end - 1);
	} else if (offset < 0 && n < start)	{
		n = end - (start - n - 1);
	}
	return String.fromCharCode(n);
}

function decryptString(enc,offset) {
	var dec = '';
	var len = enc.length;
	for(var i=0; i < len; i++)	{
		var n = enc.charCodeAt(i);
		if (n >= 0x2B && n <= 0x3A)	{
			dec += decryptCharcode(n,0x2B,0x3A,offset);	// 0-9 . , - + / :
		} else if (n >= 0x40 && n <= 0x5A)	{
			dec += decryptCharcode(n,0x40,0x5A,offset);	// A-Z @
		} else if (n >= 0x61 && n <= 0x7A)	{
			dec += decryptCharcode(n,0x61,0x7A,offset);	// a-z
		} else {
			dec += enc.charAt(i);
		}
	}
	return dec;
}

function linkTo_UnCryptMailto(s) {
	location.href = decryptString(s,-3);
}


/*
 * PHP to JAVASCRIPT
 */

/**
 * Finds position of last occurrence of a string within another string
 *
 * @version 909.322
 * @author Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * @see http://phpjs.org/functions/strrpos
 *
 * @param string haystack
 * @param string needle
 * @param int offset
 * @return int
 */
function strrpos(haystack, needle, offset) {
	var i = (haystack + '').lastIndexOf(needle, offset);
	
	return (i >= 0) ? i : false;
}

/**
 * Returns part of a string 
 *
 * @version 909.322
 * @author Martijn Wieringa
 * @see http://phpjs.org/functions/substr
 *
 * @param string f_string
 * @param int f_start
 * @param int f_length
 * @return string
 */
function substr(f_string, f_start, f_length) {
	f_string += '';

	if (f_start < 0) f_start += f_string.length;
	
	if (f_length == undefined) f_length = f_string.length;
	else if (f_length < 0) f_length += f_string.length;
	else f_length += f_start;
	
	if (f_length < f_start) f_length = f_start;
	
	return f_string.substring(f_start, f_length);
}

/*
 * Fonction de clonage
 * @author Keith Devens
 * @see http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 */
function clone(srcInstance) {

    // Si l'instance source n'est pas un objet ou qu'elle ne vaut rien c'est une feuille donc on la retourne
    if (typeof(srcInstance) != 'object' || srcInstance == null) return srcInstance;
	
    //On appel le constructeur de l'instance source pour crée une nouvelle instance de la même classe
    var newInstance = srcInstance.constructor();
    
	// On parcourt les propriétés de l'objet et on les recopies dans la nouvelle instance
    for (var i in srcInstance) {
        newInstance[i] = clone(srcInstance[i]);
    }
	
    // On retourne la nouvelle instance
    return newInstance;
}


/*
 * JQUERY PLUGINS
 */

/**
 * Fonction permettant d'effectuer un temps d'attente
 *
 * @param int time Temps en secondes
 * @param string type ?
 * @return void
 *
 * @see http://docs.jquery.com/Cookbook/wait
 */
$.fn.wait = function(time, type) {
	time = time * 1000;
	time = time || 1;
	type = type || 'fx';
	
	return this.queue(type, function() {
		var self = this;
		
		setTimeout(function() {
			$(self).dequeue();
		}, time);
	});
};
