// Libraries
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */



/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        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;
    }
};

(function($) {	
	// Fonction de tooltip XBA
	$.fn.myTooltip = function(c) {
		if(typeof wjconf.helper == 'undefined' ) {
			wjconf.helper = $('<div id="tooltip"><div class="body"></div></div>')
				// hide it at first
				.hide()
				// add to document
				.appendTo('body');
		}
		return this.each(function(){
	
			var tooltipText = $(this).attr("title") || $(this).attr("alt");
			if(typeof tooltipText == "undefined") return;
	
			$(this).hover( 
				function() { 
					if(typeof wjconf.helper_body == 'undefined' ) {
						wjconf.helper_body = $('.body', wjconf.helper);
						$(this).removeAttr("title");
						$(this).removeAttr("alt");
					}
					wjconf.helper_body.text(tooltipText);
	
					positions = findPos(this);
					var width = $(this).width();
					var left = positions[0] - 30 + Math.floor(width / 2);
					var top = positions[1] - wjconf.helper.height();

					wjconf.helper
						.css({
							left: left +'px',
							top: top + 'px'
						})
						.show(); 
				},
				function() {
					$(this).attr("title",tooltipText);
					wjconf.helper.hide();
				}
			);
		});
	};	
})(jQuery);

// WJ Config
var wjconf = {};

wjconf.forms = {}	//on y stocke tous les formulaires
wjconf.maps = {} //on y stocke toutes les cartes;
wjconf.templates = {} //on y stocke tous les templates html par défaut;
wjconf.templates.notify = 'L\'email est en cours d\'envoi&hellip;';
wjconf.templates.invite = 'L\'email est en cours d\'envoi&hellip;';
wjconf.templates.saved = '<a href="/my_offers.php" class="added">Offre sauvegard&eacute;e sur mon tableau de bord</a>';
wjconf.templates.error = 'Veuillez compl&eacute;ter tous les champs requis';
wjconf.templates.emailerror = 'Veuillez v&eacute;rifier les emails';

/* NEW Version für IE */
function load() {
    // if( $.browser.msie ) {
    //     $('#content-main').css({'width':'555px', 'margin-right':'240px'});
    //     $('#ads').css({'width': '240px', 'padding': '0', 'margin': '0', 'margin-top': '8px','margin-left': '-240px'});
    //     $(document.body).attr('id', 'ie6');
    //     // alert(' tot ');
    // }
    
	pushTPLCookie('javascript', true);
    
	$("form.offer_updatenote").each(function(){
		var offer_updatenote = $(this);
		var buttons = $("input:submit", this);
		var current_note = $("textarea[name=offer_note]", this);
		var prev_note = current_note.val();

		buttons.attr('disabled', 'disabled');
		current_note.focus(function(){
			buttons.attr('disabled', '');
		});	
        
		buttons.click(function(){
			var action = $(this).attr('class');
			switch (action) {
				case 'cancel':
					current_note.val(prev_note);
					buttons.attr('disabled', 'disabled');
					return false;
					break;
				case 'clear':
					current_note.val('');
					break;
				default:
					break;
			}
			$.ajax({
				type: "POST",
				url: '/xml.php' + offer_updatenote.attr('action').replace(/^.*?\?/i, '?'),
				data: offer_updatenote.serialize(),
				success: function(content){
					$("#flash").replaceWith(content);
				flash();
				}
			});
		    
			buttons.attr('disabled', 'disabled');
			return false;
		});
	});
    
	// Les exemples
	$("#query_search a[@rel=search]").click(function(){
		kw = $(this).text();
		$("input#search").val(kw);
		return false;
	});
	$("#query_search a[@rel=fpc]").click(function(){
		kw = $(this).text();
		$("input#fpc").val(kw);
		return false;
	});
    
	// Les exemples
	$('button, input:submit, a[title], span.tooltip').myTooltip();
	
	flash();
	
	$('#help-index').each(function(){
		$(this).toggle(function(){
			$($(this).attr('href')).slideDown('fast');
			src = $('img', this).attr('src');
			$('img', this).attr('src', src.replace('-open','-close'));
			return false;
		},function(){
			$($(this).attr('href')).slideUp('fast');
			src = $('img', this).attr('src');
			$('img', this).attr('src', src.replace('-close','-open'));
			return false;
		});
	});
	
	resizeMainContent();
	
    // pphlogger();
}

