(function(){
    $.fn.target = function(){
        return $('.targetblank').click( function() {
        window.open(
             $(this).attr('href') );
             return false;
        });
    }
})(jQuery);

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
      for(var i=0; i<this.length; i++){
          if(this[i]==obj){
              return i;
          }
      }
      return -1;
    }
}
Number.prototype.nombreFormate = function (decimales, signe, separateurMilliers) {
    var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
    if (decimales == undefined) decimales = 2;
    if (signe == undefined) signe = '.';
    if (separateurMilliers == undefined) separateurMilliers = ' ';

    function separeMilliers (sNombre) {
        var sRetour = "";
        while (sNombre.length % 3 != 0) {
            sNombre = "0"+sNombre;
        }
        for (i = 0; i < sNombre.length; i += 3) {
            if (i == sNombre.length-1) separateurMilliers = '';
            sRetour += sNombre.substr(i, 3)+separateurMilliers;
        }
        while (sRetour.substr(0, 1) == "0") {
            sRetour = sRetour.substr(1);
        }
        return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
    }
    
    if (_sNombre.indexOf('.') == -1) {
        for (i = 0; i < decimales; i++) {
            _sDecimales += "0";
        }
        _sRetour = separeMilliers(_sNombre)+signe+_sDecimales;
    } else {
        var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));

        if(sDecimalesTmp.length > decimales) {
            var nDecimalesManquantes = sDecimalesTmp.length - decimales;
            var nDiv = 1;
            for (i = 0; i < nDecimalesManquantes; i++) {
                nDiv *= 10;
            }
            _sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
        } else {
            _sDecimales = sDecimalesTmp;
            for (i = sDecimalesTmp.length; i < decimales; i++) {
            _sDecimales += "0";
            }
        }
        _sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
    }
    if(_sRetour.length == decimales + 1){
        _sRetour ='0'+_sRetour;
    }
    return _sRetour;
}

$(document).ready( function () {
    $('a').target();
    $("#boiteAcheter").hover(
        function(){
            $(this).animate({
                left: "-1px"
            }, 500 );
        },
        function(){
            $(this).animate({
                left: "-180px"
            }, 1500 );
        }
    );
    activeSurvolUi("");
    //affiche et cache le div suivant
    $(".afficheCache").prepend('<span class="ui-icon ui-icon-triangle-1-s" style="float:left;margin-right:10px;"></span>');
    $(".afficheCache").click(
        function(){
            if($(this).next().is(":visible")){
                $(this).children("span").removeClass("ui-icon-triangle-1-n");
                $(this).children("span").addClass("ui-icon-triangle-1-s");
            }else{
                $(this).children("span").removeClass("ui-icon-triangle-1-s");
                $(this).children("span").addClass("ui-icon-triangle-1-n");
            }
            $(this).next("div").slideToggle("slow");
            return false;
        }
    );
    clignote();
    $('.bulle').bt({
        padding: 10,
        width: 300});
    $('.bulleMenu').bt({
        strokeStyle: '#CC0',
        fill: 'rgba(255, 229, 132, .9)',
        cssStyles: {color: 'black', fontWeight: 'bold', textAlign: 'center', fontSize: '18px'},
        shrinkToFit: true,
        cornerRadius: 20,
        spikeLength: 15,
        spikeGirth: 5,
        positions: ['right', 'bottom'],
        padding: 20,
        width: 300});
});

function activeSurvolUi(parentUi){
    if(parentUi==""){
        //survol de class ui
        $('.ui-state-default').hover(
            function(){
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
            }
        );
        $('.ui-state-highlight').hover(
            function(){
                $(this).removeClass('ui-state-highlight');
                $(this).addClass('ui-state-hover');
            },
            function(){
                $(this).addClass('ui-state-highlight');
                $(this).removeClass('ui-state-hover');
            }
        );
        $('.ui-state-hover').hover(
            function(){
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
            }
        );
        $('.ui-state-error').hover(
            function(){
                $(this).removeClass('ui-state-error');
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
                $(this).addClass('ui-state-error');
            }
        );
    }else{
        //survol de class ui
        $(parentUi+' .ui-state-default').hover(
            function(){
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
            }
        );
        $(parentUi+' .ui-state-highlight').hover(
            function(){
                $(this).removeClass('ui-state-highlight');
                $(this).addClass('ui-state-hover');
            },
            function(){
                $(this).addClass('ui-state-highlight');
                $(this).removeClass('ui-state-hover');
            }
        );
        $(parentUi+' .ui-state-hover').hover(
            function(){
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
            }
        );
        $(parentUi+' .ui-state-error').hover(
            function(){
                $(this).removeClass('ui-state-error');
                $(this).addClass('ui-state-highlight');
            },
            function(){
                $(this).removeClass('ui-state-highlight');
                $(this).addClass('ui-state-error');
            }
        );

    }
}

