/**
 * Classe de dialogue ajax pour la localisation
 *
 * Rev 0.34 du 2011/02/08
 * - Controle de re-entrance requete ajax
 * Rev 0.33 du 2010/10/07
 * - Controle de l'existence du widget dans Localisation.start
 * Rev 0.32 du 2010/09/23
 * - Ajout de la gestion des exclusions
 * Rev 0.31 du 2010/07/19
 * - fix: les props de l'objet loc doivent être mise à '' et non à false
 * - loc_from_cookie() : mise à '' des valeurs undefined (pour IE)
 * Rev 0.3 du 2010/07/09
 * - Maintient l'état du widget dans un cookie
 * Rev 0.21 du 2010/06/30
 * - Pas d'actualisation des dimensions des select region/subregion si invisibles (width==0)
 * Rev 0.2 du 2010/03/17
 * - Va chercher les titres des scrolls directement dans les attributs title plutot que par i18
 * Rev 0.1 du 2010/02/03
 * - version initiale
 */

if (typeof(window.jQuery) == "undefined") {
	alert("jQuery doit etre charge !");
}
/**
 * Namespace
 */
var Localisation = {
	country_datas: 				new Array,
	messages:					new Array,
	loc: 						{country:'', region:'', subregion:'', cookie_name:'', comment_id:''},
	country_localisation_url: 	"/commun/localisation/"
};

var pendings = new Array;
/**
 * Initialisations
 */
Localisation.start = function() {

	jQuery.url.setUrl(Localisation.rawurldecode(window.location));

	// Handler de changement de pays
	$("#country-select").change(
		function() {
			Localisation.init_loc();
			Localisation.loc.region = '';
			Localisation.loc.subregion= '';
			Localisation.loc.cookie_name= Localisation.make_cookie_name($(this));
			// suppression du cookie
			Localisation.handle_loc(Localisation.loc);

		}
	);

	// Handler de changement de région
	$("#region-select").change(
		function() {
			Localisation.init_loc();
			Localisation.loc.subregion = '';
			Localisation.loc.cookie_name= Localisation.make_cookie_name($(this));
			Localisation.handle_loc(Localisation.loc);
		}
	);

	// Handler de changement de sous-région
	$("#subregion-select").change(
		function() {
			// récupérer les propriétés actuelle pour loc
			Localisation.init_loc();
			// le changement de subregion implique-t-il un changement de region ?
			if (Localisation.loc.subregion !='') {
				// oui - on ré-initialise la région
				Localisation.loc.region = '';
			}
			Localisation.loc.cookie_name= Localisation.make_cookie_name($(this));
			Localisation.handle_loc(Localisation.loc);
		}
	);

	// si pas de widget - le test doit etre fait ici, pas avant
	if (!  document.getElementById("#country-select")) {
		return;
	}
	// creation de l'id
	var cookie_name= Localisation.make_cookie_name($("#country-select"));

	if (cookie_name) {
		var cookie_value = $.cookie(cookie_name);
		if (cookie_value) {
			// recrée loc à partir du cookie
			Localisation.loc = loc_from_cookie(cookie_value);
		}
		else {
			// initialise l'objet loc a partir des selects
			Localisation.init_loc();
		}
		// actualise les selects
		Localisation.handle_loc(Localisation.loc);
	}
	else {
		// initialise l'objet loc a partir des selects
		Localisation.init_loc();
	}


	/**
	 * Recrée un objet loc à partir d'un cookie
	 * @param string v
	 * @return object
	 */
	function loc_from_cookie(v) {
		var parts = new Array;
		parts = v.split(/&/);
		var loc = {};
		for(var i = 0; i<parts.length; i++) {
			var a = parts[i].split(/=/);
			if (a[1] == undefined) {
				a[1] = '';
			}
			loc[a[0]] = a[1];
		}
		return loc;
	}
}

/**
 * Fabrique un nom de cookie à partir du select
 * @param object
 * @return string
 */
Localisation.make_cookie_name = function(lc) {
	return "loc"+ Localisation.get_comment_id(lc);
}

/**
 * Obtenir l'id à partir du select
 * @param object e
 * @return int
 */
Localisation.get_comment_id = function(lc) {
	if (lc.get(0).previousSibling.nodeValue != null) {
		return lc.get(0).previousSibling.nodeValue.replace(/[^0123456789abcdef]/g, '');
	}
	return '';
}