function flash() {
	$("#flash > div").css('opacity','0')
	.animate({opacity: 1.0}, { queue:true, duration:500 } )
	.animate({opacity: 1.0}, 4000 )
	.animate({opacity: 0.0}, 800 );
}

var toogleMenuFilter = function() {
	var body = $('body');
	toogleMenuFilter = function() {
	    body.toggleClass('folded');
		if(wjconf.currentDivOpened) {
			wjconf.currentDivOpened.hide();
		}
		value = body.attr('class');
		pushTPLCookie('filters-menu', value);
	}
	return toogleMenuFilter();
}

function resizeMainContent() {
    // permet de d'adapter la hauteur du contenu principal avec la colonne des filtres
    var content_main = $('#content-main');
    content_main.css({'height': 'auto'});
    var c = content_main.height();
    var h = $('#list-filters').height() + 300;
    if ( c < h ) {
        content_main.css({'height': h + 'px'})
    }
}
function foldFilters(e) {
	// 1 on plie / déplie le filtre
	$(e).next('dd').toggle();
	$('span', e).toggle();
	$(e).toggleClass('folded');
    
	// 2 On notifie par un cookie 
	key = $(e).attr('id');
	value = $(e).attr('class');
	pushTPLCookie(key, value);
	
	resizeMainContent();
}

function toogleMore(e) {
	var target = '' + $(e).attr("href");
	wjconf.currentDivClicked = $(target);
	wjconf.currentDivClicked.toggle();
	if(wjconf.currentDivOpened && wjconf.currentDivOpened.attr('id') != wjconf.currentDivClicked.attr('id')) {
		wjconf.currentDivOpened.hide();
	}
	wjconf.currentDivOpened = wjconf.currentDivClicked;
}
function saveOffer(e) {
    var me = $(e);
    
    $.ajax({
     type: "GET",
     url: "/xml.php" +  me.attr("href").replace(/^.*?\?/i, '?'),
     cache: false,
     dataType: "html",
     success: function(content){
         $("#flash").replaceWith(content);
         flash();
     }
    });
    $(me.attr("rel")).attr('style', 'background:#f6f6fb');
    me.replaceWith(wjconf.templates.saved);
	return false;
}
function deleteOffer(e) {
	current_offer = $(e).parents(".offer");
	$.ajax({
		type: "GET",
		url: "/xml.php" + $(e).attr("href").replace(/^.*?\?/i, '?'),
		cache: false,
		dataType: "html",
		success: function(content){
			$("#flash").replaceWith(content);
			flash();
		}
	});
	current_offer.css('background','#f00');
	current_offer.fadeOut('fast');
}
function unhideOffer(e) {
	current_offer = $(e).parents(".offer");
	$.ajax({
		type: "GET",
		url: "/xml.php" + $(e).attr("href").replace(/^.*?\?/i, '?'),
		cache: false,
		dataType: "html",
		success: function(content){
			$("#flash").replaceWith(content);
			flash();
		}
	});
	current_offer.css('background','#0f0').css('color','#fff');
	current_offer.fadeOut('fast');
}
function deleteSelectedFilters(e) {
	$("#selected-filters").css('background','#f00').fadeOut('slow');
}
function toggleOpinion(e) {
	$.ajax({
		type: "GET",
		url: "/xml.php" + $(e).attr("href").replace(/^.*?\?/i, '?'),
		cache: false,
		dataType: "html",
		success: function(content){
			$("#flash").replaceWith(content);
			flash();
		}
	});
	$(e).toggleClass("opinion-neutral");
	$(e).toggleClass("opinion-for");
}
function notifyFriend(e) {
	if(!validateForm(e)) {
		return false;
	}

	$("#flash").html('<div class="flash-loading">'+wjconf.templates.notify+'</div>');
	flash();
	mailer_notify_form = $(e);
	mailer_notify = mailer_notify_form.parents(".mailer_notify");
	mailer_notify_response = $(".response", mailer_notify);
	$.ajax({
		type: "POST",
		url: "/xml.php" + $(e).attr("action").replace(/^.*?\?/i, '?'),
		cache: false,
		data: $(e).serialize(),
		dataType: "html",
		success: function(content){
			$("#flash").replaceWith(content);
			$("input[name='mailer_dest']", mailer_notify_form).val('');
			$("textarea[name='mailer_message']", mailer_notify_form).val('');
			flash();
		}
	});
	mailer_notify_form.hide();
	mailer_notify_response.show();

	$(".resend_email", mailer_notify_response).bind('click',function(){
		mailer_notify_response.hide();
		mailer_notify_form.show();
		return false;
	});
	return false;
}