//Permet le survol de plusieurs lien sans affecter de style particulier
function activeSurvol(texte){ //idText li
    $(texte+" li").hover(
        function(){ $(this).addClass('ui-state-hover'); },
        function(){ $(this).removeClass('ui-state-hover'); }
    );
}

var clignoteVisible=true;
function clignote(){
    if(clignoteVisible){
        $(".blink").fadeTo(500, 1, function(){setTimeout("clignote()", 400)});
        clignoteVisible=false;
    }else{
        $(".blink").fadeTo(500, 0.1, function(){setTimeout("clignote()", 400)});
        clignoteVisible=true;
    }
}

function navigueNouvelleFenetre(url){
    window.open(url);
    return false;
}

function navigueUrl(selectIdContenu,url){
    $.ajax({
        type: "GET",
        dataType: "html",
        url: url,
        cache: false,
        success: function(data){
            $("#"+selectIdContenu).html(data);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            afficheErreur("Erreur d\'envois des données.",XMLHttpRequest.responseText);
        }
    });
}

/**
 *  Permet d'automatiser le chargement en fenetre
 * selectId = 'fenetreRaffraichie'
 * url = '/admin/formule'
 * array_post = { name: "nomform", valeur: "supprime" } si ="" on appele en GET
 */
function navigueDialogue(selectId, url, array_post){
    if(!document.getElementById(selectId)){
        $('<div id="'+selectId+'" title="Raffraichissement des donn&eacute;es"></div>').appendTo("body");
        $('#'+selectId).dialog({
            autoOpen: false,
            modal: true,
            stack: true,
            width: 700,
            position: 'top',
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });
    }
    $("#"+selectId).html("<div id='AttendEnvois' class='ui-corner-all' style='display:block;'></div>");
    $("#"+selectId).dialog('open');
    if(url!=""){
        if(array_post==""){
            navigueUrl(selectId,url);
        }else{
            $.ajax({
                type: "POST",
                dataType: "html",
                url: url,
                data: array_post,
                success: function(data){
                    $("#"+selectId).html(data);
                },
                error : function(XMLHttpRequest, textStatus, errorThrown){
                    afficheErreur("Erreur d\'envois des données.",XMLHttpRequest.responseText);
                }
            });
        }
    }
}

/**
 *  Permet d'automatiser l'affichage d'erreurs
 * texte = texte d'erreur
 */
function afficheErreur(texte, details){
    if(!document.getElementById("fenetreErreur")){
        $('<div id="fenetreErreur" title="Probl&egrave;me de validation" class="ui-state-error"></div>').appendTo("body");
        $('#fenetreErreur').dialog({
            autoOpen: false,
            modal: true,
            stack: true,
            width: 400,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });
    }
    if(details==undefined)details="pas de details";    
    $("#fenetreErreur").html('<div class="ui-state-error ui-corner-all tac fwb" style="margin-top:5px;padding:10px;"><span class="ui-icon ui-icon-alert" style="float:right;margin-right:.3em;"></span>'+texte+'<br /><br /><p class="afficheCacheDetail tal fs12 cPoint"><span class="ui-icon ui-icon-triangle-1-s" style="float:left;margin-right:5px;"></span>d&eacute;tails</p><div style="display:none;padding:7px;" class="fs10 bordB">'+details+'</div></div><br /><cite class="tar fs10">Veuillez nous excuser pour ces d&eacute;sagr&eacute;ments encourus.</cite>');
    $("#fenetreErreur").dialog('open');
    $(".afficheCacheDetail").click(
        function(){
            $(this).next("div").slideToggle("slow");
            if($(this).next().is(":visible")){
                $(this).children("span").removeClass("ui-icon-triangle-1-n");
                $(this).children("span").addClass("ui-icon-triangle-1-s");
            }else{
                $(this).children("span").removeClass("ui-icon-triangle-1-s");
                $(this).children("span").addClass("ui-icon-triangle-1-n");
            }
        }
    );
}