/**
 * Positionne la valeur par défaut de l'objet loc à partir des select
 */
Localisation.init_loc = function() {
	Localisation.loc.country 	= $("#country-select").val();
	Localisation.loc.region		= $("#region-select").val();
	Localisation.loc.subregion	= $("#subregion-select").val();
	Localisation.loc.comment_id	= Localisation.get_comment_id($("#country-select"));

}

/**
 * prise en charge d'un changement de localisation géo
 * ou positionnement d'un nouvel objet
 * @param object loc
 */
Localisation.handle_loc = function(loc) {

	if (!Localisation.country_datas[loc.country]) {
		// evite de gaspiller de la requete
		if (! pendings[loc.country]) {
			pendings[loc.country] = true;
			// obtenir les country_datas
			var lang = Localisation.get_cookie("autolang");
			$.get(new Localisation.url_builder({'action':	"get_datas"
											,	'country': 	loc.country
											,	'lang':		lang
											}
											, Localisation.country_localisation_url).toString()
				, false
				, function(data, text_status) {
						Localisation.country_datas[loc.country] = data;
						Localisation.messages = data.messages;
						// resette le semaphore
						pendings[loc.country] = false;
						Localisation.handle_loc(loc);
						return;
				}
				, "json"
			);
		}
	}
	else {
		// Assurer la bonne sélection du pays
		$("#country-select").val(loc.country);
		// données dispo - déterminer l'état final de loc
		if (loc.region 		== ''
		&&	loc.subregion	!= '')
		{
			// region en fonction de subregion
			loc.region = Localisation.country_datas[loc.country].subregions[loc.subregion].region;
		}
		// regions
		Localisation.build_region_select(loc);
		// subregions
		Localisation.build_subregion_select(loc);
	}

	// retour commun
	if (loc.cookie_name) {
		if (loc.country) {
			// pose cookie - 1 heure
			$.cookie(loc.cookie_name, jQuery.param(loc), { expires: 1/24});
		}
		else {
			// reset du select de pays - détruit le cookie
			$.cookie(loc.cookie_name, '', { expires:-1});
		}
	}

}

/**
 * Construction du select des régions
 * @param object loc
 */

Localisation.build_region_select = function(loc) {

	var rs = $("#region-select");
	var w = rs.get(0).offsetWidth;
	// On a besoin de notre comment_id s'il n'est pas déjà la (cas d'un appel préférences lieux)
	if (!loc.comment_id) {
		loc.comment_id = Localisation.get_comment_id($("#country-select"));
	}

	rs.empty();
	var filled = 0;
	// remplit en filtrant éventuellement
	for(var p in Localisation.country_datas[loc.country].regions) {

		var regex = new RegExp('\('+ loc.country + '-' + p + '\)' );

		if ( /* exclu */
			loc.comment_id
		&& 	Localisation.without_region[loc.comment_id].length > 0
		&&	Localisation.without_region[loc.comment_id].match(regex)
		|| /* inclus */
			Localisation.with_region[loc.comment_id].length > 0
		&&  ! Localisation.with_region[loc.comment_id].match(regex)
		)
		{
			continue;
		}
		rs.append(new Localisation.select_option(p, Localisation.country_datas[loc.country].regions[p].title).toString());
		filled++;
	}

	if (filled) {
		rs.prepend(new Localisation.select_option('', "--- "+ rs.attr('title')+" ---").toString());
		rs.val(loc.region ? loc.region : '');
	}
	else {
		rs.prepend(new Localisation.select_option('',"--- "+Localisation.i18('coll_no_region')+" ---").toString());
	}
	// fix IE7 sur redimensionnement non souhaité (uniquement si visible)
	if (w > 0) {
		rs.get(0).style.width= w+"px";
	}
}

/**
 * Construction du select des sous-régions
 * @param object loc
 */
