﻿/// <reference path="~/js/jquery-1.4.1.js"/>

/******************************* Carrousel d'actualités ******************************************/
function actuCarousel_init(carousel) {
    var controls = $(carousel.container).find('.carrouselControls');
    var items = carousel.list.find('> li');
    var itemCount = items.size();
    $(items).css('visibility', 'visible');
    items.each(function (index, element) {
        controls.append(
            $('<div></div>')
                .addClass('gotoActu')
                .addClass('btn')
                .attr('href', '#')
                .bind('click', function () {
                    // carousel.scroll(index + 1);
                    var turn = Math.floor((carousel.first - 1) / itemCount);
                    carousel.scroll(turn * itemCount + index + 1);
                    return false;
                })
                .manageHover()
        );
    });

    carousel.clip.hover(function () {
        carousel.stopAuto();
    }, function () {
        carousel.startAuto();
    });
}

function actuCarousel_itemDidBecomeVisible(carousel, htmlElement, index, action) {
    carousel.container.find('.carrouselControls .gotoActu').each(function (eachIndex, eachElement) {
        var active = carousel.index(index) == (eachIndex + 1);

        if (active && !$(eachElement).hasClass('btnActive')) {
            $(eachElement).addClass('btnActive');
        } else if (!active && $(eachElement).hasClass('btnActive')) {
            $(eachElement).removeClass('btnActive');
        }
    });
}

$(document).ready(function () {
    $('.carrouselActu').each(function (index, element) {
        $(element).jcarousel({
            vertical: false,
            scroll: 1,
            animation: 1000, // durée en milli
            easing: 'swing',
            auto: 5, // nb elts
            wrap: 'circular',
            initCallback: actuCarousel_init,
            buttonNextHTML: null,
            buttonPrevHTML: null,
            itemVisibleInCallback: {
                onAfterAnimation: actuCarousel_itemDidBecomeVisible
            }
        });
    });
    setTimeout("resizeActuText()", 2000);
});

function resizeActuText() {

    $('.data h2').each(function () {
        if ($(this).innerHeight() > 47) {
            var _text = $(this).find('a:first').text();
            while ($(this).innerHeight() > 47 && _text.length > 0 && _text.indexOf(' ') != -1) {
                _text = _text.substr(0, _text.lastIndexOf(' '));
                $(this).find('a:first').text(_text);
            }

            _text = _text.substr(0, _text.length - 3);
            if (_text.indexOf(' ') != -1) {
                _text = _text.substr(0, _text.lastIndexOf(' '));
            }

            $(this).find('a:first').text(_text + '...');
        }
    });

    $('.data h3').each(function () {

        if ($(this).innerHeight() > 34) {
            var _text = $(this).find('a:first').text();
            while ($(this).innerHeight() > 34 && _text.length > 0 && _text.indexOf(' ') != -1) {
                _text = _text.substr(0, _text.lastIndexOf(' '));
                $(this).find('a:first').text(_text);
            }
            _text = _text.substr(0, _text.length - 3);
            if (_text.indexOf(' ') != -1) {
                _text = _text.substr(0, _text.lastIndexOf(' '));
            }
            $(this).find('a:first').text(_text + '...');
        }
    });
    setTimeout("resizeActuText()", 2000);

}

