var oldContent = false ;
function displayAjax ( sUrl, targetDiv , backupOldDiv  ) {
    var div = $('#'+targetDiv) ;
    $.ajax({
        type: "GET",
        url: sUrl,
        async: false,
        dataType: 'html',
        beforeSend: function(){
            div.show().addClass('loading').html('Chargement en cours') ;
        },
        success: function(msg){
            div.html ( msg ) ;            
            ondomready();            
        },
        complete: function(){
            div.removeClass('loading');
        }
    });
    return false;
}



function sendForm( form , targetDiv ){
    $.post($('#'+form).attr('action'), $("#" + form).serialize(), function ( msg ) {
        $('#'+targetDiv).html(msg);
    },'html');
    return;
}

function add_cart ( type_product , param , product_id ) {
    if( $.isArray ( param ) == false ){
        post = new Array(param) ;
    }else{
        post = param ;
    }

    data_post = {
        domain: post
    }
    

    if( product_id ) {
        data_post = { 
            hosting: post ,
            product_id: product_id 
        }
    }else if( type_product == 'hosting'){
        data_post = {
            hosting: post
        }
    }
    //if( param_suppl ){
    //data_post.param_suppl = param_suppl ;
    //}
    $.ajax({
        url: '/cart/update_cart' ,
        data: data_post ,
        type: 'POST',
        dataType: 'json',
        error: function(){
            displayFlash('Erreur inattendue')
        },
        success: function( data ){
            displayFlash(data.msg);
            if( data.err ){
                return ;
            }
            update_nb_cart( data.nb );
            refresh_cart ( data ) ;
        }
    });    
}

/**
 * update
 */
function update_nb_cart( nb ) {
    if( nb ){
        $('#lnkMyCart').text('Mon panier (' + nb + ')');
    }else{
        $('#lnkMyCart').text('Mon panier');
    }
    
}

function date_naissance(){
    $("#date_naissance").datepicker(('option', {
        dateFormat: 'yy-mm-dd' ,
        defaultDate: -(365*20),
        changeYear: true ,
        minDate: new Date(1900,1  ,1) ,
        maxDate: -365 ,
        firstDay: 1 ,
        yearRange: '1900:2020'
    }));

}


function save_tld_prefs() {
    arr = new Array();
    $.each($('#blocSearch input[type=checkbox]:checked'),function(idx,el){
        arr[idx] = $(el).val() ;
    });
    $.cookie('prefs_tld' , arr , {
        expires: 7,
        path: '/'
    });
}



function refresh_cart( data ) {

    div_col = $('#rightCol') ;
    if( div_col.length ) {
        if( $('#side_cart').length == 0 ){
            el = $('<div/>',{
                id: 'side_cart'
            })
            .html(
                $('<strong/>',{
                    text: 'Mon panier'
                }))
            .append(
                $('<div/>',{
                    id: 'inside_cart'
                }).addClass('progress')
                )
            .append(
                $('<div/>',{
                    text: ' '
                }).addClass('bottom')
                );
            

                
            if( $('#shortcuts').length){
                $('#shortcuts').after(el).hide().fadeIn('slow');
            }else{
                div_col.prepend(el);
            }
            div_col.prepend($('#bloc_without_id'));
            
        }
        
        is_search_page = (location.href.indexOf('/domains/search') != -1) ? '/1' : '';
        $.ajax({
            url: host_site + '/cart/inside_side_cart'+is_search_page ,
            type: 'GET',
            data: {},
            cache: false , 
            dataType: 'json',
            success: function( data ) {
                $('#side_cart div:first').html(data.html).removeClass('progress');
                update_nb_cart(data.nb);
            }
        });
    }else{
        $.ajax({
            url: host_site + '/cart/inside_side_cart' ,
            type: 'GET',
            data: {},
            cache: false ,
            dataType: 'json',
            success: function( data ) {
                update_nb_cart(data.nb);
            }
        })
        
    }
}


function displayFlash ( setText) {
    if( setText ){
        if( $('#flash').is(':visible')){
            $('#flash').remove();
        }
        var el = $('<div/>',{
            id: 'flash'
        })
        .text(setText)
        .hide();
        
        $('body').prepend(el);
    }
    if( $('#flash').length ) {
        $('#flash').slideDown('slow').delay(1000).slideUp();
    }
}

function autoClick() {
    var q = getAutoClick();
    if( q ) {
        if( $('#'+q)){
            $('#'+q).click();
        }
    }
}
function getAutoClick() {
    var temp = document.location.href.split('#');
    if( temp.length>1 && temp[1] ){
        return temp[1];
    }
    return false ;
}