Localisation.build_subregion_select = function(loc) {

	var ss = $("#subregion-select");
	// On a besoin de notre comment_id s'il n'est pas déjà la (cas d'un appel préférences lieux)
	if (!loc.comment_id) {
		loc.comment_id = Localisation.get_comment_id($("#country-select"));
	}

	var w = ss.get(0).offsetWidth;
	ss.empty();

	var filled =0;
	// remplit en filtrant éventuellement
	for(var s in Localisation.country_datas[loc.country].subregions) {
		if (!loc.region
		||	 loc.region == Localisation.country_datas[loc.country].subregions[s].region)
		{
			var select_opt;
			if (ss.hasClass("localisation-full")) {
				select_opt = new Localisation.select_option(s, Localisation.country_datas[loc.country].subregions[s].full_title);
			}
			else {
				select_opt = new Localisation.select_option(s, Localisation.country_datas[loc.country].subregions[s].title);
			}


			var regex = new RegExp('\('+loc.country + '-[A-Z0-9]{3}-'+ s + '\)' );

			if ( /* exclu */
				loc.comment_id
			&& 	Localisation.without_subregion[loc.comment_id].length > 0
			&&	Localisation.with_subregion[loc.comment_id].match(regex)
			|| /* inclus */
				  Localisation.with_subregion[loc.comment_id].length > 0
			&&  ! Localisation.with_subregion[loc.comment_id].match(regex)
			)
			{
				continue;
			}

			// sans ou avec filtre par region
			ss.append(select_opt.toString());
			filled++;

		}
	}
	if (filled) {
		ss.prepend(new Localisation.select_option('',"--- "+ss.attr('title')+" ---").toString());
		ss.val(loc.subregion ? loc.subregion : '');
	}
	else {
		ss.prepend(new Localisation.select_option('',"-- "+Localisation.i18('coll_no_subregion')+" ---").toString());
	}
	// fix IE7 sur redimensionnement non souhaité (uniquement si visible)
	if (w > 0) {
		ss.get(0).style.width= w+"px";
	}
}

/**
 * Objet option de select
 */
Localisation.select_option = function (opt_value, opt_text) {
	this.opt_value= opt_value;
	this.opt_text = opt_text;

	this.toString = function toString() {
		if (!this.opt_text) {
			this.opt_text = this.opt_value;
		}
		return '<option value="'+this.opt_value+'">'+this.opt_text+'</option>';
	}
}

/**
 * Traduction d'après un id de message
 * @param string msg_id de message
 * @return string
 */
Localisation.i18 = function(msg_id) {
	if (! Localisation.messages) {
		return msg_id;
	}
	return (Localisation.messages[msg_id] ? Localisation.messages[msg_id] : msg_id);
}

/**
 * Constructeur d'url
 * @param object ar_params
 * @param string path_value
 * @param string host
 * @param string protocol
 */
Localisation.url_builder = function() {
	this.params 	= {};
	this.path		= false;
	this.hostv		= false;
	this.proto		= "http";

	this.set_params =( function set_params(params) {
		for(var i in params) {
			this.params[i] = params[i];
		}
	});

	this.set_path = function set_path(path_value) {
		this.path = path_value;
	}

	this.toString = function toString() {
		var s = '';
		if (this.hostv) {
			s = s+this.proto+"://"+this.hostv;
		}

		s = s+ this.path;
		var q_string = jQuery.param(this.params);
		if (q_string) {
			s = s + "?" + q_string;
		}
		return s;
	}

	if (arguments[0]) {	this.set_params(arguments[0]);	}
	if (arguments[1]) { this.path	= arguments[1];		}
	if (arguments[2]) { this.hostv	= arguments[2];		}
	if (arguments[3]) { this.proto	= arguments[3];		}

}

/**
 * Obtenir un cookie
 * @param string name
 * @return string
 */
Localisation.get_cookie = function(name) {
	var cookieValue = null;
    if (document.cookie && document.cookie != '') {
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
			var cookie = jQuery.trim(cookies[i]);
			// Does this cookie string begin with the name we want?
			if (cookie.substring(0, name.length + 1) == (name + '=')) {
				cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
				break;
			}
		}
	}
    return cookieValue;
}


/**
 * Courtesy of http://phpjs.org/
 */
Localisation.rawurldecode = function( str ) {
    // Decodes URL-encodes string
    //
    // version: 907.503
    // discuss at: http://phpjs.org/functions/rawurldecode
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // *     example 1: rawurldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin+van+Zonneveld!'
    // *     example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    // *     example 4: rawurldecode('-22%97bc%2Fbc');
    // *     returns 4: '-22—bc/bc'
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';


    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }

    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = ret.replace(/%([a-fA-F][0-9a-fA-F])/g, function (all, hex) {return String.fromCharCode('0x'+hex);}); // These Latin-B have the same values in Unicode, so we can convert them like this
    ret = decodeURIComponent(ret);

    return ret;
}

/**
 * jquery start point
 */
$(document).ready(Localisation.start);

