var arrGlue='#*arr*#';
var objGlue='#*obj*#';
var page=1;
var popEmail;
var popSMS;
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
//var favorites=$.cookie("favoritesCookie");
var favoritesbase = [
    {
        'href': 'http://google.com',
        'loc': 'a Paris (75)',
        'text': 'Eco Services vert 1 ',
        'phone': '01 54 24 67 99'
    },
    {
        'href': 'http://google.com',
        'loc': 'a Paris (75)',
        'text': 'Eco Services vert 2 ',
        'phone': '01 54 24 67 99'
    }
];

var favorites=[];
var directionsDisplay;

$(document).ready(function() {
    $('.autocomplete').autocomplete('/ajax/get/',{
        minChars: 1,
        max: 1,
        delay: 200
    });
    
    $('#blocks a').click(function(event){
        event.preventDefault();
        $(this).annuaireUpdate();
    });
    $('#container').append($('#sauvegardes-tip'));
    if($('#deployed_form_visible').val() == '1'){
        $(this).showDeployed();
    }
    $('#deployed_form_visible').remove();
    
    // test save
    //$(this).saveBase();
    // building favorites object
    favorites=$(this).getFavorites();

    $('.button-plus').click(function(){
        $(this).showDeployed();
    });
    $('#form-narrow-button,.button-minus').click(function(){
        $(this).showShort();
    });

    $('#sauvegardes-trigger, #sauvegardes-tip-header a').click(function(){
        $(this).getFavoritesPage();
        if($('#sauvegardes-tip').css('display')=='none') {
			$(this).showMesSauvegardes();
        }else {
			$(this).hideMesSauvegardes();
		}
    });
    $('#sauvegardes-tip-bottom').click(function(){
        if(!confirm('Êtes-vous sûr ?')) return;
        //empty favorites
        $(this).clearFavorites();
//        favorites = [];
        // set to cookie
        $(this).save();
        $(this).hideMesSauvegardes();        
    });

    $('#tip1').bind('click', function(e) {
        e.preventDefault();
        
        var pos = $(this).offset();
        var elemHeight = $(this).height();
        var elemWidth = $(this).width();
        var ttWidth = $('#tt_aide').width();
        
        $('#tt_aide .content').text($(this).attr('rel'));
        
        $('#tt_aide').css({
            'top': pos.top + elemHeight + 1,
            'left': pos.left - ttWidth + (elemWidth / 2)
        }).toggle();
        
        $(this).toggleClass('tip1_hover');
    });
    
    $('#tt_aide .header a').bind('click', function(e) {
        e.preventDefault();
        
        $('#tt_aide').hide();
        $('#tip1').removeClass('tip1_hover');
    });
    

    $('.sent-to').click(function(e){
        $('.pop-up-windows').remove();
        if($(this).siblings('.send-items').css('display')=='none'){
            $('.send-items').css({'display':'none'});
            var pos = $(this).position();
            $(this).siblings('.send-items').css({'display':'block','top':(pos.top + 31) + 'px'});
        }else{
            $(this).siblings('.send-items').css({'display':'none'});
        }
        e.preventDefault();
    });
    $('.close-send-items').click(function(){
        $('.pop-up-windows').remove();
        $('.send-items').css({'display':'none'});
    });
    $('.en-savoir').hover(
            function(){
                $(this).attr('title', '');
                $(this).toolTipEnSavoir();
            },
            function(){
                $(this).toolTipEnSavoir();
            }
    );
    $('.button-plus1').hover(
            function(){
                objParams = {
                        element: 'tool-tip-button-plus1',
                        image: '/images/lb_afficher_plus.png',
                        x: 215,
                        y: 96
                };
                $(this).toolTip(objParams);
				if(isIE6) {
					$(this).addClass('button-plus-hover');
				}
            },
            function(){
                objParams = {
                        element: 'tool-tip-button-plus1',
                        image: '/images/lb_afficher_plus.png',
                        x: 275,
                        y: 96
                };
                $(this).toolTip(objParams);
				if(isIE6) {
					$(this).removeClass('button-plus-hover');
				}
            }
    );
    $('.button-plus2').hover(
            function(){
                objParams = {
                        element: 'tool-tip-button-plus1',
                        image: '/images/lb_afficher_plus.png',
                        x: 475,
                        y: 96
                };
                $(this).toolTip(objParams);
				if(isIE6) {
					$(this).addClass('button-plus-hover');
				}
            },
            function(){
                objParams = {
                        element: 'tool-tip-button-plus1',
                        image: '/images/lb_afficher_plus.png',
                        x: 475,
                        y: 96
                };
                $(this).toolTip(objParams);
				if(isIE6) {
					$(this).removeClass('button-plus-hover');
				}
            }
    );

    //moving filters to the end of time :) for IE 6
    $('#container').append($('#filters .filter-dd'));

    $('#filters .filter-field').bind('click', function() {
        var $objThis = $(this);
        if(!$objThis.parent('.filter-deactivated').length) {
			if(isIE6) {
				$('.list-paginator:first select').css({'visibility':'visible'});
			}
            $objFilterDD = $('#'+$objThis.attr('rel'));
            
            var pos = $objThis.offset();
            var elemHeight = $(this).height();
            
            $objFilterDD.css({
                'top': pos.top + elemHeight,
                'left': pos.left
            });
            
            $intNbElements = $objFilterDD.find('li').length;
            
            // Add a scrollbar is more than 10 elements
            if($intNbElements > 10 && !$objFilterDD.hasClass('filter-dd-scroll')) {
                $objFilterDD.addClass('filter-dd-scroll');
            }
            
            $objFilterDD.toggle(1, function() {
                if($objFilterDD.is(':visible')) {
                    $('body').bind('click', function(event) {
                        $eventTarget = $(event.target);
                        if($('.filter-dd:visible').length) {
                            $('.filter-dd').hide();
                            $('body').unbind('click');
                            if(!$eventTarget.is('div.filter-field') || $eventTarget.parent('.filter-deactivated').length) {
                                $('.filter-field').removeClass('filter-field-hover');
								$('.list-paginator:first select').css({'visibility':'visible'});
                            }
                        }
                    });
                    
                    $('.filter-field-hover').removeClass('filter-field-hover');
                    $objThis.addClass('filter-field-hover');
					
					// IE 6 LOL
					if(isIE6 && $objThis.attr('rel') == 'localite-dd') {
						$('.list-paginator:first select').css({'visibility':'hidden'});
					}
                }else {
                    $objThis.removeClass('filter-field-hover');
					
					// IE 6 LOL
					if(isIE6) {
						$('.list-paginator:first select').css({'visibility':'visible'});
					}
                }
            });
        }
    });

    $('.submit .form-trouver').hover(        
        function() {
            var pos = $(this).position();
            $(this).next('.ttLancerRecherche').css({
                'top': pos.top + 30,
                'left': pos.left - 140
            });
            $(this).next('.ttLancerRecherche').show();
        },
        function() {
            $(this).next('.ttLancerRecherche').hide();
        }
    );    
    
    $('#find-professional-form-indisponible .help').click(function(e) {
		e.preventDefault();
		var objThis = $(this);
		objThis.addClass('help_hover');
        var objHelpTT = $('#popup-help-opt-indispo');
        //objHelpTT.find('.content').text($(this).attr('alt'));
		
		var pos = $(this).position();
		objHelpTT.css({
			'top': pos.top + $(this).height() + 1,
			'left': pos.left - objHelpTT.width() + Math.round($(this).width() / 2)
		}).show();
        
        objHelpTT.find('.kill-window').bind('click', function(e) {
			e.preventDefault();
            objHelpTT.hide();
            objHelpTT.unbind('click');
			objThis.removeClass('help_hover');
        });
		
    });        
        
    $('#go-find-professional').hover(        
        function() {
            var pos = $(this).position();
            $(this).next('.ttLancerRecherche').css({
                'top': pos.top + 30,
                'left': pos.left - 170
            });
            $(this).next('.ttLancerRecherche').show();
			$(this).parent('div').addClass('hover');
        },
        function() {
            $(this).next('.ttLancerRecherche').hide();
			$(this).parent('div').removeClass('hover');
        }
    );
    
    $('.results .annuaire .phone_others, .results .annuaire .title, #narrow-list .annuaire .phone_others, #narrow-list .annuaire .title, .results .en_savoir_plus, #narrow-list .en_savoir_plus').hover(
            function() {
                var $objParent = $(this).parents('.result');
                var objEnSavoirPlus = $objParent.find('.en_savoir_plus');
                objEnSavoirPlus.attr('title', '');
                objEnSavoirPlus.addClass('en_savoir_plus_hover');
                $objParent.find('.title a').addClass('hover');
                $objParent.find('.phone_others').addClass('hover');
            },
            function() {                
                var $objParent = $(this).parents('.result');
                $objParent.find('.en_savoir_plus').removeClass('en_savoir_plus_hover');
                
                $objParent.find('.title a').removeClass('hover');
                $objParent.find('.phone_others').removeClass('hover');
            }
            
    );	
	
    $('.result .tag_opposition, .autres-numeros-hidden .tag_opposition_autre, #item-phone-number .tag_opposition_autre').hover(            
            function() {
			
                $(this).attr('title', '');
                var pos = $(this).offset();
                var elemHeight = $(this).height();
                
                $('#tt_oppose_marketing').css({
                    'top': pos.top + elemHeight + 1,
                    'left': pos.left
                }).show();
            },
            function() {
                $('#tt_oppose_marketing').hide();
            }
    );
	
	    
    
	
	
	
	
    $('.results .tools .envoyer a').bind('click', function(e) {
        e.preventDefault();
        $('#tt_send_item').hide();
        $('#tt_send_item_email').hide();
        
        // facebook link
        var facebookUrl = 'http://www.facebook.com/sharer.php?';
        if($(this).parents('.details').length){
            facebookUrl += 'u=' + window.location;
            facebookUrl += '&t=' + escape($('.details .title').contents().filter(function(){
                return this.nodeType == 3;
            }).text().replace(/^\s+/,'').replace(/\s+$/,''));
        }else{
            facebookUrl += 'u=' + $(this).attr('href');
            facebookUrl += '&t=' + escape($(this).parents('.tools').siblings('.annuaire').find('.title a').text().replace(/^\s+/,'').replace(/\s+$/,''));
        }
        
		$('#tt_send_item .container a.facebook').attr('onclick', "window.open('"+facebookUrl+"', 'StatusBar', 'toolbar=no,resizable=no,scrollbars=yes,width=700,height=450,left=200,top=200');");

        // email popup1
        $('#tt_send_item .container .email').attr('href', $(this).attr('href'));
		$('#tt_send_item .container .email').attr('alt', $(this).attr('alt'));
        $('#tt_send_item_email input, #tt_send_item_email textarea').attr('value', '');
        $('#ajax-email-reply').hide();

        var pos = $(this).offset();        
        var elemHeight = $(this).height();
        
        if($('#tt_send_item').parent('.details').length) {
            pos.left += 77;
        }
        
        $('#tt_send_item').css({
            'top': pos.top + elemHeight + 1,
            'left': pos.left - 50
        });
        $('#tt_send_item').show();
        
        if($('#tt_send_item .email').is(':visible')) {
            $('#tt_send_item .email').removeClass('hover');
        }
    });
    $('#tt_send_item .container img').bind('click', function() {
        $('#tt_send_item').hide();        
        $('#tt_send_item_email').hide();
        $('#tt_send_item .email').removeClass('hover');
        
        $('#tt_send_item_email input, #tt_send_item_email textarea').attr('value', '');
        $('#ajax-email-reply').hide();
    });
	
	$('.tag_oppositiongmap').bind('click', function () {
	
		//alert("Yo");
	});
    
    $('#tt_send_item .email').bind('click', function(e) {
        e.preventDefault();
        // Get the value for this link and add it to the form
        var mainurl = $(this).attr('href'); 
		var titre = $(this).attr('alt'); 		
        var referer = window.location;        
        $('#tt_send_item_email').find('.mainurl').attr('value', mainurl);        
        $('#tt_send_item_email').find('.referer').attr('value', referer);
		$('#tt_send_item_email').find('.nameFiche').attr('value',titre);         
        $('#tt_send_item_email label').css('display', 'block');
        var pos = $(this).offset();
        var elemHeight = $(this).height();
        
        if($('#tt_send_item_email').parent('.details').length) {
            pos.left += 355;
        }
        
        $('#tt_send_item_email').css({
            'top': pos.top + elemHeight + 6,            
            'left': pos.left - 327
        });
        $('#tt_send_item_email').show();
        
        $(this).toggleClass('hover');
    });
    $('#tt_send_item_email .header a, #tt_send_item_email .ferme-link, #tt_send_item_email .ajax-email-reply-active').bind('click', function(e) {
        e.preventDefault();
        $('#tt_send_item_email').hide();
        $('#tt_send_item .email').removeClass('hover');
        
        $('#tt_send_item_email input, #tt_send_item_email textarea').attr('value', '');
        $('#ajax-email-reply').hide();
    });

    $('#tt_send_item_email .submit_wrapper .submit').hover(
        function() {
            var pos = $(this).offset();
            var posPopup = $('#tt_send_item_email').offset();
            var elemHeight = $(this).height();
            var tooltipValiderEmail = $(this).next('.email-tip-valider');
            tooltipValiderEmail.css({
                'top': pos.top - posPopup.top + elemHeight + 1,
                'left': pos.left - posPopup.left - 66
            });
            tooltipValiderEmail.show();
        },
        function() {
            $(this).next('.email-tip-valider').hide();
        }
    );
    
    $('#tt_send_item_email .submit').click(function(e) {	
	
		var urla="";
        e.preventDefault();         
        var objForm = $(this).parents('form');	
		var chainaction = objForm.attr('action');	
		
		 if (chainaction.indexOf('private') == -1) {
			urla = "/pro/sendemail";
		} else {
			urla = "/private/sendemail";
		}  		
		
        var postData = objForm.serialize(); 
        
        $.ajax({
            url: urla,
            type: 'POST',
            data: postData,
            success: function(data) {			
                var emailResponse = eval("(" + data + ")");
                var message ='';
                var mailSent = false;	
			
                switch(emailResponse.strReplyCode){
			
                    case 'no_post':
                        message = 'Veuillez réessayer';
                        break;
                    case 'invalid_post':						
                        message = 'Veuillez saisir un destinataire valide';
                        break;
					case 'invalid_postD':						
                        message = 'Veuillez saisir un destinataire valide';
                        break;							
					case 'invalid_postU':						
                        message = 'Veuillez saisir une adresse e-mail valide';
                        break;										
					case 'invalid_postN':						
                        message = 'Veuillez saisir un nom valide';
                        break;		
                    case 'email_sent':					
                        message = 'Votre e-mail a bien été envoyé';
                        mailSent = true;
                        break;
                }
                $('#ajax-email-reply span').text(message);
                if(mailSent){
                    $('#ajax-email-reply span').append(' | ');
                    $('#tt_send_item_email .ferme-link').addClass('ferme-link-active');
                    $('#ajax-email-reply').attr('class', 'ajax-email-reply-active');
                    $('#ajax-email-reply').show();
                }else {
                    $('#ajax-email-reply').attr('class', 'ajax-email-reply');
					$('#ajax-email-reply').show();
                }
            },
            error: function(msg) {
                $('#ajax-email-reply span').text('Une erreur est survenue, veuillez réessayer');
                $('#ajax-email-reply').show();
            }
        });
    });

    $('.sauvegardes-tip-list .link-to-sauvegardes, .sauvegardes-tip-list .voir').live('mouseover mouseout', function(event) {
        if(event.type == 'mouseover') {
            $(this).parent('.sauvegardes-tip-list').addClass('sauvegardes-tip-list-voir');
        } else {
            $(this).parent('.sauvegardes-tip-list').removeClass('sauvegardes-tip-list-voir');
        }
    });

   
    if(!$('#print-container').length) {
        $('#autres-numeros').click(function() {
            $(this).next('.autres-numeros-hidden').toggle();
            $(this).toggleClass('autres-numeros-hover');
        });
    }
    
    
    // Auto blur sor the search engine
    $('form .autoblur').live('focus', function() {
        if($(this).attr('value') == $(this).attr('rel')) {
            $(this).attr('value', '').addClass('input-black');
        }
    });
    $('form .autoblur').live('blur', function() {
        if($(this).attr('value').replace(/^\s+|\s+$/g,'') == '' || $(this).attr('value') == $(this).attr('rel')) {
            $(this).attr('value', $(this).attr('rel')).removeClass('input-black');
        }
    });
    
    if($('#narrow-list .result').length > 2) {
        $('#narrow-list .result:last').addClass('result-last-bloc');
    }
    
    $('.details-container .itineraire-options').bind('click', function(e) {
        e.preventDefault();
        $(this).toggleClass('itineraire-options-deployed');
        $('.details-container .itineraire-search-form').toggle();
        $('.details-container .itineraire-way').toggle();
    });
    
    $('.details-container .itineraire-way').bind('click', function(e) {
        e.preventDefault();
        $('.details-container .itineraire-way').removeClass('itineraire-way-hover');
        $(this).addClass('itineraire-way-hover');
    });
    //header form events
    $('.reverse-form-container .text-field').live('click', function(){
        if($(this).val() == 'ex.: 04 25 51 14 25, 03.23.36.77.12,...') $(this).val('');
    });
    $('.reverse-form-container .text-field').live('blur', function(){
        if(this.value.replace(/^\s+|\s+$/g,'')=='') this.value='ex.: 04 25 51 14 25, 03.23.36.77.12,...';
    });
    $('#short .submit input, #deployed .submit input, #short-reversed .submit input').click(function(){
        $(this).cleanSearchForm();
    });

//    $('#map_comment').keyup(function(){
//        limitChars('map_comment', 255, 'map_comment_chars');
//    })
	var onEditCallback = function(remaining){
		//$('.remaining-text p').text(remaining+ " caractéres restants");

		if(remaining > 1){
            $('.remaining-text p').text(remaining+ " caractères restants");
		}
        else
        {
            $('.remaining-text p').text(remaining+ " caractère restant");
        }
	}

	var onLimitCallback = function(){
		
	}

	$('#map_comment').limitMaxlength({
        attribute: 255,
		onEdit: onEditCallback,
		onLimit: onLimitCallback
	});

    // attach xiti
    $('.attach-xiti').click(function(){
        $(this).attachXiti();
    });
    // attach favorites
    $('a.add-to-favorites, a.heart').live('click', function() {
        $(this).addFavorites();
    });
	
	// Back button
	$('.retour-a-la-liste-container').bind('click', function(e) {
		e.preventDefault();
		
		history.go(-1);
	});
	
	$('.itineraire-form .itineraire-submit, .itineraire-results .votre-itineraire').bind('click', function(e) {
	
	    e.preventDefault();
	    
	    // Get the address
	    var startAddress = $('.itineraire-depart').val();
	    var goalAddress = $('.itineraire-arrivee').val();

        // Define travel mode
        var itineraireTravelMode = $('.itineraire-way-hover').hasClass('itineraire-men')?google.maps.TravelMode.WALKING:google.maps.TravelMode.DRIVING;
        
        // Define options (highways and tolls)
        var blnAvoidHighways = $('#avoidHighways').attr('checked');
        var blnAvoidTolls = $('#avoidTolls').attr('checked');

        var objDirectionRequest = {
            origin: startAddress,
            destination: goalAddress,
            travelMode: itineraireTravelMode,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: blnAvoidHighways,
			provideRouteAlternatives:true,
            avoidTolls: blnAvoidTolls,
            region: 'fr'
        };
    	var directionsService = new google.maps.DirectionsService();
        var objRoutes = directionsService.route(objDirectionRequest, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var objItineraireList = $('#itinerairePath');
				

                var objItineraireSteps = $(result.routes[0].legs[0].steps);
				 var objItineraireLegs = $(result.routes[0].legs[0]);
                var itineraireRows = '';
                
                // Clear the old path if exist
                objItineraireList.empty();
                // create rows				
                objItineraireSteps.each(function(i) {
                    itineraireRows += '<li>'+this.instructions+ ' sur ' +this.distance.text+ ' (environ ' +this.duration.text+ ')</li>';
                });
				 objItineraireList.html('<h2>'+ objItineraireLegs[0].distance.text +' en '+ objItineraireLegs[0].duration.text +' </h2>');
                objItineraireList.append(itineraireRows);
                
                directionsDisplay.setDirections(result);
            }
        });
	});
});