function displayLogin(e) {
	if(typeof wjconf.forms.login == 'undefined' ) {
		wjconf.forms.login = $('#wjconf_forms_login');
		if(wjconf.forms.login.length < 1) {
			wjconf.forms.login = false;
		}
		else {
			// On ajoute une jolie boiboite pour afficher les erreurs
			$("form", wjconf.forms.login).append('<div class="if-error"></div>');
		}
	}
	
	if(wjconf.forms.login) { 
		_position = findPos(e);
		_h = $(e).height();
		_w = $(e).width();
	
		form_w = 280;
	
		if( (_position[0] + form_w) > $(document).width() ) { // On fait flotter à droite
			new_left = (_position[0] + _w) - form_w;
		}
		else { // On fait flotter à gauche
			new_left = _position[0];
		}
		new_top = _position[1] + _h;
		wjconf.forms.login.css('left', new_left + 'px');
		wjconf.forms.login.css('top', new_top + 'px');
		wjconf.forms.login.toggle();
		
		if(wjconf.currentAjaxFormOpened && wjconf.currentAjaxFormOpened.attr('id') != wjconf.forms.login.attr('id')) {
			wjconf.currentAjaxFormOpened.hide();
		}
		
		wjconf.currentAjaxFormOpened = wjconf.forms.login;
		return false;
	}
		
	return true;
}
function displayInvite(e) {
	if(typeof wjconf.forms.invite == 'undefined' ) {
		wjconf.forms.invite = $('#wjconf_forms_invite');
		if(wjconf.forms.invite.length < 1) {
			wjconf.forms.invite = false;
		}
		else {
			// On ajoute une jolie boiboite pour afficher les erreurs
			$("form fieldset", wjconf.forms.invite).append('<div class="if-error"></div>');
		}
	}
	
	if(wjconf.forms.invite) {
		_position = findPos(e);
		_h = $(e).height();
		_w = $(e).width();
	
		form_w = 350;
	
		if( (_position[0] + form_w) > $(document).width() ) { // On fait flotter à droite
			new_left = (_position[0] + _w) - form_w;
		}
		else { // On fait flotter à gauche
			new_left = _position[0];
		}
		new_top = _position[1] + _h;
		wjconf.forms.invite.css('left', new_left + 'px');
		wjconf.forms.invite.css('top', new_top + 'px');
		wjconf.forms.invite.toggle();

		if(wjconf.currentAjaxFormOpened && wjconf.currentAjaxFormOpened.attr('id') != wjconf.forms.invite.attr('id')) {
			wjconf.currentAjaxFormOpened.hide();
		}
		
		wjconf.currentAjaxFormOpened = wjconf.forms.invite;

	}

	// On surcharge le formulaire idoine
	$('form', wjconf.forms.invite).bind('submit',function(){
		if(!validateForm(this)) {
			return false;
		}
		$("#flash").html('<div class="flash-loading">'+wjconf.templates.invite+'</div>');
		flash();
		$.ajax({
			type: "POST",
			url: "/xml.php" + $(this).attr("action").replace(/^.*?\?/i, '?'),
			cache: false,
			data: $(this).serialize(),
			dataType: "html",
			success: function(content){
				$("#flash").replaceWith(content);
				$("input[name='mailer_dest']", wjconf.forms.invite).val('');
				$("textarea[name='mailer_message']", wjconf.forms.invite).val('');
				flash();
			}
		});
		wjconf.forms.invite.hide();
		return false;
	});
}