function add_to_cart ( redirect ) {
    var form_cart = $('#add_to_cart') ;
    $.ajax({
        url: form_cart.attr('action'),
        data: form_cart.serialize(),
        type: 'POST',
        dataType: 'json',
        error: function(){
            displayFlash('Erreur inattendue');
        },
        success: function(data){
            displayFlash(data.msg);
            if( data.err ){
                return ;
            }
            if( redirect ){
                document.location.href = '/cart';
            }
        }
    })

}


/**
 * backupOldDiv()
 */
function backupOldDiv(div){
    if( $('#'+div) && $('#'+div).html()){
        oldContent = $('#'+div).html();
        return ; 
    }
    oldContent = false ;
}

function restoreLastDiv( div ) {
    if( oldContent ){
        if(confirm('Confirmez le retour vers la liste ?\n\nToute modification en cours sera annulée')){
            $('#'+div).html(oldContent);
        }
        return false ;
    }
    alert('Aucun contenu précédent trouvé - la page va se rafraichir');
    window.location.reload();
    return false ;
}

function isInteger(s) {
    return (s.toString().search(/^-?[0-9]+$/) == 0);
}


jQuery.validator.addMethod('not_equal_to', function(value, element, param) {
    return value != jQuery(param).val();
}, 'La valeur doit etre modifiée'
);

// http://regexlib.com/REDetails.aspx?regexp_id=391
// autre possibilité : http://regexlib.com/REDetails.aspx?regexp_id=138 plus restricitve
jQuery.validator.addMethod("domain_name", function(value, element) {
    // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
    return this.optional(element) || /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/i.test(value);
}, "Merci de spécifier un nom de domaine valide");


jQuery.validator.addMethod("sld", function(value, element) {
    // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
    return this.optional(element) || /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)$/i.test(value);
}, "Merci de spécifier un nom de domaine valide");

jQuery.validator.addMethod("siret", function(value, element) {
    return this.optional(element) || /^([0-9]{14})$/i.test(value);
}, "Numéro de SIRET invalide");

jQuery.validator.addMethod("postal_code", function(value, element) {
    return this.optional(element) || /^([0-9]{5})$/i.test(value);
}, "Le code postal ne peut pas contenir de lettres ou de caractères accentués");

// Nom  prénom ville : alphanum avec les caractères spéciaux classiques
jQuery.validator.addMethod("regex_name", function(value, element) {
    return this.optional(element) || /^[À-ÿa-zA-Z0-9\- °&\'\"\.\:\;]+$/i.test(value);
}, "Caractère invalide");


jQuery.validator.addMethod("phone", function(value, element) {
    return this.optional(element) || /([0-9\-\+ ])$/i.test(value);
}, "Caractère invalide");

// Nom  prénom ville : alphanum avec les caractères spéciaux classiques
jQuery.validator.addMethod("login_rapido", function(value, element) {
    return this.optional(element) || /^RAPIDO\-([a-zA-Z]{2})[0-9]+$/i.test(value);
}, "Login Rapidomaine invalide");


jQuery.validator.addMethod("expiration_date", function(value) {
    temp = value.split('/');
    if( temp[0].length == 1){
        value = '0' + value ;
    }

    if( value.length != 7 ){
        return false;
    }

    if( temp.length == 1 ){
        return false ;
    }
    if( temp[0]>12){
        return false ;
    }
    return true ;
}, 'Date d\'expiration invalide');

jQuery.validator.addMethod("cvc", function(value) {
    return value.length == 3 ;
}, '3 caractères de longueur');






// @TODO MARCHE PAS
jQuery.validator.addMethod("domain_name_without_tld", function(value, element) {
    return this.optional(element) || /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))$/i.test(value);
}, "Merci de spécifier un nom de domaine valide");

jQuery.validator.addMethod("dns", function(value, element) {
    return this.optional(element) || /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/i.test(value);
}, "Merci de renseigner une url de DNS valide");



/**
     * 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. Keep in mind that you have to use the same path and domain
     *       used when the cookie was set.
     *
     * @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
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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;
    }
};



jQuery.fn.DefaultValue = function(text){
    return this.each(function(){
        if(this.type != 'text' && this.type != 'password' && this.type != 'textarea')
            return;

        //Store field reference
        var fld_current=this;

        //Set value initially if none are specified
        if($(this).val()=='') {
            $(this).val(text).addClass('default').removeClass('focus');
        } else {
            //Other value exists - ignore
            return;
        }

        //Remove values on focus
        $(this).focus(function() {
            if($(this).val()==text || $(this).val()=='')
                $(this).val('').removeClass('default').addClass('focus');
        });


        //Place values back on blur
        $(this).blur(function() {
            if($(this).val()==text || $(this).val()=='')
                $(this).val(text).addClass('default').removeClass('focus');
        });

        //Capture parent form submission
        //Remove field values that are still default
        $(this).parents("form").each(function() {
            //Bind parent form submit
            $(this).submit(function() {
                if(fld_current.value==text) {
                    fld_current.value='';
                }
            });
        });
    });
};