/******************************* Carrousels liés aux widgets ******************************************/
jQuery.fn.extend({
    wSlide: function (widgetSelector, itemsContainerSelector, itemsSelector, onSlide, onItemVisible, onItemHidden) {
        this.each(function () {
            // récupération des items
            var that = this;
            var itemsContainer = $(that).find(itemsContainerSelector);
            var items = $(itemsContainer).children(itemsSelector);
            if (items.length > 1) {
                // ajout des boutons de navigation
                var currentItem = 0;
                var itemSize = $(items[0]).outerWidth();
                $(itemsContainer).css('width', itemSize * items.length + 1 + 'px');

                $.each(items, function (i) {
                    if (i > 0) {
                        $(this).append("<div class='slide-left'></div>")
                        $(this).children(".slide-left:first").click(function () {
                            if (currentItem > 0) {
                                currentItem -= 1;
                                if (onSlide) {
                                    onSlide();
                                }
                                $(items[currentItem]).data("itemVisible", true);
                                $(items[currentItem + 1]).data("itemVisible", false);
                                $(itemsContainer).animate({ 'left': -(currentItem * itemSize) + 'px' }, function () {
                                    if (onItemVisible) {
                                        onItemVisible(items[currentItem]);
                                    }
                                    if (onItemHidden) {
                                        onItemHidden(items[currentItem + 1]);
                                    }
                                });
                            }
                        });
                    }
                    if (i < items.length - 1) {
                        $(this).append("<div class='slide-right'></div>");
                        $(this).children(".slide-right:first").click(function () {
                            if (currentItem < items.length - 1) {
                                currentItem += 1;
                                if (onSlide) {
                                    onSlide();
                                }
                                $(items[currentItem]).data("itemVisible", true);
                                $(items[currentItem - 1]).data("itemVisible", false);
                                $(itemsContainer).animate({ 'left': -(currentItem * itemSize) + 'px' }, function () {
                                    if (onItemVisible) {
                                        onItemVisible(items[currentItem]);
                                    }
                                    if (onItemHidden) {
                                        onItemHidden(items[currentItem - 1]);
                                    }
                                });
                            }
                        });
                    }
                });
            }
            $.each(items, function (i) {
                $(this).data("itemVisible", i == 0);
            });
            $(this).parents(widgetSelector).data("initComplete", true);
        });
        return this;
    },
    wcSlide: function (itemsContainerSelector, itemsSelector, onSlide, onItemVisible, defilement) {
        this.each(function () {
            // récupération des items
            var that = this;
            var itemsContainer = $(that).find(itemsContainerSelector);
            var items = $(itemsContainer).children(itemsSelector);
            var currentItem = 0;
            if (items.length > defilement) {
                // ajout des boutons de navigation
                var itemSize = $(items[0]).outerWidth(true);
                $(itemsContainer).css('width', itemSize * items.length + 1 + 'px');
                var curItem = 0;
                var sens = 1;
                if (items.length > defilement) {
                    var autoSlide = function () {
                        if (sens == 1) {
                            $(btnRight).click();
                        }
                        else {
                            $(btnLeft).click();
                        }
                    }

                    $(that).append("<div class='slide-left'></div>");
                    $(that).append("<div class='slide-right'></div>");
                    var btnLeft = $(that).children(".slide-left:first");
                    $(btnLeft).setDisabled(true, "disabled");
                    $(btnLeft).css({ opacity: 0.35 });
                    var btnRight = $(that).children(".slide-right:first");
                    $(btnRight).manageHover();
                    $(btnLeft).manageHover();
                    $(btnLeft).click(function () {
                        if (onSlide) {
                            onSlide();
                        }
                        if (currentItem - defilement > 0) {
                            currentItem -= defilement;
                        }
                        else {
                            if (sens == -1) {
                                sens = 1;
                            }
                            currentItem = 0;

                            $(this).animate({ opacity: 0.35 }, 300, function () {
                                $(this).setDisabled(true, "disabled");
                            });
                        }
                        $(itemsContainer).animate({ 'left': -(currentItem * itemSize) + 'px' }, 'slow', function () {
                            $(btnRight).animate({ opacity: 1 }, 300, function () {
                                $(this).setDisabled(false, "disabled"); ;
                            });
                            $.each(items, function (i) {
                                $(items[i]).data("itemVisible", (i >= currentItem && i < currentItem + defilement));
                            });
                            if (onItemVisible) {
                                for (var i = 0; i < defilement; i++) {
                                    onItemVisible(items[currentItem + i]);
                                }
                            }
                        });

                    });
                    $(btnRight).click(function () {
                        if (onSlide) {
                            onSlide();
                        }
                        if (currentItem + defilement < items.length - defilement) {
                            currentItem += defilement;
                        }
                        else {
                            if (sens == 1) {
                                sens = -1;
                            }
                            currentItem = items.length - defilement;
                            $(this).animate({ opacity: 0.35 }, 300, function () { $(this).setDisabled(true, "disabled"); });
                        }
                        $(itemsContainer).animate({ 'left': -(currentItem * itemSize) + 'px' }, 'slow', function () {
                            $(btnLeft).animate({ opacity: 1 }, 300, function () {
                                $(this).setDisabled(false, "disabled");
                            });
                            $.each(items, function (i) {
                                $(items[i]).data("itemVisible", (i >= currentItem && i < currentItem + defilement));
                            });
                            if (onItemVisible) {
                                for (var i = 0; i < defilement; i++) {
                                    onItemVisible(items[currentItem + i]);
                                }
                            }
                        });
                    });
                }
            }

            var nbItemInitialized = 0;
            $.each(items, function (i) {
                $(this).data("itemVisible", (i >= currentItem && i < currentItem + defilement));
                $(this).initComplete(function () {
                    nbItemInitialized++;
                });
            });

            var isInitComplete = function () {
                if (nbItemInitialized == items.length) {
                    $(that).data("initComplete", true);
                }
                else {
                    setTimeout(isInitComplete, 100);
                }
            }
            isInitComplete();
        });
        return this;
    },
    initScroll: function (containerSelector, itemSelector, separator) {
        this.each(function () {
            var item = $(this).find(itemSelector);
            var container = $(this).find(containerSelector);
            var containerWidth = $(container).innerWidth();
            $(container).css("width", "200000px");
            var itemWidth = $(item).width();
            if (itemWidth > $(this).innerWidth()) {
                // Ajout séparateur et 2ème item
                $(container).append('<div class="scrollSeparator">&nbsp;' + separator + '&nbsp;</div>');
                var separatorDiv = $(container).find(".scrollSeparator:first");
                var separatorWidth = $(separatorDiv).width();
                $(item).clone().appendTo(container);
                $(container).css('width', (2 * itemWidth + separatorWidth + 1) + 'px');
                var travel = itemWidth + separatorWidth;
                var defTiming = travel / 0.03;
                $(container).data("scrollParams", { "travel": travel, "defTiming": defTiming });
            }
            else {
                $(container).css("width", "");
            }
        });
        return this;
    },
    startScroll: function () {
        this.each(function () {
            var params = $(this).data("scrollParams");
            var t = this;
            if (params) {
                $(t).css('left', '0px');
                var scroll = function () {
                    $(t).animate({ 'left': '-=' + params.travel }, params.defTiming, "linear", function () {
                        $(t).css('left', '0px');
                        scroll();
                    });
                }
                scroll();
            }
        });
        return this;
    },
    updateDateHeure: function () {
        var t = this;
        var o = $(this[0])
        var date_du_jour, jour, mois, annee, heure, minute;
        date_du_jour = new Date();
        jour = To2DigitsString(date_du_jour.getDate());
        mois = To2DigitsString(date_du_jour.getMonth() + 1);
        annee = date_du_jour.getYear();
        if (annee < 2000) {
            annee += 1900;
        }
        heure = To2DigitsString(date_du_jour.getHours());
        minute = To2DigitsString(date_du_jour.getMinutes());
        o.text(" - " + jour + "/" + mois + "/" + annee.toString() + " - " + heure + "h" + minute);
        var updateFn = function () {
            $(t).updateDateHeure();
        }
        setTimeout(updateFn, 1000);
    },
    initComplete: function (callback) {
        this.each(function () {
            if (callback) {
                var t = this;
                var isInitComplete = function () {
                    if ($(t).data("initComplete")) {
                        callback();
                    }
                    else {
                        setTimeout(isInitComplete, 100);
                    }
                }
                isInitComplete();
            }
        });
        return this;
    }
});

