﻿var menuItem = null;


jQuery(document).ready(function() {
    $('a[rel=external]').attr('target', '_blank');
    $("a.gotoHead").click(function() {
        $(window).scrollTo(0, { duration: 1000 });
    });

    /* associate actions with formation list block */
    $('#formationByEditor').addClass('hidden');
    $('#formationByKeywords').addClass('hidden');
    $('#actionFormationByEditor').click(actionFormationByEditorClick);
    $('#actionFormationByTheme').click(actionFormationByThemeClick);
    $('#actionFormationBySearchEngine').click(actionFormationBySearchEngineClick);
    // recherche case
    /* $('.menu > li').hover(actionHover, actionHover2); */

    /* Recherche sur le site*/
    $('#searchHeaderText').focus(actionFocusSearchAllWebsite);
    $('#newSearchText').focus(actionFocusNewSearchAllWebsite);
    $('#searchRightText').focus(actionFocusFormationSearchAllWebsite);
    $('#inscriptionExpressText').click(function() {
        $('#inscriptionExpressText').val('');
    });
    $('#searchFMSText').click(function() {
        $('#searchFMSText').val('');
    });

    /* Affiche ou masque les résultats de la recherche*/
    $('#search_formation').click(function() {
        hideAndDisplaySearchDiv('Formation');
    });
    $('#search_seminaire').click(function() {
        hideAndDisplaySearchDiv('Seminaire');
    });
    $('#search_certification').click(function() {
        hideAndDisplaySearchDiv('Certification');
    });
    $('#search_cursus').click(function() {
        hideAndDisplaySearchDiv('Cursus');
    });
    $('#search_autres').click(function() {
        hideAndDisplaySearchDiv('Autres');
    });

    /* this is for the Fiche Formation page */
    var className = "linkSessions";
    var className2 = "tableSession";

    accordeonDropDown(className, className2);

    $("#FMSBloc").click(function() {
        window.location = baseUrl + "formations-intra/formations-sur-mesure/etape2";
    });


    /**** Formations sur mesure ****/

    $("#searchFMSButton").click(function() {
        var searchValue = $("#searchFMSText").val();
        block();
        searchValue = searchValue.replace(/\+/g, "{plus}");
        $.ajax({
            url: baseUrl + "formations-intra/formations-sur-mesure/recherche/" + searchValue,
            success: function(data) {
                displayGammes(data);
            }
        });
    });

    $(".G_surmesure_title").click(function() {
        var GammeName = $(this).prev('div').html();
        $.ajax({
            url: baseUrl + "formations-intra/formations-sur-mesure/Gamme/" + GammeName,
            success: function(data) {
                displayGammes(data);
            }
        });
    });

    $(".E_surmesure_title").click(function() {
        var EditeurName = $(this).prev('div').html();

        $.ajax({
            url: baseUrl + "formations-intra/formations-sur-mesure/Editeur/" + EditeurName,
            success: function(data) {
                displayGammes(data);
            }
        });
    });

    function displayGammes(data) {
        $(".otherSearch").show();
        $(".container").removeAttr("style");
        $('#programmes').hide();
        $('#themes').html(data);
        $('#themes').show();
        self.location.hash = '#themes';
        $(".getProgramme").click(function() {
            var id = $(this).attr("id");
            var title = $(this).prev("div").html();
            $.ajax({
                url: baseUrl + "formations-intra/formations-sur-mesure/programmes/" + id + "/" + title,
                success: function(data) {
                    displayProgrammes(data, true);
                }
            });
        });

        function displayProgrammes(data, anchor) {
            $(".backToList").show();
            $(".container").removeAttr("style");
            $('#themes').hide();
            $('#programmes').html(data);
            $('#programmes').show();

            if (anchor)
                self.location.hash = '#programmes';

            $(".hideProgramme").click(function() {
                $(".backToList").hide();
                $('#programmes').hide();
                $('#themes').show();
            });

            $(".AddProgramme").click(function() {
                var title = $(this).next('div').html();
                $.ajax({
                    url: baseUrl + "formations-intra/formations-sur-mesure/add/programme/" + title,
                    success: function(data) {
                        upFSMBloc();
                        displayProgrammes(data, false);
                    }
                });
            });

            $(".DeleteProgramme").click(function() {
                var title = $(this).next('div').html();
                $.ajax({
                    url: baseUrl + "formations-intra/formations-sur-mesure/delete/programme/" + title,
                    success: function(data) {
                        downFSMBloc();
                        displayProgrammes(data, false);
                    }
                });
            });
        }
    }

    $(".checkbox_step2").click(function() {
        var title = $(this).next('div').html();
        var isChecked = $(this).attr('checked') ? true : false;
        if (!isChecked) {
            $.ajax({
                url: baseUrl + "formations-intra/formations-sur-mesure/delete/step2/" + title,
                success: function(data) {
                    downFSMBloc();
                }
            });
        }
        else {
            $.ajax({
                url: baseUrl + "formations-intra/formations-sur-mesure/add/step2/" + title,
                success: function(data) {
                    upFSMBloc();
                }
            });
        }
    });

    $("#saveLittlePeach").click(function() {
        block();
        window.location = baseUrl + "formations-intra/formations-sur-mesure/etape5";

    });

    /**** Fin Formations sur mesure ****/


    $("form.addFormation").ajaxForm();


    // Lien pour l'élément "Plus d'infos" du menu droit
    $('#rmDemandeInfosFormLink').click(function() {

        var link = baseUrl + $('#demandeInfosFormLink').text();
        window.location = link;
    });

    $('#rmCallbackFormLink').click(function() {

        var link = baseUrl + $('#callbackFormLink').text();
        window.location = link;
    });


    //Pour le Panier Etape 1
    $("#goToEtape2").click(function() { goToEtape('2'); });
    //Pour le Panier Etape 2
    checkPanierEtape2();

    // Formulaire de recherche
    // Header
    $('#searchHeader').submit(function() {

        if ($('#searchHeaderText').val() == "Rechercher sur tout le site" ||
            $('#searchHeaderText').val() == "") {
            return false;
        }
        return true;
    });

    // page de résultat
    $('#newSearch').submit(function() {

        if ($('#newSearchText').val() == "Rechercher sur tout le site" ||
            $('#newSearchText').val() == "") {
            return false;
        }
        return true;
    });

    // rechercher une formation
    $('#rightSearch').submit(function() {

        if ($('#searchRightText').val() == "Référence, mot clé..." ||
            $('#searchRightText').val() == "") {
            return false;
        }
        return true;
    });

    // inscription express
    $('#inscription_express').submit(function() {

        if ($('#inscriptionExpressText').val() == "Référence" ||
            $('#inscriptionExpressText').val() == "") {
            return false;
        }
        return true;
    });


    //patch to keep a regular size in the container
    //the '47' is needed because height doesn't take into account the margin and the padding
    var menuCategorieHeight = $(".menuCategorie").height() + 47;
    var containerRightHeight = $(".containerRight").height();
    var centralHeight = $(".container").height();

    if (centralHeight < menuCategorieHeight || centralHeight < containerRightHeight) {

        if (menuCategorieHeight > containerRightHeight)
            $(".container").height(menuCategorieHeight - 15);
        else
            $(".container").height(containerRightHeight - 15);
    }

});