/*POUR FORMULAIRES*/
function activeAjaxForm(idForm,urlForm, functBefore, functSucces){
    if(functBefore==undefined)functBefore= valideForm;
    if(functSucces==undefined)functSucces= function(data){ traiteReponse(data,$("form#"+idForm)); };
    $('form#'+idForm).ajaxForm({
        url: urlForm,
        type: 'POST',
        dataType:  'json',
        cache: false,
        beforeSubmit: functBefore,
        success:  functSucces,
        error : function(XMLHttpRequest, textStatus){
            $("#AttendEnvois").fadeOut("slow");
            $(".NFButtonRight, .NFButtonLeft, .NFButton").fadeIn("slow");  //on affiche le bouton
            afficheErreur("Erreur d\'envois des données.", XMLHttpRequest.responseText);
        }
    });
}

function animeErreur(id,texte){
    if(!document.getElementById("cadreErreur")){
        $("<div id='cadreErreur' class='ui-corner-all'></div>").appendTo("form");
    }
    $("#cadreErreur").show();
    $("#"+id).addClass("erreur");
    pos = $("#"+id).position();
    pos.left= pos.left+$("#"+id).width()+20;
    $("html,body").animate({
        scrollTop:pos.top-10
    },1000);
    $("#cadreErreur").animate({
        top: pos.top-10,
        left : pos.left
        }, 1500 );
    $("#"+id).focus();
    $("#cadreErreur").html(texte);
}

function valideForm(formData, jqForm, options){
    $("#cadreErreur").hide();
    for(var i=0; i < formData.length; i++){
        if($("#"+formData[i].name).attr("type")=="hidden") continue;
        $("#"+formData[i].name).removeClass("erreur");
        if(!formData[i].value || $('#'+formData[i].name).css("color")=="gray"){
            animeErreur(formData[i].name, "Vous devez remplir tous les champs");
            return false;
        }
    }
    if(!document.getElementById("AttendEnvois"))
        $("<div id='AttendEnvois' class='ui-corner-all'>&nbsp;</div>").appendTo("form");
    $("#AttendEnvois").fadeIn("slow");
    $(".NFButtonRight, .NFButtonLeft, .NFButton").fadeOut("slow");  //on cache le bouton
    return true;
}

function traiteReponse(data,form){
    if(!document.getElementById("resultatEnvois"))
        $("<div align='center'><div id='resultatEnvois' title='Reponse du site www.kiddyparc.com'></div></div>").insertAfter(form);
    else $("#resultatEnvois").dialog('open');
    $("#AttendEnvois").fadeOut("slow");
    $(".NFButtonRight, .NFButtonLeft, .NFButton").fadeIn("slow");
    if(data.raffraichiBlank != undefined){   //ouverture dune nouvelle fenetre
        $("#resultatEnvois").html("Une nouvelle fen&ecirc;tre va s'ouvrir pour afficher votre devis.<br />Si votre navigateur bloque la fen&ecirc;tre, <a href='"+data.raffraichiBlank+"' title='ouvrir le devis' target='_blank'>vous pouvez cliquer ici pour l'ouvrir</a>.");
        $('#resultatEnvois').dialog({
            autoOpen: true,
            modal: true,
            stack: true,
            width: 400,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });
        $("#resultatEnvois").dialog('open');
        window.open(data.raffraichiBlank);
        return;
    }
    if(data.fenetreAjax != undefined){   //ouverture dune nouvelle fenetre AJAX
        $("#resultatEnvois").html(data.fenetreAjax);
        $('#resultatEnvois').dialog({
            autoOpen: true,
            modal: true,
            stack: true,
            width: 500,
            position: 'top',
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });
        $("#resultatEnvois").dialog('open');
        return;
    }
    if(data.id == undefined){   //envois reussi ou impossible
        if(data.texte == undefined) $("#resultatEnvois").html(data);
        else{
            $("#resultatEnvois").html(data.texte);
            form.fadeOut("fast",
                function(){ 
                    $('html,body').animate({
                        scrollTop:100
                    },1000);
                }
            );
            if(data.raffraichi != undefined){
                window.setTimeout(function(){
                    document.location = data.raffraichi;
                },1000);
            }
        }
    }else{
        $("#"+data.id).addClass("erreur");
        animeErreur(data.id,data.texte);
    }
}
/*FIN FORMULAIES*/

function animeHover(idDiv){
    $("#"+idDiv).hover(
        function(){
            $(this).fadeTo("fast", 100);
        }, function(){
            $(this).fadeTo("fast", 60);
        }
    );
    $("#"+idDiv).fadeTo("fast", 60);
}