/******************************* Widget itinéraire ******************************************/
var ViaMichelinControls = null;

function WaitLoadForIFrame() {
    try {
        document.getElementById('frameid').contentWindow.AfficherPage(ViaMichelinControls);
        $('#itineraireLoader').hide();
    }
    catch (err) {
        setTimeout('WaitLoadForIFrame()', 200);
    }
}

function LoadViaMichelinRequestIframe(controls) {
    $('#itineraireLoader').show();
    ViaMichelinControls = controls;
    if (document.getElementById('frameid') == null) {
        $('body').append("<iframe id=\"frameid\"  src=\"/Templates/Widgets/ViaMichelinRequest.aspx\" style=\"display:none;\"/>");
    }
    WaitLoadForIFrame();
}


function WaitSearchForIFrame(startCity, startZip, startAddress, destCity, destZip, stopAddress) {
    try {
        document.getElementById('frameid').contentWindow.searchStart(startCity, startZip, startAddress, destCity, destZip, stopAddress);
    }
    catch (err) {
        setTimeout(function () { WaitSearchForIFrame(startCity, startZip, startAddress, destCity, destZip, stopAddress) }, 200);
    }
}

function SearchFromViaMichelinRequestIframe(startCity, startZip, startAddress, destCity, destZip, stopAddress) {
    if (document.getElementById('frameid') == null) {
        $('body').append("<iframe id=\"frameid\"  src=\"/Templates/Widgets/ViaMichelinRequest.aspx\" style=\"display:none;\"/>");
    }
    WaitSearchForIFrame(startCity, startZip, startAddress, destCity, destZip, stopAddress);
}