function fromGeoloc(e) {
	
	   e.preventDefault();
	    
	    // Get the address
	    var startAddress = $(this).cookie('current_location');
	    var goalAddress = $('.itineraire-arrivee').val();

        // Define travel mode
        var itineraireTravelMode = $('.itineraire-way-hover').hasClass('itineraire-men')?google.maps.TravelMode.WALKING:google.maps.TravelMode.DRIVING;
        
        // Define options (highways and tolls)
        var blnAvoidHighways = $('#avoidHighways').attr('checked');
        var blnAvoidTolls = $('#avoidTolls').attr('checked');

        var objDirectionRequest = {
            origin: startAddress,
            destination: goalAddress,
            travelMode: itineraireTravelMode,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: blnAvoidHighways,
			provideRouteAlternatives:true,
            avoidTolls: blnAvoidTolls,
            region: 'fr'
        };
    	var directionsService = new google.maps.DirectionsService();
        var objRoutes = directionsService.route(objDirectionRequest, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var objItineraireList = $('#itinerairePath');
				

                var objItineraireSteps = $(result.routes[0].legs[0].steps);
				 var objItineraireLegs = $(result.routes[0].legs[0]);
                var itineraireRows = '';
                
                // Clear the old path if exist
                objItineraireList.empty();
                // create rows				
                objItineraireSteps.each(function(i) {
                    itineraireRows += '<li>'+this.instructions+ ' sur ' +this.distance.text+ ' (environ ' +this.duration.text+ ')</li>';
                });
				 objItineraireList.html('<h2>'+ objItineraireLegs[0].distance.text +' en '+ objItineraireLegs[0].duration.text +' </h2>');
                objItineraireList.append(itineraireRows);
                
                directionsDisplay.setDirections(result);
            }
        
		
		
		});
	};














jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		attribute: 255,
		onLimit: function(){},
		onEdit: function(){}
	}, options);
	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(settings.attribute);
		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}

jQuery.fn.showMesSauvegardes=function() {
    var pos = $('#sauvegardes-trigger').offset();
    $('#sauvegardes-tip').css({
        'bottom': pos.bottom,
        'left': pos.left + 6
    });
    $('#sauvegardes-tip').show();
    $('#sauvegardes-trigger').addClass('sauvegardes-trigger_hover');
	
	if(isIE6) {
		$('#sauvegardes-trigger').css({'background-position':'left top'});
		if(!$('#sauvegardes-tip .sauvegardes-tip-list').length) {
			$('#sauvegardes-tip-container').css({'margin-top':-10})
		}
	}
};

jQuery.fn.hideMesSauvegardes=function(){
    $('#sauvegardes-tip').hide();
    $('#sauvegardes-trigger').removeClass('sauvegardes-trigger_hover');
	
	if(isIE6) {
		$('#sauvegardes-trigger').css({'background-position':'left bottom'});
		$('#sauvegardes-tip-container').css({'margin-top':0})
	}
};


jQuery.fn.getFavoritesPage=function(){
    // setting page to 1 if called without it
    if(undefined==page || page<1) page=1;
    // number of items on sauvegardes list
    itemsPerPage=5;
    // total items stored in cookie
    totalItems=favorites.length;
    // total pages
    totalPages=Math.ceil(totalItems/itemsPerPage);
    // set the page value to the max page if the page from client is bigger than the max page
    page=(totalPages<page)?totalPages:page;
    // set the offset for the start item to be displayed in list
    offset=(page-1)*itemsPerPage;
    // clear old items on page
    $('.sauvegardes-tip-list').remove();
    // build the html elements for each array entry
    listItems='';
    for(var i=offset;i<(offset+5);i++){


        if(undefined!=favorites[i]){
            // favorites[i].href|text|loc|phone
            // build first link to element
            blackSpan=$('<span>').attr({'class':'black'});
            blackSpan.text(favorites[i].text);
            linkAnchor=$('<a>').append(blackSpan);
            linkAnchor.append(favorites[i].loc);
            linkAnchor.attr({
                href: favorites[i].href,
                'class': 'link-to-sauvegardes'
            });
            // build phone span
            phoneSpan=$('<span>');
            phoneSpan.attr('class','phone');
            phoneSpan.text(favorites[i].phone);
            // build delete link
            deleteAnchor=$('<a>');
            deleteAnchor.text('Supprimer cette fiche');
            deleteAnchor.attr('href',i);
            deleteAnchor.attr({'class': 'sauvegardes-supprime'});
            deleteAnchor.click(function(event){
                event.preventDefault();
                j=$(this).attr('href');
                getPage=$('.current').text();
                favorites=jQuery.map(favorites,function(v,ii){
                    if(ii==j){
                        $(this).displaySauvegarderItem(v);
                        return null;
                    }
                    return v;
                });
                $(this).save();
                $(this).getFavoritesPage(getPage);
            });
            
            // build the secont link to element
            viewLink = $('<a>');
            viewLink.attr({'href': favorites[i].href, 'class':'voir'});
            viewLink.text('Voir');
            viewLink.click(function(i){
                location.href=favorites[i].loc;
            });
            
            
            // build the list item
            listItem=$('<div>');
            listItem.append(linkAnchor).append('&nbsp;<br>');
            listItem.append(phoneSpan).append('<br>');
            listItem.append(deleteAnchor);
            listItem.append(viewLink);
            listItem.attr('class','sauvegardes-tip-list');

            // append list items before the paginator
            $('#sauvegardes-tip-paging').before(listItem);
        }
    }

    // remove old pagination
    $('#sauvegardes-tip-paging').empty();
	$('#sauvegardes-tip-bottom').hide();
    if(!favorites.length) $('#sauvegardes-tip-paging').html('Aucune fiche sauvegardée<br>Cet espace vous permet de retrouver rapidement les contacts que vous avez sauvegardés via l\'icône   <img src="/images/icon_saveinfo.gif" height="16px" width="16px"/> ');
	
	
	if(!favorites.length) {
		$('#sauvegardes-tip-bottom').hide();
		} else {
		$('#sauvegardes-tip-bottom').show();
		$('#sauvegardes-tip-bottom').html(' Supprimer toutes les sauvegardes <span></span>');
		}

    // adding the "previous" button if page is not the first one
    if(page>1){
        fisrtImg=$('<a>');
        fisrtImg.attr('id', 'prevPage');
        fisrtImg.attr('class', 'prevPage');
        $('#sauvegardes-tip-paging').append(fisrtImg);
        $('#prevPage').click(function(e) {
            e.preventDefault();
            page--;
            $(this).getFavoritesPage();
        });
    }else{
        fisrtImg=$('<span>');
        fisrtImg.attr('class', 'inactive-left');
        $('#sauvegardes-tip-paging').append(fisrtImg);
    }
    // adding the rest of the buttons
    for(j=0;j<totalPages;j++){
        k=j+1;
        pageItem=$('<a>'+k+'</a>');
        pageItem.attr({'class':"digit"+((page==k)?" current":""),'id':'page'+k});
        $('#sauvegardes-tip-paging').append(pageItem);


        if(page!=k){
            $('#page'+k).click(function(){
                page=$(this).text();
                $(this).getFavoritesPage();
            });
        }
        
        if(k < totalPages) {
            pageItem.after('<span class="pipe">|</span>');
        }
    }
    // adding the last arrow if the current page is not the last page
    if(page<totalPages){
        lastImg=$('<a>');
        lastImg.attr('id', 'nextPage');
        lastImg.attr('class', 'nextPage');
        $('#sauvegardes-tip-paging').append(lastImg);
        $('#nextPage').click(function(e) {
            e.preventDefault();
            page++;
            $(this).getFavoritesPage();
        });
    }else{
        lastImg=$('<span>');
        lastImg.attr('class', 'inactive-right');
        $('#sauvegardes-tip-paging').append(lastImg);
    }
};

