/* Treeview variables */
var AllowCollapse = false, Expand = true, IsRootNode = true;

/* Product variables */
var hideTab = true;
var SessionTabIndex, videoLinkText, videoAutoPlay;
var ExpandText, CollapseText;

/* Mail variables */
var To, ToBcc, DefaultFrom, SendMailCloseText, SendMailTitle, SendmailSuggestiontext, SendMailCommentText, MailSendOK = "Votre email a bien été envoyé.", MailSendFailure = "Une erreur est survenue, votre email n'a pu être envoyé.";

/* News listing variables */
var news, visibleNews, pageNum, pageSize;

/* Map variables */
var geocoder, map, latlng, infowindow, address, myOptions;

/* Tooltip variables */
var ToolTipCandidates, UniqueNumber;

/* Mail function */
function SendMail(maildata) {
    $.ajax({
        url: '/_vti_bin/webfactory/webfactory.svc/Email',
        data: JSON.stringify(maildata),
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        complete: function(request, status) {
            if (status == 'success')
                alert(MailSendOK);
            else
                alert(MailSendFailure);
        }
    });
}

function ValidateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}


/* listing functions */
function selectCategory(category) {

    var direction = !$(".jq_desc", news).length ? 1 : -1;

    if (category.length == 0) {

        visibleNews = $(news).clone();

        $(visibleNews).attr("first", 0);

        if ($(visibleNews).filter("[topnews=1]").length > 0) {
            $($(visibleNews).filter("[topnews=1]").get().sort(function(a, b) {

                if ($(a).attr("date") == $(b).attr("date")) {
                    return 0;
                }
                else if ($(b).attr("date") > $(a).attr("date")) {
                    return 1 * direction;
                }
                else {
                    return -1 * direction;
                }
            })[0]).attr("first", 1);
        }
    }
    else {
        visibleNews = $(news).filter("[category='" + category + "']").clone();

        $(visibleNews).attr("first", 0);

        if ($(visibleNews).filter("[topcategory=1]").length > 0) {
            $($(visibleNews).filter("[topcategory=1]").get().sort(function(a, b) {

                if ($(a).attr("date") == $(b).attr("date")) {
                    return 0;
                }
                else if ($(b).attr("date") > $(a).attr("date")) {
                    return 1 * direction;
                }
                else {
                    return -1 * direction;
                }

            })[0]).attr("first", 1);
        }
    }

    visibleNews = $(visibleNews).get().sort(function(a, b) {

        if ($(a).attr("first") != $(b).attr("first")) {
            return -($(a).attr("first") - $(b).attr("first"));
        }
        else {
            if ($(a).attr("date") == $(b).attr("date")) {
                return 0;
            }
            else if ($(b).attr("date") > $(a).attr("date")) {
                return 1 * direction;
            }
            else {
                return -1 * direction;
            }
        }
    });

    $(visibleNews).removeClass('actu-first').addClass('actu');
    $(visibleNews[0]).removeClass('actu').addClass('actu-first');

    display();
}

function display() {
    $(".news-panel").empty();

    for (i = 1; i <= Math.ceil(visibleNews.length / pageSize); i++) {
        if (i == 1) $(".news-panel").append("<div class='jQuery-page' page='" + i + "' ></div>");
        else $(".news-panel").append("<div class='jQuery-page' page='" + i + "' style='display:none'></div>");

        $(".jQuery-pageCount").text(Math.ceil(visibleNews.length / pageSize));

        pageNum = 1;

        setPage();

        DoCufon();

    }

    $.each(visibleNews, function(index, item) {
        $("[page='" + Math.ceil((index + 1) / pageSize) + "']").append(item);
    });
}

function setPage(page) {
    switch (page) {
        case 1:
            if ($(".jQuery-page:visible").next(".jQuery-page").length == 1) {
                $(".jQuery-page:visible").hide().next(".jQuery-page").show();
                pageNum++;
            }
            break;
        case -1:
            if ($(".jQuery-page:visible").prev(".jQuery-page").length == 1) {
                $(".jQuery-page:visible").hide().prev(".jQuery-page").show();
                pageNum--;
            }
            break;
    }

    if (pageNum == 1) $(".jQuery-previous").removeClass("wf-prev").addClass("wf-prev-deactivated");
    else $(".jQuery-previous").removeClass("wf-prev-deactivated").addClass("wf-prev");

    if (pageNum == Math.ceil(visibleNews.length / pageSize)) $(".jQuery-next").removeClass("wf-next").addClass("wf-next-deactivated");
    else $(".jQuery-next").removeClass("wf-next-deactivated").addClass("wf-next");


    $(".jQuery-pageNum").text(pageNum);
}