/* opt : classe au format 
Controls : tableau de string --> id des controles (ordre : ville depart, ville arrivee, adresse depart, adresse arrivee);
Valeurs : tableau de string --> valeurs nominales (ordre : ville, adresse)
TextSelector : sélecteur du contrôle de texte à afficher si non valide*/
function AfficherPage(controls) {
    var vdepart;
    var varrivee;
    var adepart;
    var aarrivee;
    var valid;
    if (window != window.top) {
        var vdepart = $("#" + controls[0], parent.document).val();
        var varrivee = $("#" + controls[1], parent.document).val();
        var adepart = $("#" + controls[2], parent.document).val();
        var aarrivee = $("#" + controls[3], parent.document).val();
        var valid = vdepart != $("#" + controls[0], parent.document)[0].defaultValue && varrivee != $("#" + controls[1], parent.document)[0].defaultValue;
    }
    else {
        var vdepart = $("#" + controls[0]).val();
        var varrivee = $("#" + controls[1]).val();
        var adepart = $("#" + controls[2]).val();
        var aarrivee = $("#" + controls[3]).val();
        var valid = vdepart != $("#" + controls[0])[0].defaultValue && varrivee != $("#" + controls[1])[0].defaultValue;
    }

    if (!valid) {
        alert("Veuillez saisir une ville pour le départ et l'arrivée");
    }
    else {
        searchStart(vdepart, "", adepart, varrivee, "", aarrivee);
    }
}



/* Insérez ici votre clé */
try {
    VMAPI.registerKey("JSBS20091002133430216137419297");
    VMAPI.setLanguage("fra");
}
catch (err) {
    //API viaMichelin non chargée//
}

/* La fonction qui demandera au serveur le géocodage */

function searchStart(startCity, startZip, startAddress, destCity, destZip, stopAddress) {
    Start_geosearch = new VMGeoSearch();
    Start_myaddress = new VMAddress();
    Start_myaddress.zipCode = startZip;
    Start_myaddress.address = startAddress;
    Start_myaddress.city = startCity;
    Start_myaddress.countryVMCode = "1424";
    Start_geosearch.addEventHandler("onCallBack", function () {
        Stop_geosearch = new VMGeoSearch();
        Stop_myaddress = new VMAddress();
        Stop_myaddress.zipCode = destZip;
        Stop_myaddress.address = stopAddress;
        Stop_myaddress.city = destCity;
        Stop_myaddress.countryVMCode = "1424";
        Stop_geosearch.addEventHandler("onCallBack", function () {
            if (Start_geosearch.results.length == 1 && Stop_geosearch.results.length == 1) {
                startPointLat = Start_geosearch.results[0].coords.lat;
                startPointLon = Start_geosearch.results[0].coords.lon;

                stopPointLat = Stop_geosearch.results[0].coords.lat;
                stopPointLon = Stop_geosearch.results[0].coords.lon;
                if (window != window.top) {
                    window.parent.document.location.href = "/fr/preparation_au_voyage/itineraires/feuille_route/resultat?sp=" + startPointLat + "," + startPointLon + "&ep=" + stopPointLat + "," + stopPointLon + "&st=" + startCity + "&et=" + destCity;
                }
                else {
                    document.location.href = "/fr/preparation_au_voyage/itineraires/feuille_route/resultat?sp=" + startPointLat + "," + startPointLon + "&ep=" + stopPointLat + "," + stopPointLon + "&st=" + startCity + "&et=" + destCity;
                }
            }
            else {
                if (window != window.top) {
                    window.parent.document.location.href = "/fr/preparation_au_voyage/itineraires/feuille_route" + "?vdepart=" + startCity + "&varrivee=" + destCity + "&cpdepart=" + startZip + "&cparrivee=" + destZip;
                }
                else {
                    document.location.href = "/fr/preparation_au_voyage/itineraires/feuille_route" + "?vdepart=" + startCity + "&varrivee=" + destCity + "&cpdepart=" + startZip + "&cparrivee=" + destZip;
                }
            }
        });
        Stop_geosearch.search(Stop_myaddress);
    });
    Start_geosearch.search(Start_myaddress);
}