function upFSMBloc() {
    var nbModule = $(".nbModuleFMS").html();
    var newValue = 1;
    if (nbModule == null || nbModule == "aucun") {
        $("#FMSBloc").addClass("selected2");
        $("#goToLuigi").removeClass("disabled");
    }
    else {
        newValue = parseInt(nbModule) + 1;
        $(".singPlurFMS").html("modules sélectionnés");
    }
    $(".nbModuleFMS").html(newValue.toString());
}

function downFSMBloc() {
    var nbModule = $(".nbModuleFMS").html();
    var newValue = parseInt(nbModule) - 1;
    if (newValue == 0) {
        $("#goToLuigi").addClass("disabled");
        $("#FMSBloc").removeClass("selected2");
        $(".nbModuleFMS").html("aucun");
    }
    else
        $(".nbModuleFMS").html(newValue.toString());
    if (newValue == 1 || newValue == 0)
        $(".singPlurFMS").html("module sélectionné");
}

function checkPanierEtape2() {


    var canSubmit = true;

    if ($("#PanierEtape").val() == 2) {
        $(".prenom").each(function() {
            if ($(this).val() == "Prénom" || $(this).val() == "")
                canSubmit = false;
        });

        $(".nom").each(function() {
            if ($(this).val() == "Nom" || $(this).val() == "")
                canSubmit = false;
        });

        $(".select").each(function() {
            if ($(this).val() == 0)
                canSubmit = false;
        });

        if (canSubmit) {
            $("#goToEtape3").removeClass("disabled");
            $("#goToEtape3").click(function() { goToEtape('3'); });
        }
        else {
            $("#goToEtape3").addClass("disabled");
        }
    }

}