function newSearch(e) {
	if(typeof wjconf.arrow == 'undefined' ) {
		wjconf.arrow = $("#arrow-right");
		if(wjconf.arrow.length < 1) {
			wjconf.arrow = false;
		}
	}
	if(wjconf.arrow) {
		$("input[@name=fpc]").val('Lieu').addClass('blur');
		$("input[@name=search]").each(function(){
			$(this).focus().val('').removeClass('blur');

			pos = findPos(this);
			y = pos[1];
			x = pos[0] - 19;
			wjconf.arrow
				.css('top', y + 'px')
				.css('left', x + 'px')
				.fadeIn("fast")
				.fadeOut("slow");
			
		});
		return false;
	}
		
	return true;
}

function validateForm(e) {
	// On surcharge tous les formulaires qui nécessite une prévalidation
	var err = null;
	var error_stdout = null;
	var do_flash = true;
	var err_mess = wjconf.templates.error;
	var reEmail = /^[ ]*[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})[ ]*$/;

	// Avons-nous une boiboite if error ?
	$(".if-error", e).each(function(){
		error_stdout = $(this);
		do_flash = false;
	});
	// Non, donc on affiche les messages d'erreur dans le Flash
	if(error_stdout == null) {
		error_stdout = $("#flash");
		do_flash = true;
	}

	// 1re boucle : on valide la compl�tion des champs
	$("label.req", e).each(function(){
		l = $(this);
		f = '#' + l.attr('for');
		elt = $(f);
		if(!elt.val() || (elt.val() == '')) {
			l.addClass('error');
			elt.addClass('error');
			if(!err) {
				err_mess = wjconf.templates.error;
				elt.focus();
			}
			err = true;
		}
		else {
			l.removeClass('error');
			elt.removeClass('error');
		}
	});

	// 2me boucle : on valide les emails
	$("label.validate-email", e).each(function(){
		l = $(this);
		f = '#' + l.attr('for');
		elt = $(f);
		
		val = elt.val();

		if(val.match(reEmail)) {
			// OK
			l.removeClass('error');
			elt.removeClass('error');
		}
		else {
			// NOK
			l.addClass('error');
			elt.addClass('error');
			if(!err) {
				err_mess = wjconf.templates.emailerror;
				elt.focus();
			}
			err = true;
		}
	});
	

	if(err) {
		error_stdout.html('<div class="flash-error">'+err_mess+'</div>');
		if(do_flash == true ) {
			flash();
		}
		return false;
	}
	else {
		error_stdout.empty();
		return true;
	}
}
function pushTPLCookie(key, value) {
	// 1 on évalue le cookie correspondant en une Hash
	wjconf.cookie = $.cookie('wj_tpl');

	if( wjconf.cookie != null) {
		eval("var folded = "+ wjconf.cookie +";");
	}
	else {
		folded = {};
	}
	// 2 on complête la Hash avec la nouvelle paire clé / valeur
	folded[key] = value;
	items = []; var j = 0;
	for (var i in folded) {
		if(typeof folded[i] != 'undefined') {
			items[j] = '"'+ i + '":"' + folded[i] + '"';
			j++;
		}
	}
	var output = '{' + items.join(',') + '}';
	$.cookie('wj_tpl', output);
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* Permet d'insérer de compter les liens sortants 
 * S'utilise avec /outgoing.php qui se charge de mettre en base les données
 * 
 * Exemple d'implémentation :
 * - <a href="manpower?id=999" onclick="outgoingLink(e, 'FEED', 'manpower');">voir cette offre</a>
 *
 */
function outgoingLink(e, kw1, kw2, kw3) {
	var src = 'http://www.wanajob.com/outgoing.php?destination='+ encodeURIComponent(e.href) +'&kw1='+ kw1 +'&kw2='+ kw2 +'&kw3=' + kw3;
	new Image().src = src;
	return true;
}

function bookmarkLink() {
    var title = window.document.title;
    var url = window.location.href;

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	}
	else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	}
	else if(window.opera && window.print) { // Opera Hotlist
	    var a = document.createElement("a");
        a.rel = "sidebar";
        a.target = "_search";
        a.title = title;
        a.href = url;
        a.click();
	}
}