// just for testing
jQuery.fn.saveBase=function(){
    //build string
    strCookie='';
    var arrItem=new Array();
    var arrCookie=new Array();
    for(i=0;i<favoritesbase.length;i++){
        arrItem[0]=favoritesbase[i].href;
        arrItem[1]=favoritesbase[i].loc;
        arrItem[2]=favoritesbase[i].text;
        arrItem[3]=favoritesbase[i].phone;
        arrCookie[i]=arrItem.join(arrGlue);
    }
    //store to cookie
    $(this).cookie('favoritesCookie',arrCookie.join(objGlue));
};

jQuery.fn.save=function() {
    //build string
    strCookie='';
    var arrItem=new Array();
    var arrCookie=new Array();    
    
    for(i=0;i<favorites.length;i++){
        arrItem[0]=favorites[i].href;
        arrItem[1]=favorites[i].loc;
        arrItem[2]=favorites[i].text;
        arrItem[3]=favorites[i].phone;
        arrItem[4]=favorites[i].wsid;
        arrCookie[i]=arrItem.join(arrGlue);
    }

    //store to cookie
    $(this).cookie('favoritesCookie',arrCookie.join(objGlue));
};

jQuery.fn.getFavorites=function() {
    var fav=$(this).cookie('favoritesCookie');
    if(null==fav) return [];
    if(fav.length) fav=fav.split(objGlue);
    processed=[];
    for(var i=0;i<fav.length;i++){
        var item=fav[i].split(arrGlue);
        processed[i]={
            'href':item[0],
            'loc':item[1],
            'text':item[2],
            'phone':item[3],
            'wsid':item[4]
        };
    }
    if(processed.length) return processed;
    return [];
};