function numberOfParticipantsChanged(formation) {

    var NumberOfParticipants = $(formation).val();

    if (!isNaN(NumberOfParticipants) && NumberOfParticipants > 0) {
        updateNumberOfParticipants(formation);

        var total = 0;

        $(".nbParticipants").each(function() {

            var price = $(this).attr("price").replace(' € HT', '');
            total += price * $(this).val();
        });


        $("#total").html(number_format(total, 0, ',', ' ') + ' € HT');
        $("#goToEtape2").removeClass("disabled");
        $("#goToEtape2").click(function() { goToEtape('2'); });

        $(".participantError_" + $(formation).attr('id').replace(/\//g, "_").replace(/ /g, "_")).hide();

    }
    else {

        $("#goToEtape2").addClass("disabled");
        $("#goToEtape2").click(function() { });

        if ($(formation).attr('id') != undefined)
            $(".participantError_" + $(formation).attr('id').replace(/\//g, "_").replace(/ /g, "_")).show();
    }
}

function updateNumberOfParticipants(formation) {

    var NumberOfParticipants = $(formation).val();
    var formation = $(formation).attr("id").split('_');
    var Code = formation[1];
    var Place = formation[2];
    var Date = formation[3].replace(/\//g, "_");

    $.post(baseUrl + "Panier/updateFormation/" + Code + "/" + Place + "/" + Date + "/" + NumberOfParticipants, {}, null);
}

function removeFormationFromPanier(formationToDelete) {

    var formation = $(formationToDelete).attr("id").split('_');
    var Code = formation[1];
    var Place = formation[2];
    var Date = formation[3].replace(/\//g, "_");

    $(formationToDelete).parent().parent().parent().remove();
    $.post(baseUrl + "Panier/RemoveFormation/" + Code + "/" + Place + "/" + Date, {}, updatePanierCount);
    numberOfParticipantsChanged();
    updateTotal();
}

function updateTotal() {

    var total = 0;

    $(".formation").each(function() {

        total += ($(this).attr('total').replace(' € HT', '') * 1);

    });

    $("#total").html(number_format(total, 0, ',', ' ') + ' € HT');
}



function goToEtape(etapeNumber) {

    //first we need to make sure we have some formations, if it is the case then we call the real saving in the post back
    $.post(baseUrl + "Panier/countFormations/", {}, isPanierEmptyFromEtape);


    switch (etapeNumber) {
        case "2":
            if (!$("#goToEtape2").hasClass("disabled"))
                window.location = "etape" + etapeNumber;
            break;
        case "3":
            if (!$("#goToEtape3").hasClass("disabled"))
                window.location = "etape" + etapeNumber;
            break;
        default:
            window.location = "etape" + etapeNumber;
            break;
    }


}



function isPanierEmptyFromEtape(total) {
    if (total < 1) {
        block();
        showPanierEmptyMessageAndRedirect();
    }
}

function savePanier() {

    //first we need to make sure we have some formations, if it is the case then we call the real saving in the post back
    $.post(baseUrl + "Panier/countFormations/", {}, isPanierEmpty);
    
}

function isPanierEmpty(total) {
    if (total > 0) {
        block();
        $.post(baseUrl + "Panier/SavePanier", {}, function() { unblock(); setTimeout("goToEtape(5)", 100); });
    }
    else {
        showPanierEmptyMessageAndRedirect();
    }
}

function showPanierEmptyMessageAndRedirect() {
    $.blockUI({ css: {
        border: 'none',
        padding: '15px',
        backgroundColor: '#000',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: .5,
        color: '#fff'
    },
        message: '<h1>Le panier est vide. Vous allez être redirigé sur la page d\'acceuil</h1>'
    });

    setTimeout("unblock(); setTimeout(\"window.location.href = baseUrl\", 100);", 3000);
    
}

function block() {
    $.blockUI({ css: {
        border: 'none',
        padding: '15px',
        backgroundColor: '#000',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: .5,
        color: '#fff'
    },
    message: '<h1>Traitement en cours. Veuillez patienter s\'il vous plaît</h1>'
    }); 
}

function unblock() {
    $.unblockUI({}); 
}



function closeDiv() {
    $.modal.close();
}

function addFormationToPanier(formId) {
  
    submitAForm(formId);
    $.post(baseUrl + "Panier/countFormations/", {}, updatePanierCount);

    
    var myForm = document.getElementById(formId);

    $("#formationName").html(myForm.Title.value.replace(/_/g, '\''));

    if (myForm.Lieu.value != "empty")
        $("#DateAndPlace").html("<p>du " + myForm.DateShow.value + " à " + myForm.Lieu.value + "</p>");

    $("#popupPlusInfos").click(function() {
        var url = $(this).find("a").attr('href');
        url = baseUrl + "formations/G_" + toUrl(myForm.Gamme.value) + "/" + myForm.Reference.value + "_.html";

        window.location = url;
    });
}

function addCalendrierToPanier(formId) {

    var myForm = document.getElementById(formId);
    var postURL = baseUrl + "Panier/AddFormation?time=" + Math.floor((new Date()).getTime() / 1000); //$(formId).attr("action");
   
    // build the post data
    var data = "&Title=" + myForm.Title.value.replace(/_/g, '\'');
    data += "&Reference=" + myForm.Reference.value;
    data += "&Duree=" + myForm.Duree.value;
    data += "&Lieu=" + myForm.Lieu.value;
    data += "&Date=" + myForm.Date.value;
    data += "&DateShow=" + myForm.DateShow.value;
    
    $.ajax({
        type: "POST",
        url: postURL,
        data: data,
        success: function() {
            $.post(baseUrl + "Panier/countFormations/", {}, updatePanierCount);

            $("#formationName").html(myForm.Title.value.replace(/_/g, '\''));

            if (myForm.Lieu.value != "empty")
            $("#DateAndPlace").html("<p>du " + myForm.DateShow.value + " à " + myForm.Lieu.value + "</p>");

            $("#popupPlusInfos").click(function() {
            var url = $(this).find("a").attr('href');
            url = baseUrl + "formations/G_" + toUrl(myForm.Gamme.value) + "/" + myForm.Reference.value + "_.html";

            window.location = url;
        });
        }
    });
}

function viderMaSelection() {

    $(".formation").each(function() {

        removeFormationFromPanier(this)
    });

    $("#total").html(number_format(0, 0, ',', ' ') + ' € HT');


}
function updatePanierCount(total) {
    if (total > 0) {
        $("#panierCountDiv").addClass("selected");
        $("#panierCountDiv").html('<a href="' + baseUrl + 'Panier/etape1"><p id="panierCount">vous avez sélectionné<br />' + total + ' formation(s)</p></a>');
    }
    else {
        $("#panierCountDiv").removeClass("selected");
        $("#panierCount").html('aucune formation<br/>sélectionnée');
    }
}

function updateTotalRepas(repas) {

    //need to remove number formating and multiply by 1 to convert from string to number
    var price = parseInt($(repas).attr("price").replace(' € HT', ''));
    var total = parseInt($("#total").attr("value"));


    if ($(repas).is(':checked')) {
        $("#total").html(number_format((total + price), 0, ',', ' ') + ' € HT');
        $("#total").attr("value", total + price);
    }
    else {
        $("#total").html(number_format((total - price), 0, ',', ' ') + ' € HT');
        $("#total").attr("value", total - price);
    }

    saveParticipant(repas);
}




function submitAForm(formId) {
    
    if($("#" + formId) != null)
        $("#" + formId).submit();
}

function buildFormationId(id) {
    var formationId = "";
    var idParts = id.split('_');

    for (var i = 3; i < idParts.length - 1; i++)
        formationId += idParts[i] + '_';

    formationId += idParts[idParts.length - 1];

    return formationId;
}

function buildParticipantId(id) {
    var participantId = "";
    var idParts = id.split('_');

    for (var i = 2; i < idParts.length - 1; i++)
        participantId += idParts[i] + '_';

    participantId += idParts[idParts.length - 1];

    return participantId;
}

function clearMe(elem) {

    if (elem.value == "Prénom" || elem.value == "Nom")
        elem.value = "";

}


function saveParticipant(elem) {


    var formationId = buildFormationId(elem.id);
    var participantId = buildParticipantId(elem.id);

    var FirstName = "Prénom";
    var LastName = "Nom";
    var Place = "empty";
    var Prix = "0 € HT";
    var Date = "01_01_1900";
    var Repas = "0 € HT";
    var FormationCode = "";
    var FormationPlace = "";
    var FormationDate = "";
    var nbParticipants = 1;

    FormationCode = $("#formationInfoCode_" + formationId).val();
    FormationPlace = $("#formationInfoPlace_" + formationId).val();
    FormationDate = $("#formationInfoDate_" + formationId).val();


    nbParticipants = $("#formationInfoNbParticipants_" + formationId).val();

    if ($("#prenom_participant_" + participantId).val() != "")
        FirstName = $("#prenom_participant_" + participantId).val();

    if ($("#nom_participant_" + participantId).val() != "")
        LastName = $("#nom_participant_" + participantId).val();


    if ($("#select_participant_" + participantId).val() != 0) {
        Place = $("#select_participant_" + participantId).val().split('-')[0].replace(/ /g, '_');
        Date = $("#select_participant_" + participantId).val().split('-')[1].replace(/\//g, '_').replace(/ /g, '');
        Prix = $("#select_participant_" + participantId).val().split('-')[2].replace(/\//g, '_').replace(/ /g, '').replace("€HT", '');
    }
    
    if (Place != "empty") {


        //uncheck if we changed location
        if (elem.type == "select-one") {
            $("#forfaitRepasParis_participant_" + participantId).attr('checked', false);
            $("forfaitRepasProvince_participant_ " + participantId).attr('checked', false);
        }

        if ($("#forfaitRepasParis_participant_" + participantId).is(':checked'))
            Repas = $("#forfaitRepasParis_participant_" + participantId).attr("price");
        else if ($("#forfaitRepasProvince_participant_" + participantId).is(':checked'))
            Repas = $("#forfaitRepasProvince_participant_" + participantId).attr("price");


        //refresh the page if we changed location
        if (elem.type == "select-one") {
            $("#forfaitRepasParis_participant_" + participantId).attr('checked', false);
            $("forfaitRepasProvince_participant_ " + participantId).attr('checked', false);

            $.post(baseUrl + "Panier/AddParticipant/" + FormationCode + "/" + FormationPlace + "/" + FormationDate + "/" + FirstName + "/" + LastName + "/" + Place + "/" + Date + "/" + Repas + "/" + Prix + "/" + participantId, { async: false }, function() { window.location.reload(); });
        }
        else {
            $.post(baseUrl + "Panier/AddParticipant/" + FormationCode + "/" + FormationPlace + "/" + FormationDate + "/" + FirstName + "/" + LastName + "/" + Place + "/" + Date + "/" + Repas + "/" + Prix + "/" + participantId, { async: false }, null);
        }

        checkPanierEtape2();

    }
    else {
        $.post(baseUrl + "Panier/AddParticipant/" + FormationCode + "/" + FormationPlace + "/" + FormationDate + "/" + FirstName + "/" + LastName + "/" + Place + "/" + Date + "/" + Repas + "/" + Prix + "/" + participantId, { async: false }, null);
    }

    checkPanierEtape2();

}

function saveEtape3() {
    submitAForm("OrderInfosForm");
}

function accordeonDropDown(className, className2) {

    $("." + className).click(function() {

        if ($(this).children("a").is(".active")) {
            $("." + className + " a").removeClass("active");
            $(this).next("." + className2).hide()
        } else {
            $("." + className + " a").removeClass("active");
            $(this).children("a").addClass("active");
            $("." + className).next("." + className2).hide();
            $(this).next("." + className2).show();
        }
    });
}




/*function actionHover() {
if (menuItem != null) 
{
menuItem.find('ul.subMenu1').slideUp("fast");
menuItem = null;
} //if

$(this).find('ul.subMenu1').slideDown("fast");
}

function actionHover2() {
menuItem = $(this);
checkHover();		
}

function checkHover() {
if (menuItem != null) 
menuItem.find('ul.subMenu1').slideUp("fast");
} //checkHover */


function actionFormationByEditorClick() {
    $('#formationByTheme').addClass('hidden');
    $('#formationByEditor').removeClass('hidden');
    $('#formationByKeywords').addClass('hidden');
    $('#actionFormationByEditor').addClass('selected');
    $('#actionFormationByTheme').removeClass('selected');
    $('#actionFormationBySearchEngine').removeClass('selected');   
}

function actionFormationByThemeClick() {
    $('#formationByTheme').removeClass('hidden');
    $('#formationByEditor').addClass('hidden');
    $('#formationByKeywords').addClass('hidden');
    $('#actionFormationByEditor').removeClass('selected');
    $('#actionFormationByTheme').addClass('selected');
    $('#actionFormationBySearchEngine').removeClass('selected');
}

function actionFormationBySearchEngineClick() {
    $('#formationByTheme').addClass('hidden');
    $('#formationByEditor').addClass('hidden');
    $('#formationByKeywords').removeClass('hidden');
    $('#actionFormationByEditor').removeClass('selected');
    $('#actionFormationByTheme').removeClass('selected');
    $('#actionFormationBySearchEngine').addClass('selected');  
}


function actionFocusSearchAllWebsite() {
    var sSearchValue = $('#searchHeaderText').val('');
}

function actionFocusNewSearchAllWebsite() {
    var sSearchValue = $('#newSearchText').val('');
}

function actionFocusFormationSearchAllWebsite() {
    var sSearchValue = $('#searchRightText').val('');
}

function hideAndDisplaySearchDiv(divToDisplay) {
    var divs = $(".resultatsRecherche > div");
    for (var i = 0; i < divs.length; i++) {
        var content = $(divs[i]).attr("class");
        if (content.search(/recherche/) != -1) continue;
        if (content.search(divToDisplay) != -1)
            $(divs[i]).css("display", "block");
        else
            $(divs[i]).css("display", "none");
    }
}


//////////////////////////calendar functions ////////////////
function makeSelected(idSelect, idDeSelect) {
    $('#' + idSelect).addClass('selected');
    $('#' + idDeSelect).removeClass('selected');
}

function goToCalendar(Type, Name) {
    window.location.href = baseUrl + "formations-inter/calendriers/" + Type + '/' + Name;
}


/////////////////////////////////////////////////////////////



function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function(n, prec) {
        var k = Math.pow(10, prec); return (Math.round(n * k) / k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec); var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/); i = _[0].length % 3 || 3;

        _[0] = s.slice(0, i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep + '$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec); if (prec >= 1 && decPos !== -1 && (s.length - decPos - 1) < prec) {
        s += new Array(prec - (s.length - decPos - 1)).join(0) + '0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec + new Array(prec).join(0) + '0';
    }
    return s;
}

function toUrl(param) {
    var temp = param;

    temp = temp.toLowerCase();
    temp = temp.replace("<br/>", "-");
    temp = temp.replace(/ /g, "-");
    temp = temp.replace(/\'/g, "-");
    temp = temp.replace(/\\/g, "-");
    temp = temp.replace(/!/g, "-");
    temp = temp.replace(/\,/g, "-");
    temp = temp.replace(/:/g, "-");
    temp = temp.replace(/\?/g, "-");
    temp = temp.replace(/\(/g, "-");
    temp = temp.replace(/\)/g, "-");
    temp = temp.replace(/&/g, "-");
    temp = temp.replace(/\./g, "-");
    temp = temp.replace(/é/g, "e");
    temp = temp.replace(/è/g, "e");
    temp = temp.replace(/ë/g, "e");
    temp = temp.replace(/ê/g, "e");
    temp = temp.replace(/à/g, "a");
    temp = temp.replace(/â/g, "a");
    temp = temp.replace(/ä/g, "a");
    temp = temp.replace(/ï/g, "i");
    temp = temp.replace(/î/g, "i");
    temp = temp.replace(/ô/g, "o");
    temp = temp.replace(/ö/g, "o");
    temp = temp.replace(/õ/g, "o");
    temp = temp.replace(/ü/g, "u");
    temp = temp.replace(/û/g, "u");
    temp = temp.replace(/\+/g, "-");
    temp = temp.replace(/-----/g, "-");
    temp = temp.replace(/----/g, "-");
    temp = temp.replace(/---/g, "-");
    temp = temp.replace(/--/g, "-");
    temp = temp.replace(/_/g, "-");
    return temp;
}