// Lance toi !
load();

// L'utilisateur courant
function currentUser(json) {
	return;
};

function pphlogger() {
    
    var id = 'pphlogger';
    var showme = 'n';
    var st = 'js';  // st means show-type

    // If you're using a frameset and are not getting correct 
    // referrers, please uncomment the following line:
    // pp_frames = true;
    
    
    // get the user agent name ----------------------------------
    v = navigator.appName;
    
    // get the screen resolution --------------------------------
    c=0;
    if (v != "Netscape") c = screen.colorDepth;
    else c = screen.pixelDepth;
    
    // get the screen size --------------------------------------
    s = screen.width+"x"+screen.height;
    
    // get the document's title ---------------------------------
    t = escape(document.title);
    
    // get the document's referrer -------------------------------
    var f = "";
    
    // if pp_frames is true then try getting the framed referral (without error checking)
    if (typeof(pp_frames) != "undefined")
    	if (pp_frames)
    		f = top.document.referrer;
    
    // get the referral for non-multi-domained-framed sites using a Netscape browser
    if ((f == "") || (f == "[unknown origin]") || (f == "unknown") || (f == "undefined"))
    	if (document["parent"] != null) 
    		if (parent["document"] != null) // ACCESS ERROR HERE!
    			if (parent.document["referrer"] != null) 
    				if (typeof(parent.document) == "object")
    					f = parent.document.referrer; 
    
    // get the referral for the current document if a framed referral wasn't found
    if ((f == "") || (f == "[unknown origin]") || (f == "unknown") || (f == "undefined"))
    	if (document["referrer"] != null) 
    		f = document.referrer;
    
    // convert all the unknown's into blank
    if ((f == "") || (f == "[unknown origin]") || (f == "unknown") || (f == "undefined"))
    	f = "";
    
    // escape the referral
    f = escape(f);
    
    // getting data ready to send -------------------------------
    r="?id="+id+"&referer="+f+"&r="+s+"&c="+c+"&showme="+showme+"&st="+st+"&title="+t;
    
    // adding logid if called by st='phpjs'
    if(jslogid==null) var jslogid = 0;
    else r = r + "&jslogid="+jslogid;
    
    rand = Math.round(1000*Math.random());
    r = r+"&b="+rand;  //force the page to load the IMG
    new Image().src = "http://media.wanajob.com/pphlogger/pphlogger.php" + r;
}



exemple_json = {
	"user": "toto@yes.com",
	"filters": {
		"29329":{
			"name":"\u00e9nergie",
			"shorter_name":"\u00e9nergie",
			"query":"search=energie",
			"id":"29329",
			"url":"http:\/\/milou.wanajob.com\/offres_emplois.php?search=energie",
			"elements":{"mots cl\u00e9s":"energie"},
			"to_nav":"1",
			"to_email":"0",
			"to_publish":"1",
			"total_offers":"541"
		}
	},
	"offers":{
		"9f5ad45a11ba554b34e324b5a0ca2e6f":["neutral"],
		"5eceadd2a27603080fd5176505e2901d":["neutral"],
		"0386f7b192518c95f5553be97c591990":["neutral"],
		"155ca61a0bb9dd0b831b8ae35586b7a3":["neutral"]
	}
};