function ManageIti(selector) {
    var container = $(selector).find(".itemContainer:first");
    if (container.length > 0) {
        var maxHeight = $(container).innerHeight();
        var source = $(selector).find(".preselectionItems:first");
        var sourceList =  $(source).find("ul:first");
        if (sourceList.length > 0) {
            // parcours des items
            var items = $(sourceList).find("li");
            while (items.length > 0) {
                var itemCode = $("<div class='WidgetItem'></div>");
                var list = $("<ul></ul>");
                $(list).appendTo(itemCode);
                $(itemCode).appendTo(container);
                var sizeOk = true;
                while (sizeOk && items.length > 0) {
                    $(items[0]).appendTo(list);
                    sizeOk = $(list).outerHeight() <= maxHeight;
                    if (!sizeOk) {
                        if (items.length > 1) {
                            $(items[1]).before(items[0]);
                        }
                        else {
                            $(items[0]).appendTo(sourceList);
                        }

                    }
                    items = $(sourceList).find("li");
                }
            }
            $(source).remove();        
        }
    }
    $(selector).wSlide('.widgetContainer', '.itemContainer', '.WidgetItem');
}

/******************************* Widget prévisions trafic ******************************************/

function GetPrevisions(elementId, vue, dateModif) {
    var adr = "/Templates/WebServices/Prevision_trafic_ws.aspx";
    var dataGet = undefined;
    if (vue)
        dataGet = { "vue": vue, "modif": dateModif };
    // appel du webservice
    $.ajaxSetup({ cache: false });
    $.getJSON(adr, dataGet, function (data) {
        $.ajaxSetup({ cache: true });
        var itemContainer = $("<div class='itemContainer'></div>");
        $(itemContainer).appendTo("#" + elementId);
        //ajout des items
        $.each(data, function () {
            var item = this;
            var libelle = item.Heures.length > 1 ? "Pics de trafic à" : "Pic de trafic à";
            var itemCode = $("<div class='WidgetItem'><div class='PrevContent'><div class='titre'>" + item.Libelle + "<div class='date'>Demain le " + getShortDate() + "</div></div><div class='pic'><div class='labelPic'>" + libelle + "</div><div class='heures'></div></div></div></div>");
            $(itemCode).appendTo(itemContainer);

            $.each(item.Heures, function (i) {
                $(itemCode).find(".heures:first").append("<div class='previsionHeure'" + (i > 0 ? " style='display:none'" : "") + ">" + this + "h00</div>");
            });
            // fadein fadeout des heures
            if (item.Heures.length > 1) {
                var displayed = 0;
                var change = function () {
                    var heure = $(itemCode).find(".previsionHeure")[displayed];
                    $(heure).fadeOut('slow', function () {
                        if (displayed < item.Heures.length - 1) {
                            displayed++;
                        }
                        else {
                            displayed = 0;
                        }
                        heure = $(itemCode).find(".previsionHeure")[displayed];
                        $(heure).fadeIn('slow');
                        setTimeout(change, 3000);
                    });
                };
                change();

            }
        });
        // init carrousel
        $("#" + elementId).parent().children(".loader").remove();
        $("#" + elementId).css("display", "block");
        $("#" + elementId).wSlide(".widgetContainer", ".itemContainer", ".WidgetItem");
    });
}

/******************************* Widget Tarifs ******************************************/

var wsTarifs = "/Templates/WebServices/Tarifs_ws.aspx"
var Reseau;