jQuery.fn.cookie=function(name,value) {
    if(undefined == name) return false;
    
    if(undefined != value) {        
        cookieExpire = 180; // days
        date = new Date();
        date.setDate(date.getDate() + cookieExpire);
        document.cookie = name + '=' + value + '; domain=.' + baseUrl.replace(/^http:\/\//,'').replace(/\/$/,'') + '; expires=' + date.toUTCString() + '; path=/;';
        
        return true;
    }        
    
    arrCookie = document.cookie;
    cookie = arrCookie.split(';');        
    for(var i = 0;i < cookie.length;i++) {
        var item = cookie[i].split("=");                
        item[0] = item[0].match(/[a-z0-9_]+/i);        
        if(name == item[0]) {
            return item[1];
        }
    }
    return null;
};

jQuery.fn.addFavorites=function() {
    if(favorites.length > 24){
        alert("Vous avez atteint le nombre maximal de fiches sauvegardées. Afin de sauvegarder une nouvelle donnée, veuillez en supprimer au moins une de vos sauvegardes 118000.fr");
        return;
    }
    
    var wsid = $(this).attr('rel').replace('wsid-', '');    
    var addObj;

    // retrieve the data from the "gTipObj" object.    
    $.each(gTipObj, function(index, item) {
        if(item.wsid == wsid) {
            objPhone = $(gTipObj[index].phone);
            addObj = {
                'href':gTipObj[index].href,
                'loc':' '+gTipObj[index].address.replace('<br>', ' '),
                'text':gTipObj[index].title.replace(/^\s+/, '').replace(/\s+$/, ''),
                //'phone':gTipObj[index].phone.replace(/^\s+/, '').replace(/\s+$/, ''),
                'phone':objPhone.is('img')?objPhone.attr('alt'):gTipObj[index].phone.replace(/^\s+/, '').replace(/\s+$/, ''),
                'wsid':gTipObj[index].wsid
            };
        }
    });
    
    if(!addObj) {
        $objResult = $(this).parents('.result').clone();
        $objResult.find('.adresseFlag').remove();
        textTitleNotParsed = !$objResult.find('.annuaire .title a').length?$objResult.find('.annuaire .title').text():$objResult.find('.title a').text();
        textTitle = textTitleNotParsed.replace(/(^\s+|\s+$)/g,'').replace(/^\s+/, '').replace(/\s+$/, '');
        textHref = !$objResult.find('.title a').length?document.location.href:$objResult.find('.title a').attr('href');

        addObj = {
                'href':textHref,
                'loc':' '+$objResult.getText().replace('<br>', ' '),
                'text':textTitle,
                /*'phone':(!$objResult.find('.phone_number img')?$objResult.find('.phone_number').text():$objResult.find('.phone_number').html()).replace(/^\s+/, '').replace(/\s+$/, ''),*/
                'phone':(!$objResult.find('.phone_number img').length?$objResult.find('.phone_number').text():$objResult.find('.phone_number img').attr('alt')),
                'wsid':$objResult.find('.wsid').text()
            };
    }

    var newFavorite=true;
    for(var i=0;i<favorites.length;i++){
        if(addObj.wsid==favorites[i].wsid){
            newFavorite=false;
            break;
        }
    }
    
    addObj.phone = addObj.phone.replace(/[^0-9]+/g,'');  
    
    if(favorites.length == 0){
        favorites[favorites.length] = addObj;
    }else if(newFavorite){
        var append = true;
        $.each(favorites, function(index, obj){
            if(obj.text.toLowerCase() > addObj.text.toLowerCase() && append){
                append = false;
                favorites.splice(index, 0, addObj);
            }
        });
        if(append) favorites[favorites.length] = addObj;
    }
    $(this).save();
    
    var trigerParent = $(this).parent();
    $(this).remove();
    trigerParent.prepend($('<span>').attr('class','sauve').text('Sauvé'));
    if(!trigerParent.hasClass('sauvegarder')){
        $('.result').each(function(){
            if($(this).find('.wsid').text() == addObj.wsid){
                $(this).find('.sauvegarder').empty().prepend($('<span>').attr('class','sauve').text('Sauvé'));
            }
        });
    }
    var e=jQuery.Event('click');
    e.preventDefault();
};

jQuery.fn.toolTipEnSavoir = function(){
    var state = $('#tool-tip-en-savoir').css('display');    
    if(state == 'block'){
        $('#tool-tip-en-savoir').css({'display':'none'});
        return;
    }
    $(this).parent().parent().prepend($('#tool-tip-en-savoir'));
    var reference = $(this).position();

    $('#tool-tip-en-savoir').css({
        'position':'absolute',
        'z-index':'100',
        'top':(reference.top + 16) + 'px',
        'left':(reference.left + 75) + 'px',
        'display':'block'
    });
};

jQuery.fn.toolTip = function(objParams){
    
    var state = $('#'+objParams.element).css('display');
    if(state == 'block'){
        $('#'+objParams.element).css({'display':'none'});
        return;
    }
    $(this).parent().parent().prepend($('#'+objParams.element));
    var reference = $(this).position();
    $('#'+objParams.element).css({
        'position':'absolute',
        'z-index':'100',
        'top':(reference.top + parseInt(objParams.y)) + 'px',
        'left':(reference.left + parseInt(objParams.x)) + 'px',
        'display':'block'
    });
};

jQuery.fn.popUpEmailContent = function(){
    return $('#div-pop-up-email-content').html();
};
jQuery.fn.popUpSMSContent = function(){
    return $('#div-pop-up-sms-content').html();
};

jQuery.fn.toggleSMSvalider = function(){
    var position = $(this).position();
    var state = $('#sms-tip-valider').css('display');
    if('block' == state){
        $('#sms-tip-valider').css({'display':'none'});
        return;
    }
    $('#sms-tip-valider').css({
        'position':'absolute',
        'top':(position.top + 29) + 'px',
        'left':(position.left - 92) + 'px',
        'display':'block'
    });
};

jQuery.fn.toggleEmailValider = function(){
    var position = $(this).position();
    var state = $('#email-tip-valider').css('display');
    if('block' == state){
        $('#email-tip-valider').css({'display':'none'});
        return;
    }
    $('#email-tip-valider').css({
        'position':'absolute',
        'top':(position.top + 31) + 'px',
        'left':(position.left + 220) + 'px',
        'display':'block'
    });
};

jQuery.fn.cleanSearchForm = function(){
    var form = $(this).closest("form");
    form.find('input[type="text"]').each(function(){
        if($(this).val().match(/ex\s*:/) || $(this).val() == 'ex.: 04 25 51 14 25, 03.23.36.77.12,...'){
            $(this).val('');
        }
    });	 
    
	if ($("#geoenlarge_checkbox")[0].checked)
    {
         form.append('<input type="hidden" name="geoenlarge" value="50">');
    } /*else {
		if(form.find("input:hidden[name=geoenlarge]").length>0)
			form.remove('<input type="hidden" name="geoenlarge" value="50">');		
		
	}*/
    //form[0].submit();
}

jQuery.fn.showDeployed = function(){
    $('#short').attr('class','');
    $('#form-head').attr('class','form-head-expand');
    $('#deployed').attr('class','deployed-active');
    $('#form-narrow').css({'display':'block'});
    $('.blue-fix').css({'padding-bottom':'10px'});
}
jQuery.fn.showShort = function(){
    $('#deployed').attr('class','');
    $('#form-head').attr('class','form-head-narrow');
    $('#short').attr('class','short-active');
    $('#form-narrow').css({'display':'none'});
    $('.blue-fix').css({'padding-bottom':'0px'});
}

jQuery.fn.createAutocomplete = function(formtype, inputnr, ptype){
//    var elementID = $(this).attr('id');
//    var minCharValue = 0;
//    var limitValue;
//
//    if (elementID != undefined)
//    {
//        if($(this).length){
//            $.each(minChars, function(key, value) {              
//              if (elementID == key)
//              {
//                minCharValue = value;
//              }
//            });
//            $.each(limit, function(key, value) {              
//              if (elementID == key)
//              {
//                limitValue = value;
//              }
//            });
//            $(this).autocomplete('/ajax/get/formtype/'+formtype+'/inputnr/'+inputnr+'/ptype/'+ptype, {
//                minChars: minCharValue,
//                max: limitValue,
//                cacheLength: 1,
//                delay: 0
//            });
//        }
//    }
}
jQuery.fn.fieldExample = function(){
    $(this).live('click', function(){
        if($(this).val() == $(this).attr('rel')) $(this).val('');
    });
    $(this).live('blur', function(){
        if($(this).val() == '') $(this).val($(this).attr('rel'));
    });
}

jQuery.fn.annuaireUpdate = function() {
    var annuaireRequest = $(this).attr('id');
    
    if(isHome){
        switch(annuaireRequest) {
            case 'professionnels':
                location.href = baseUrl.replace(/^[^0-9]+/,'http://www.');
                break;
            case 'particuliers':
                location.href = baseUrl.replace(/^[^0-9]+/,'http://annuaire.');
                break;
            case 'inverse':
                location.href = baseUrl.replace(/^[^0-9]+/,'http://annuaire-inverse.');
                break;
        }
    }else{
        $(this).siblings().attr('class','');
        $(this).attr('class','hover');
        var activeForm = $('.blue-fix').find('.short-reverse-active,.short-active,.deployed-active').attr('id');
        
        switch(annuaireRequest) {
            case 'professionnels':
                $('#form-head-left').text('Qui ? Quoi ?');
                $('#form-head-right').removeClass('hidden');
                $('input[name="sb_Professionnel1"]').val('sb_professionnel');
                $('input[name="sb_Prenom"]').attr('name','sb_CategoryName');
                $('input[name="sb_CategoryName"]').parent().siblings('label').text('Activité');
                $('input[name="sb_CategoryName"]').attr('value', '');

                
                //$("#ac_quiquoi_pro, #ac_quiquoi_prv").attr('formtype', '1');
                $("#ac_quiquoi_pro, #ac_quiquoi_prv").attr('inputnr', '1');
                
                
                //$("#ac_nom_pro, #ac_nom_prv").attr('formtype', '2');
                $("#ac_nom_pro, #ac_nom_prv").attr('inputnr', '4');
                
                
                //$("#ac_activite").attr('formtype', '2');
                $("#ac_activite").attr('inputnr', '5');                
                
                
                
                
                $('.autocomplete').attr('ptype', 'sb_professionnel');
                $('.autocomplete').unautocomplete();
                $('.autocomplete').autocomplete('/ajax/get/',{
                    minChars: 1,
                    max: 1,
                    delay: 0
                });

                if ($("#ac_quiquoi_pro").attr('rel') == $("#ac_quiquoi_pro").val())
                {
                    $("#ac_quiquoi_pro").attr('value', 'ex: Plombier, Alain Dupont,...');
                }
                $("#ac_quiquoi_pro").attr('rel', 'ex: Plombier, Alain Dupont,...');

                if ($("#ac_nom_pro").attr('rel') == $("#ac_nom_pro").val())
                {
                    $("#ac_nom_pro").attr('value', 'ex: Alain Dupont, Pierre Martin,...');
                }
                $("#ac_nom_pro").attr('rel', 'ex: Alain Dupont, Pierre Martin,...');
                
                if ($("#ac_quiquoi_prv").attr('rel') == $("#ac_quiquoi_prv").val())
                {
                    $("#ac_quiquoi_prv").attr('value', 'ex: Plombier, Alain Dupont,...');
                }
                $("#ac_quiquoi_prv").attr('rel', 'ex: Plombier, Alain Dupont,...');

                if ($("#ac_nom_prv").attr('rel') == $("#ac_nom_prv").val())
                {
                    $("#ac_nom_prv").attr('value', 'ex: Alain Dupont, Pierre Martin,...');
                }
                $("#ac_nom_prv").attr('rel', 'ex: Alain Dupont, Pierre Martin,...');

                if ($("#ac_activite").attr('rel') == $("#ac_activite").val())
                {
                    $("#ac_activite").attr('value', 'ex: Plombier, hôtel, serrurier,...');
                }
                $("#ac_activite").attr('rel', 'ex: Plombier, hôtel, serrurier,...');
                $('#ac_quiquoi_pro, #ac_ou, #ac_nom_pro, #ac_activite, #ac_adresse, #ac_cp_ville, #ac_departement, #ac_region, #ac_quiquoi_prv, #ac_nom_prv').fieldExample();



                if(activeForm == 'short-reversed'){
                    $('#short-reversed').attr('class','');
                    $('#short').attr('class','short-active');
                }

                $("#header").attr('class', 'header_pro');
                break;
            case 'particuliers':
                $('#form-head-left').text('Qui ?');
                $('#form-head-right').removeClass('hidden');
                $('input[name="sb_Professionnel1"]').val('sb_Particulier1');
                $('input[name="sb_CategoryName"]').attr('name','sb_Prenom');
                $('input[name="sb_Prenom"]').parent().siblings('label').text('Prénom');
                $('input[name="sb_Prenom"]').attr('value', '');



                $("#ac_quiquoi_pro, #ac_quiquoi_prv").attr('inputnr', '1');
                $("#ac_nom_pro, #ac_nom_prv").attr('inputnr', '6');
                $("#ac_activite").attr('inputnr', '7');
                
                
                
                $('.autocomplete').attr('ptype', 'sb_Particulier1');
                $('.autocomplete').unautocomplete();

                $('.autocomplete').autocomplete('/ajax/get/',{
                    minChars: 1,
                    max: 1,
                    delay: 0
                });

                if ($("#ac_quiquoi_pro").attr('rel') == $("#ac_quiquoi_pro").val())
                {
                    $("#ac_quiquoi_pro").attr('value', 'ex: Florence Mériaux, Enzo Petot,...');
                }
                $("#ac_quiquoi_pro").attr('rel', 'ex: Florence Mériaux, Enzo Petot,...');

                if ($("#ac_nom_pro").attr('rel') == $("#ac_nom_pro").val())
                {
                    $("#ac_nom_pro").attr('value', 'ex: Mériaux, Petot,...');
                }
                $("#ac_nom_pro").attr('rel', 'ex: Mériaux, Petot,...');
                

                if ($("#ac_quiquoi_prv").attr('rel') == $("#ac_quiquoi_prv").val())
                {
                    $("#ac_quiquoi_prv").attr('value', 'ex: Florence Mériaux, Enzo Petot,...');
                }
                $("#ac_quiquoi_prv").attr('rel', 'ex: Florence Mériaux, Enzo Petot,...');

                if ($("#ac_nom_prv").attr('rel') == $("#ac_nom_prv").val())
                {
                    $("#ac_nom_prv").attr('value', 'ex: Mériaux, Petot,...');
                }
                $("#ac_nom_prv").attr('rel', 'ex: Mériaux, Petot,...');
                
                if ($("#ac_activite").attr('rel') == $("#ac_activite").val())
                {
                    $("#ac_activite").attr('value', 'ex: Florence, Enzo,...');
                }
                $("#ac_activite").attr('rel', 'ex: Florence, Enzo,...');

                $('#ac_quiquoi_pro, #ac_ou, #ac_nom_pro, #ac_activite, #ac_adresse, #ac_cp_ville, #ac_departement, #ac_region, #ac_quiquoi_prv, #ac_nom_prv').fieldExample();

                if(activeForm == 'short-reversed'){
                    $('#short-reversed').attr('class','');
                    $('#short').attr('class','short-active');
                }
                $("#header").attr('class', 'header_private');
                break;
            case 'inverse':
                $('#form-head-left').text('A qui est ce numero ?');
                $('input[name="qui"]').val('ex : 04 25 51 14 25 ou 03.23.36.77.12,...');
                $('#form-narrow').css({'display':'none'});
                $('.blue-fix').css({'padding-bottom':'0px'});
                $('#form-head').attr('class','form-head-narrow');
                $('#form-head-right').attr('class','hidden');
                if(activeForm != 'short-reversed'){
                    $('#'+activeForm).attr('class','');
                    $('#short-reversed').attr('class','short-reverse-active');
                }
                break;
        }
    }
}

jQuery.fn.displaySauvegarderItem = function(item) {
    wsid = item.wsid;
    $('.result').each(function(){
        if($(this).find('.wsid').text() == wsid){
            $(this).find('.sauvegarder').empty().prepend($('<a>').attr('class','add-to-favorites').attr('rel','wsid-'+wsid).text('Sauvegarder'));
            $(this).find('.sauvegarder a').click(function(){
                $(this).addFavorites(item);
            });
            return;
        }
    });
}

jQuery.fn.attachXiti = function(){
    var xitiParams = $(this).attr('rel');
    $('.' + xitiParams).each(function(){
        var params = [];
        $(this).children().each(function(index){
            params[index] = $(this).text();
        });
        if(params.length == 4){
            xt_med(params[0], params[1], params[2], params[3]);
        }
    });
}

jQuery.fn.clearFavorites = function(){
    $('.results').children('.result').each(function(){
        if($(this).find('span.sauve').length){
            var wsid = $(this).find('span.wsid').text();
            $.each(favorites, function(index, item){
                if(wsid == item.wsid){
                    var current = item;
                }
            })
            $(this).find('span.sauve').remove();
            $(this).find('div.sauvegarder').append(
                $('<a>').attr({
                    'class':'add-to-favorites',
                    'rel':'wsid-' + wsid,
                    'title':'Sauvegarder'
                }).text('Sauvegarder')
            );
        }
    });
    favorites = [];
}


function checkJsHeader (frm) {
	
	var retour = true;
	
	if (frm.id == 'short') {
	
		if (($('input#ac_ou').val() == '') && ($('input#ac_quiquoi_pro').val() == '')) {
			retour = false;
		}
		
		var form = $(frm).closest("form");
		form.find('input[type="text"]').each(function(){
			if($(this).val() == $(this).attr('rel')){
					$(this).val('');
			}
		});
	}

	if (frm.id == 'deployed') {
		if ($('input#ac_nom_pro').val() == '' && $('input#ac_adresse').val() == '' && $('input#ac_activite').val() == '' && $('input#ac_cp_ville').val() == '' && $('input#ac_departement').val() == '' && $('input#ac_region').val() == '') {
			retour = false;
		}
		
		var form = $(frm).closest("form");		
		form.find('input[type="text"]').each(function(){
			if($(this).val() == $(this).attr('rel')){
					$(this).val('');
			}
		});		
	}

	if (frm.id == 'short-reversed') {
		if ($('input#ac_reversed').val() == '') {
			retour = false;
		}
		var form = $(frm).closest("form");		
		form.find('input[type="text"]').each(function(){
			if($(this).val() == $(this).attr('rel')){
					$(this).val('');
			}
		});		
		
	}	
	return retour;
}