function UpdatePackagePrice() {

    var TotalPrice = $(".jquery_elearningtotalprice");

    var GlobalPrice = eval($.map($(".jquery_elearningprice:checked"), function (n, i) { return ($(n).attr("price")); }).join("+") + ";");

    if (GlobalPrice == undefined) GlobalPrice = "-";
    //else GlobalPrice = GlobalPrice.nombreFormate(2, TotalPrice.attr("Decimal"), TotalPrice.attr("Thousand"));

    TotalPrice.text(TotalPrice.attr("PriceTemplate").replace("{Price}", GlobalPrice).replace("{Currency}", TotalPrice.attr("Currency")));
}

$(function () {

    /** Accordéon des parametres de page **/

    /* Au chargement, on met une classe Show au H3 */
    if ($("#accordion > div").css('display') != 'none')
        $("#accordion > h3").addClass('show');

    /* Sur le click (h3), switch de class CSS + show/hide de la 1ère div contenue */
    $("#accordion > h3").live('click', function () {

        if ($("#accordion > h3").hasClass('show')) $("#accordion > h3").removeClass('show').addClass('hide');
        else $("#accordion > h3").removeClass('hide').addClass('show');

        $("#accordion > div").toggle('blind', {}, 150);
    });

    if ($("#TabPageProperties").length) $("#TabPageProperties").tabs();

    /** Accordéon des parametres de page **/

    /** Treeview **/

    if (AllowCollapse) {
        $('[RootNode]').live('click', function (event) {
            if (!($.inArray(event.target.nodeName.toUpperCase(), ['CANVAS', 'RECT', 'A', 'CUFON']) != -1 &&
              $(event.target).parentsUntil('[RootNode]').parent().has('a').length != 0)) {
                $("[ChildNode='" + $(this).attr("RootNode") + "']").slideToggle();
                if ($(this).hasClass("intitule-domaines-plus") || $(this).hasClass("intitule-domaines-moins")) {
                    $(this).toggleClass("intitule-domaines-plus intitule-domaines-moins");
                }
            }
        });

        $('.jquery-collapse-all').live('click', function (event) {
            if ($("[ChildNode]:visible").length != 0) {
                $("[ChildNode]").slideUp();
                $('[RootNode].intitule-domaines-moins').removeClass("intitule-domaines-moins").addClass("intitule-domaines-plus");
            }
            else {
                $("[ChildNode]").slideDown();
                $('[RootNode].intitule-domaines-plus').removeClass("intitule-domaines-plus").addClass("intitule-domaines-moins");
            }
        });

        if (Expand)
            $("[ChildNode]").hide();
    }

    /* Masque les blocs dans la navigation "category" */
    if (!IsRootNode) {
        $(".article, .domaine-formation, .domaines-bottom").hide();
    }

    /** Treeview **/

    /** Fiche produit **/

    /* Onglets */
    if ($('.product-tabs').length) $('.product-tabs').tabs({ fx: { opacity: 'toggle'} });

    /* Cacher les onglets vide */
    if (hideTab) {
        $(".product-tabs > div").each(function (index, Element) {
            var hasChild = false;
            $(this).find(".ms-WPBody").each(function () {
                if ($.trim($(this).children().html()).length > 0)
                    hasChild = true;
            });
            if (!hasChild)
                $(".product-tabs li > a[href='#" + this.id + "']").parent().hide();
        });
    }
    /* Onglets */

    /* Video */
    if (typeof videoUrl != "undefined") {
        $("#player").flowplayer(
			"/_LAYOUTS/Demos/ClientSide/flowplayer-3.2.2-0.swf",
			{
			    key: "#@66804b03b3b27f18eb2",
			    clip: {
			        autoPlay: true,
			        autoBuffering: true,
			        url: videoUrl,
			        height: 390,
			        width: 550
			    }
			});

        $("#player").flowplayer(0).load();

        $('#popup-video').dialog({
            autoOpen: false,
            modal: true,
            width: 564,
            height: 413,
            resizable: false,
            closeOnEscape: true,
            closeText: 'Fermer',
            draggable: false,
            open: function (event, ui) {
                $("#player").flowplayer(0).play();
            },
            close: function (event, ui) {
                $("#player").flowplayer(0).stop();
            }
        });

        $('.block-video').wrapInner('<a class="popin-video"/>').find('img').attr('alt', videoLinkText);

        $(".popin-video").click(function () {
            $('#popup-video').dialog('open');
            return false;
        });

        if (videoAutoPlay) $(".popin-video").click();
    }
    /* Video */

    /* Sessions */
    if (typeof SessionTabIndex != "undefined") {
        $('.goToSessionTab').click(function () {
            $('.product-tabs').tabs("select", SessionTabIndex);
        });
    }
    /* Sessions */


    /* Envoi d'email */
    /* Envoyer à un collegue */
    if ($(".send-dialog").length) {
        var to = $("#MailTo"),
			comment = $("#MailComment"),
			from = $("#MailFrom"),
			firstName = $("#FirstName"),
			lastName = $("#LastName"),
			allFields = $([]).add(to).add(comment).add(from).add(firstName).add(lastName);

        $("#MailSend").click(function (event) {
            if (!SubscriptionValidation()) {
                return;
            }
            var maildata = {
                email: {
                    From: (from.val().length != 0 ? from.val() : DefaultFrom),
                    To: to.val(),
                    ToBcc: ToBcc,
                    Subject: SendMailTitle + ' - ' + document.title,
                    Message: '<a href="mailto:' + from.val() + '">' + firstName.val() + ' ' + lastName.val() + '</a> ' + SendmailSuggestiontext + ' <a href="' + document.URL + '">' + document.title + '</a>' + (comment.val().length != 0 ? '<br/><br/>' + SendMailCommentText + ' : <br/>' + comment.val() : '')
                }
            };

            SendMail(maildata);

            $("*").dialog('close');
            event.stopImmediatePropagation();
        });

        $(".send-dialog:gt(0)").remove();

        $(".send-dialog").dialog({
            autoOpen: false,
            modal: true,
            height: 350,
            width: 308,
            resizable: false,
            closeOnEscape: true,
            closeText: SendMailCloseText,
            draggable: false,
            open: function (event, ui) { allFields.val(''); }
        });

        $("li.send a").live('click', function (event) {
            $(".send-dialog").dialog('open');
        });
    }
    /* Inscription à un évènement */
    if ($(".jquery_subscriptionForm").length) {
        $(".jquery_subscription2").hide();

        var defaultValue = $(".jquery_container").html();

        var form = $(".jquery_subscriptionForm").html();
        $(".jquery_subscriptionForm").html('');

        $(".jquery_subscription").live('click', function () {
            $(".jquery_container").hide();
            $(".jquery_container").html(form);
            $(".jquery_container").show();
        });

        $("#chkAccompagnement").live('click', function () {
            $(".jquery_subscription2").slideToggle();
        });

        $("#sendSubscriptionForm").live('click', function () {
            var mailHtml = $("#civility1").val() + ' ' + $("#firstName1").val() + " " + $("#lastName1").val() + "<br/>" + $("#job1").val() + ' de la société ' + $("#socity1").val() + "<br/>";

            if ($("#address1").val().length != 0) mailHtml += $("#address1").val() + "<br/>";

            if ($("#zipCode1").val().length != 0 || $("#city1").val().length != 0) mailHtml += $("#zipCode1").val() + " " + $("#city1").val() + "<br/>";

            if ($("#phoneNumber1").val().length != 0) mailHtml += $("#phoneNumber1").val() + "<br/>";

            if ($("#mail1").val().length != 0) mailHtml += $("#mail1").val() + "<br/>";

            if ($("#chkAccompagnement:checked").length != 0) {
                mailHtml += '<br/>' + $("#civility2").val() + ' ' + $("#firstName2").val() + " " + $("#lastName2").val() + "<br/>" + $("#job2").val() + ' dans la société ' + $("#socity2").val() + "<br/>";

                if ($("#address2").val().length != 0) mailHtml += $("#address2").val() + "<br/>";

                if ($("#zipCode2").val().length != 0 || $("#city2").val().length != 0) mailHtml += $("#zipCode2").val() + " " + $("#city2").val() + "<br/>";

                if ($("#phoneNumber2").val().length != 0) mailHtml += $("#phoneNumber2").val() + "<br/>";

                if ($("#mail2").val().length != 0) mailHtml += $("#mail2").val() + "<br/>";
            }

            if ($("#chkOffers:checked").length != 0) {
                mailHtml += "<br/>" + $("#civility1").val() + ' ' + $("#firstName1").val() + " " + $("#lastName1").val() + " accepte de recevoir les offres et informations du Groupe DEMOS";
            }


            if (!SubscriptionValidation()) {
                alert("Veuillez remplir tout les champs suivis de *");
                return;
            }


            var maildata = {
                email: {
                    From: "Information DEMOS<contact@demos.fr>",
                    To: To,
                    Subject: 'Demos - Inscription à ' + document.title,
                    Message: mailHtml
                }
            };

            SendMail(maildata);

            $(".jquery_container").hide();
            $(".jquery_container").html(defaultValue);
            $(".jquery_container").show();
        });

        $("#cancelSubscriptionForm").live('click', function () {
            $(".jquery_container").hide();
            $(".jquery_container").html(defaultValue);
            $(".jquery_container").show();
        });
    }

    function SubscriptionValidation() {
        var isValid = true;

        $(".send-dialog .jquery_needed").each(function () {

            var that = $(this);

            that.next("span.jquery_emptymandatoryfield").remove();

            if (that.val() == "") {
                isValid = false;

                $("<span>").addClass("jquery_emptymandatoryfield").html("*").css({ 'margin': '0px', 'width': 'auto', 'padding': '0px', 'color': 'red' }).insertAfter(that);

            }
            else if (that.is(".jquery_mailAddress")) {
                if (!ValidateEmail(that.val())) {
                    isValid = false;
                    $("<span>").addClass("jquery_emptymandatoryfield").html("*").css({ 'margin': '0px', 'width': 'auto', 'padding': '0px', 'color': 'red' }).insertAfter(that);                    
                }
            }

        });

        $(".jquery_subscription1 .jquery_needed").each(function () {
            if ($(this).val() == "") {
                isValid = false;
                $("label[for='" + $(this).attr("id") + "']").css("color", "red");
            }
            else $("label[for='" + $(this).attr("id") + "']").css("color", "");

        });

        if ($("#chkAccompagnement:checked").length != 0) {
            $(".jquery_subscription2 .jquery_needed").each(function () {
                if ($(this).val() == "") {
                    isValid = false;
                    $("label[for='" + $(this).attr("id") + "']").css("color", "red");
                }
                else $("label[for='" + $(this).attr("id") + "']").css("color", "");
            });
        }

        return isValid;
    }
    /* Envoi d'email */

    /* Programme parcours pro */
    if ($(".product-program").length) {
        /* Hide all children */
        $("[ChildIndex]").hide();

        $('.collapse-program').live('click', function () {
            var currentIndex = $(this).attr('Index');

            if ($("[ChildIndex='" + currentIndex + "']:visible").length == 0) {
                $(this).text(CollapseText);
                $("[ChildIndex='" + currentIndex + "']").show();
            }
            else {
                $(this).text(ExpandText);
                $("[ChildIndex='" + currentIndex + "']").hide();
            }
        });
    }
    /* Programme parcours pro */


    /* Elearning */
    $("#produit #col-left .cadre-bottom .block-elearning-module .close").bind('click', function () {
        var _context = $(this).parent();
        var _callback = function () {
            if ($(this).is(":visible")) {
                $(".close", _context).text(closeText);
                _context.removeClass('module-collapsed').addClass('module-expended');
            }
            else {
                $(".close", _context).text(moreText);
                _context.addClass('module-collapsed').removeClass('module-expended');
            }
        };
        $('.long-description', _context).slideToggle(_callback);
    });

    if ($(".jquery_elearningprice").length) {
        $(".jquery_elearningprice").change(UpdatePackagePrice).change();
    }
    /* Elearning */

    /* Tooltip */

    // Ce selecteur match tout les elements de notre page qui ont un alt ou un title.
    // la partie [] permet de dire prendre tout les element du dom qui ont cet attribut, la virgule
    // permet d'indiquer un autre selecteur , séparer plusieurs selecteurs par une virgule nous
    // renvoie la somme des resultats des 2 selecteurs.            
    ToolTipCandidates = $('.product-attributes img, .product-attributes span[title]');
    UniqueNumber = 0;

    ToolTipCandidates.each(function (index, element) {
        var ToolTipAltText = "";
        var ToolTipTitleText = "";
        if (element.alt) {
            ToolTipAltText = element.alt;
            element.alt = "";
        }
        if (element.title) {
            ToolTipAltText = element.title;
            element.title = "";
        }

        // Crée un div
        $('<div id="ToolTip' + UniqueNumber + '"></div>')
        //  Insere le div apres l'élement courrant
                    .appendTo('body')
        //  Rajoute un label incluant le text du tooltip a se div
                    .append('<label>' + ToolTipAltText + '</label>')
        //  Le positionement absolue nous sert a positioner le div relativement a la souris
                    .addClass('ToolTip')
        //  Ce div resteras caché jusqu'a ce qu'on passe sur son element.
                    .hide()

        $(element).attr('ToolTipId', UniqueNumber);
        UniqueNumber++;

        $(element).parent().attr("title", "");
    });

    ToolTipCandidates.hover(
            function (e) {
                // Recupere le ToolTip associé a l'element
                var ToolTipId = $(e.target).attr('ToolTipId');
                // Permet de s'assurer que l'annimation est terminée avant dans lancer une autre
                // afin d'éviter une "boucle infinie"
                $('#ToolTip' + ToolTipId).stop(true, true);
                // Affiche progressivement le ToolTip
                $('#ToolTip' + ToolTipId).fadeIn('medium');
            },
            function (e) {
                // Recupere le ToolTip associé a l'element
                var ToolTipId = $(e.target).attr('ToolTipId');
                // Permet de s'assurer que l'annimation est terminée avant dans lancer une autre
                // afin d'éviter une "boucle infinie"
                $('#ToolTip' + ToolTipId).stop(true, true);
                // Cache progressivement le ToolTip
                $('#ToolTip' + ToolTipId).fadeOut();
            });

    ToolTipCandidates.mousemove(function (e) {
        // Recupere le ToolTip associé a l'element
        var ToolTipId = $(e.target).attr('ToolTipId');
        // jQuery ce charge pour nous de recuperer la position de la souris.
        // Nous avons uniquement a ajouter un top et un left coherent a notre element en fonction
        // de la position qui nous est indiquée.
        $('#ToolTip' + ToolTipId).css('top', e.pageY + "px").css('left', (e.pageX + 12) + "px");
    });


    /* Tooltip */

    /** Fiche produit **/

    /** News **/

    /* news Listing */
    if ($("#categoryList").length || $(".jquery_categorylink").length) {
        news = $(".jQuery-load > div").clone();

        $(".wf-next").live('click', function () {
            setPage(1);
        });
        $(".wf-prev").live('click', function () {
            setPage(-1);
        });
    }

    if ($("#categoryList").length) {
        $("#categoryList").change(function () {
            selectCategory($(this).val());
        });

        $("#categoryList").change();
    }

    if ($(".jquery_categorylink").length) {
        selectCategory(decodeURI(location.hash.substring(1)));

        $(".jquery_categorylink").live('click', function () {
            selectCategory(decodeURI($(this)[0].href.split("#")[1]));
        });
    }
    /* news Listing */

    /* Map */
    if ($(".jquery_map").length) {
        latlng = new google.maps.LatLng(0, 0);
        infowindow = new google.maps.InfoWindow();

        myOptions = {
            zoom: 14,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map($(".jquery_map")[0], myOptions);

        geocoder = new google.maps.Geocoder();

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
            }
            else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    /* Map */
    /** News **/



});