function selectReseau() {

    var reseau = $("input[name='reseau']:checked").val();

    if (reseau == Reseau)
        return;
    else
        Reseau = reseau;

    // raz de tous les combo
    $("#geSelect").html("<option value='0' selected='selected'>Gare d'entrée</option>");
    $("#gsSelect").html("<option value='0' selected='selected'>Gare de sortie</option>");
    $("#cvSelect").html("<option value='0' selected='selected'>Classe de véhicule</option>");
    // désactivation des contrôles

    $("#blStart, #blEnd, #blClass, #blBtn").setBlockDisabled(true);

    // récup des gares d'entree
    if (Reseau == "APRR") {
        var getdata = { "action": "ge" };
        $.getJSON(wsTarifs, getdata, function (data) {
            $.each(data, function () {
                $("#geSelect").append("<option value='" + this.CodeSociete + "." + this.CodeGare + "'>" + this.Libelle + "</option>");
            });
            $("#blStart").setBlockDisabled(false);
        });
    }
    else if (Reseau == "AREA") {
        $.ajax({
            url: wsTarifs,
            data: { "output": "area" },
            success: function (data) {
                $("#geSelect").html("");
                $(data).find("#gare-entree").children('option').appendTo("#geSelect");
                $("#geSelect").val("0");
                $("#blStart").setBlockDisabled(false);
            }
        });
    }
    else {
        $("#blStart").setBlockDisabled(true);
    }
}

function Valider(reseau) {
    var ge, gs, cv;
    ge = $("#geSelect").val();
    gs = $('#gsSelect').val();
    cv = $('#cvSelect').val();
    $(location).attr('href', "/fr/preparation_au_voyage/itineraires/tarifs?reseau=" + Reseau + "&ge=" + ge + "&gs=" + gs + "&classe=" + cv);
}
function GetGaresSortie() {

    $("#gsSelect").html("<option value='-1' selected='selected'>Gare de sortie</option>");
    $("#cvSelect").html("<option value='-1' selected='selected'>Classe de véhicule</option>");
    $("#blEnd, #blClass, #blBtn").setBlockDisabled(true);

    var value = $("#geSelect").val();
    if (value) {
        if (value != "0") {
            if (Reseau == "APRR") {
                var getdata = { "action": "gs", "ge": value };
                $.getJSON(wsTarifs, getdata, function (data) {
                    $.each(data, function () {
                        $("#gsSelect").append("<option value='" + this.CodeSociete + "." + this.CodeGare + "'>" + this.Libelle + "</option>");
                    });
                    $("#blEnd").setBlockDisabled(false);
                });
            }
            else if (Reseau == "AREA") {
                $.ajax({
                    url: wsTarifs,
                    data: { "output": "area", "ge": value },
                    success: function (data) {
                        $("#gsSelect").html("");
                        $(data).find("#gare-sortie").children('option').appendTo("#gsSelect");
                        $("#gsSelect").val("0");
                        $("#blEnd").setBlockDisabled(false);
                    }
                });
            }
        }
    }
}
function GetClasses() {
    $("#cvSelect").html("<option value='0' selected='selected'>Classe de véhicule</option>");
    $("#blClass, #blBtn").setBlockDisabled(true);
    var ge = $("#geSelect").val();
    var gs = $("#gsSelect").val();
    if (ge && gs) {
        if (ge != "0" && gs != "0") {
            if (Reseau == "APRR") {
                var getdata = { "action": "classes", "ge": ge, "gs": gs };
                $.getJSON(wsTarifs, getdata, function (data) {
                    $.each(data.PrixClasses, function () {
                        $("#cvSelect").append("<option value='" + this.Classe + "'>" + this.Classe + "</option>");
                    });
                    $("#blClass").setBlockDisabled(false);
                });
            }
            else if (Reseau == "AREA") {
                // Ajout des classes de vehicule
                $("#cvSelect").append("<option value='1'>1</option>");
                $("#cvSelect").append("<option value='2'>2</option>");
                $("#cvSelect").append("<option value='3'>3</option>");
                $("#cvSelect").append("<option value='4'>4</option>");
                $("#cvSelect").append("<option value='5'>5</option>");
                $("#blClass").setBlockDisabled(false);
            }
        }
    }
}
function ChangeClasse(reseau) {
    $("#blBtn").setBlockDisabled(true);
    var ge = $("#geSelect").val();
    var gs = $("#gsSelect").val();
    var classe = $("#cvSelect").val();
    if (ge && gs && classe) {
        if (ge != "0" && gs != "0" && classe != "0") {
            $("#blBtn").setBlockDisabled(false);
        }
    }
}