/*Fonction de dessin pour le site
 * ex: dessineDiv("nomdiv","vert")
 */
function dessineDiv(idDiv,couleur){
    $("#"+idDiv).backgroundCanvas();
    switch(couleur){
        case "vert":
            $(window).resize(function(){ DrawBackground_vert(idDiv); });
            $("#"+idDiv).change(function(){ DrawBackground_vert(idDiv); });
            DrawBackground_vert(idDiv);
            break;
        case "vertFonce":
            $(window).resize(function(){ DrawBackground_vertFonce(idDiv); });
            DrawBackground_vertFonce(idDiv);
            break;
        case "orange":
            $(window).resize(function(){ DrawBackground_orange(idDiv); });
            DrawBackground_orange(idDiv);
            break;
        case "orangeFonce":
            $(window).resize(function(){ DrawBackground_orangeFonce(idDiv); });
            DrawBackground_orangeFonce(idDiv);
            break;
        case "rose":
            $(window).resize(function(){ DrawBackground_rose(idDiv); });
            DrawBackground_rose(idDiv);
            break;
        case "bleuVert":
            $(window).resize(function(){ DrawBackground_bleuVert(idDiv); });
            DrawBackground_bleuVert(idDiv);
            break;
        case "jaune":
            $(window).resize(function(){ DrawBackground_jaune(idDiv); });
            DrawBackground_jaune(idDiv);
            break;
        case "rouge":
            $(window).resize(function(){ DrawBackground_rouge(idDiv); });
            DrawBackground_rouge(idDiv);
            break;
        case "rougeFonce":
            $(window).resize(function(){ DrawBackground_rougeFonce(idDiv); });
            DrawBackground_rougeFonce(idDiv);
            break;
        default:
            $(window).resize(function(){ DrawBackground_bleu(idDiv); });
            DrawBackground_bleu(idDiv);
            break;
    }
}

function DrawBackground_vert(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_vert);
}
function DrawBackground_vertFonce(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_vertFonce);
}
function DrawBackground_orange(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_orange);
}
function DrawBackground_orangeFonce(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_orangeFonce);
}
function DrawBackground_bleu(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_bleu);
}
function DrawBackground_rose(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_rose);
}
function DrawBackground_bleuVert(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_bleuVert);
}
function DrawBackground_jaune(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_jaune);
}
function DrawBackground_rouge(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_rouge);
}
function DrawBackground_rougeFonce(idDiv){
    $("#"+idDiv).backgroundCanvasPaint(BackgroundPaintFkt_rougeFonce);
}


function BackgroundPaintFkt_vert(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#4B9B28";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#9EEF7C');
    backgroundGradient.addColorStop(1 ,'#C9F7B6');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}
function BackgroundPaintFkt_vertFonce(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#4B9B28";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#4B9B28');
    backgroundGradient.addColorStop(1 ,'#9EEF7C');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_orangeFonce(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#FA6707";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#FEC535');
    backgroundGradient.addColorStop(1 ,'#FA6707');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_orange(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#A6592B";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#FFB284');
    backgroundGradient.addColorStop(1 ,'#FFD5BC');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_bleu(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#3636A6";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#A6A6FF');
    backgroundGradient.addColorStop(1 ,'#E7F2FF');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_bleuVert(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#70D7BD";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#96EBD6');
    backgroundGradient.addColorStop(1 ,'#ADEBDB');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_rose(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#A12A3F";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#E175C6');
    backgroundGradient.addColorStop(1 ,'#F0B0E0');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_jaune(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#D2B752";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#FFE584');
    backgroundGradient.addColorStop(1 ,'#FFEBA0');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}

function BackgroundPaintFkt_rouge(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#CD5066";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#F88196');
    backgroundGradient.addColorStop(1 ,'#FA9DAD');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}
function BackgroundPaintFkt_rougeFonce(context, width, height, elementInfo ){
    var options = {x:0, height: height, width: width, radius:10,  border: 0 };
    context.fillStyle = "#D5161F";
    $.canvasPaint.roundedRect(context,options);
    var options = {x:1,y:1, height: height-2, width: width-2, radius:10,  border: 0 };
    var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 2);
    backgroundGradient.addColorStop(0 ,'#D5161F');
    backgroundGradient.addColorStop(1 ,'#EA777C');
    options.border = elementInfo.borderLeft;
    context.fillStyle = backgroundGradient;
    $.canvasPaint.roundedRect(context,options);
}