/******************************* Widget conditions de circulation ******************************************/

function GetAlertes(elementId, zone) {
    var adr = "/Templates/WebServices/Conditions_circu_ws.aspx";
    var dataGet = undefined;
    if (zone)
        dataGet = { "zone": zone };

    // appel du webservice
    $.ajaxSetup({ cache: false });
    $.getJSON(adr, dataGet, function (data) {
        $.ajaxSetup({ cache: true });
        // ajout de la description
        if (data.Titre && data.Titre != "") {
            $("#" + elementId).append("<div class='descView'><div class='descZone'><div class='descContainer'><div class='desc'>" + data.Titre + "</div></div></div></div>");
        }
        $("#" + elementId).append("<div class='widgetSlider'><div class='deg'>&nbsp;</div></div>");
        var slider = $("#" + elementId).children(".widgetSlider:first");
        $(slider).append("<div class='itemContainer'></div>");
        var itemContainer = $(slider).children(".itemContainer:first");
        //ajout des items
        $.each(data.Alertes, function () {
            var item = this;

            //Date et heure
            var titre = GetFormatedDate(item.Date) + " " + item.Titre + " : ";

            var picto = "";
            if (item.Type == "aucun") {
                item.Type = "information";
                titre = "";
            }
            picto = "<div class='zonePicto'><img src='/img/skin/circulation/i-" + item.Type + ".gif' alt='" + item.Type + "' /></div>";
            $(itemContainer).append("<div class='WidgetItem'>" + picto + "<p>" + titre + item.Description + "</p>");

        });
        // init carrousel
        $("#" + elementId).parent().children(".loader").remove();
        $("#" + elementId).css("display", "block");
        $(slider).wSlide(".widgetContainer", ".itemContainer", ".WidgetItem");
    });
}



/******************************* Widget météo ******************************************/

function GetMeteo(elementId, localites) {
    var adr = "/Templates/WebServices/MsnMeteo_ws.aspx";
    var dataGet = undefined;
    if (localites)
        dataGet = { "localites": localites };
    // appel du webservice
    $.ajax({
        url: adr,
        cache: false,
        data: dataGet,
        dataType: "html",
        success: function (data) {
            // Création de la structure du carrousel
            $("#" + elementId).append("<div class='widgetSlider'></div>");
            var slider = $("#" + elementId).children(".widgetSlider:first");
            $(slider).append("<div class='itemContainer'></div>");
            var itemContainer = $(slider).children(".itemContainer:first");
            //ajout des items
            $(data).find(".meteo-bg").each(function () {
                $(itemContainer).append("<div class='WidgetItem'></div>");
                var item = $(itemContainer).children(".WidgetItem:last");
                $(this).appendTo(item);
            });
            // init carrousel
            $("#" + elementId).parent().children(".loader").remove();
            $("#" + elementId).css("display", "block");
            $(slider).wSlide(".widgetContainer", ".itemContainer", ".WidgetItem");
        }
    });
}

/******************************* Widget temps de parcours ******************************************/

function GetTemps(elementId, zoneData) {
    var adr = "/Templates/WebServices/Temps_parcours_ws.aspx";
    var dataGet = undefined;
    if (zoneData.code)
        dataGet = { "zone": zoneData.code };
    // ajout de la description
    if (zoneData.description != "") {
        $("#" + elementId).append("<div class='descView'><div class='descZone'><div class='descContainer'><div class='desc'>" + zoneData.description + "</div></div></div></div>");
    }
    // appel du webservice
    $.ajaxSetup({ cache: false });
    $.getJSON(adr, dataGet, function (data) {
        $.ajaxSetup({ cache: true });

        // Création de la structure du carrousel
        $("#" + elementId).append("<div class='widgetSlider" + (zoneData.description != "" ? "" : " noDesc") + "'></div>");
        var slider = $("#" + elementId).children(".widgetSlider:first");
        $(slider).append("<div class='itemContainer'></div>");
        var itemContainer = $(slider).children(".itemContainer:first");

        //ajout des items
        $.each(data, function () {
            var ratio = 0;
            if (this.Temps > 0) {
                ratio = this.Diff / this.Temps;
            }
            var itemClass = "normal";
            if (ratio < 0.2 && ratio > 0) {
                itemClass = "medium"
            }
            else if (ratio >= 0.2) {
                itemClass = "high";
            }
            var tpsDiffDiv = (this.Diff == 0 ? "" : "<div class='tpsDiff'>(+" + this.Diff + "mn)</div>");
            var temps = this.Temps + this.Diff;
            var h = Math.floor(temps / 60);
            var min = temps - h * 60;

            $(itemContainer).append("<div class='WidgetItem " + itemClass + "'><div class='tpsContent'>" + this.Depart + " - " + this.Arrivee + "<div class='tpsDuree'>" + h + "h" + To2DigitsString(min) + tpsDiffDiv + "</div></div><div class='deg'>&nbsp;</div></div>");
        });
        // init carrousel
        $("#" + elementId).parent().children(".loader").remove();
        $("#" + elementId).css("display", "block");
        $(slider).wSlide(".widgetContainer", ".itemContainer", ".WidgetItem");
    });
}

/******************************* Widget webcam ******************************************/

var listeners = new Array();

function addListener(parentId, url, image, num) {
    listeners.push(new Listener('WebCamPlayer_' + num, url, image));
    $(document).ready(function () {
        $('#' + parentId).find('.WidgetItem.Webcam_' + num).data('listener', listeners[num]);
    });
}

function Listener(elementId, url, image) {
    this.elementId = elementId;
    this.position = 0;
    this.image = image;
    this.url = url;
}
/**
* Initialisation
*/
Listener.prototype.onInit = function () {
    this.loadImage();
};
/**
* onClick event on the video
*/
Listener.prototype.onClick = function () {
    this.play();
};
/**
* onKeyUp event on the video
*/
Listener.prototype.onKeyUp = function (pKey) {
};
/**
* onComplete event
*/
Listener.prototype.onFinished = function () {
    this.loop();
};
/**
* Update
*/
Listener.prototype.onUpdate = function () {
    if (this.isPlaying == "true" && parseInt(this.position) > 0) {
        this.unloadImage();
    }
};
Listener.prototype.play = function () {
    var url = this.url;
    if (this.position == 0) {
        $("#" + this.elementId).each(function () { this.SetVariable("method:setUrl", url); });
    }
    $("#" + this.elementId).each(function () { this.SetVariable("method:play", ""); });
};
Listener.prototype.stop = function () {
    if (this.isPlaying == "true") {
        $("#" + this.elementId).each(function () { this.SetVariable("method:stop", ""); });
        this.loadImage();
    }
};
Listener.prototype.loop = function () {
    this.setPosition(0);
    this.play();
};
Listener.prototype.setPosition = function (position) {
    this.position = position;
    $("#" + this.elementId).each(function () { this.SetVariable("method:setPosition", position.toString()); });
};
Listener.prototype.loadImage = function () {
    var image = this.image;
    $("#" + this.elementId).each(function () { this.SetVariable("method:loadMovieOnTop", image + "|" + 1 + "|" + 0 + "|" + 0); });
};
Listener.prototype.unloadImage = function () {
    $("#" + this.elementId).each(function () { this.SetVariable("method:unloadMovieOnTop", 1); });
};


/******************************* Fonctions transverses ******************************************/

function GetFormatedDate(value) {
    var today = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
    var day = today.getDate();
    var month = today.getMonth() + 1;
    var year = today.getFullYear();
    var hours = today.getHours();
    var minutes = today.getMinutes();

    return To2DigitsString(day)
        + "/" + To2DigitsString(month)
        + "/" + year + " - " + hours
        + "h"
        + To2DigitsString(minutes);
}

function getShortDate() {
    var tomorrow = new Date();
    tomorrow.setTime(tomorrow.getTime() + (1000 * 3600 * 24));
    var day = tomorrow.getDate();
    var month = tomorrow.getMonth() + 1;
    var year = tomorrow.getFullYear();
    return To2DigitsString(day)
        + "/" + To2DigitsString(month)
        + "/" + year;
}

function To2DigitsString(num) {
    if (num) {
        if (num < 10) {
            return "0" + num;
        }
        return num;
    }
    return "00";
}

