var updateBasketOnEachAction = false;
var couldSendData = false;

$(function() {
    $('#bodywf .custom-font, #bodywf .panier h3,#bodywf #container.ms-WPTitle, #bodywf .custom-font-selus, #bodywf #produit h4.custom-font-selus, #bodywf #wf-contactus-minimal a, #bodywf #header #recherche-top td.ms-sbtext span, #bodywf .product-subscription a, #bodywf .helvetica, #bodywf a.btn-red, #bodywf .wp-webfactory-createuser .wp-webfactory-createuser-btnsubmit, #bodywf .wp-webfactory-createuser .wp-webfactory-createuser-btnmodify, #bodywf a.wf-trans').show();
    if (product.sessions.length == 0) {
        $('a#popin').parent().hide();
        return;
    }
    for (var a = 0; a < product.sessions.length; a++) {
        if (product.sessions[a].length == 0) {
            $('a#popin').parent().hide();
            return;
        }
    }
    $('a#popin').colorbox({
        close: '',
        maxWidth: 750,
        overlayClose: false,
        transition: 'elastic',
        inline: true,
        scrolling: false,
        href: '#contentPopIn #panier'
    });

    $('div.learning').remove();
    $('div.pro').remove();

    $('#title').text(product.title);
    if (product.modalities != '') {
        $('#code').html(product.typeProduitNom + ' / ' + product.modalities + ' / CODE : ' + product.code);
    } else {
        $('#code').html(product.typeProduitNom + ' / CODE : ' + product.code);
    }

    var strJ, strH;
    if (product.duration > 1) {
        strJ = strJoursFormat;
    } else {
        strJ = strJourFormat;
    }
    if (product.durationInHours > 1) {
        strH = strHoursFormat;
    } else {
        strH = strHourFormat;
    }
    $('#code').next().html(strJ.format(product.duration) + ' (' + strH.format(product.durationInHours) + ')');

    actionButtons = $('div.actionButtons');
    actionButtonsDefault = $($(actionButtons).html());
    actionButtonsEdit = $($('#templateActionButtonsEdit').html());

    actionButtonsEdit.insertSession = function(event) {
        event.preventDefault();
        insertSession($('.ajouter-date.modifier-participant:visible'));
    }

    actionButtonsEdit.cancelInsertSession = function(event) {
        event.preventDefault();
        cancelEditParticipant($('.ajouter-date.modifier-participant:visible'));
    }

    actionButtonsEdit.insertParticipant = function(event) {
        event.preventDefault();
        updateParticipant($('.modifier-participant:visible').prev());
    }

    actionButtonsEdit.cancelInsertParticipant = function(event) {
        event.preventDefault();
        cancelEditParticipant($('.modifier-participant:visible').prev());
    }

    refreshNbPersonAndPrice();
    initTemplate();
    initStageTemplate();
    createNewSession();
    if (typeof (DoCufon) != 'undefined') { DoCufon(); }
});

function hideAddNewSession() {
    for (var w = 0; w < product.sessions.length; w++) {
        if (product.sessions[w].users == null || product.sessions[w].users.length == 0) {
            return;
        }
    }
    $('div.bottom', panier).hide();    
}


function addAndContinue() {
    if (!couldSendData) {
        alert(strAlertElearning1);
        return;
    }
    var parameters = {"productId":product.id, "data":product.sessions};
    $.ajax({
        type: "POST",
        url: WS + "/AddToBasketStage",
        data: JSON.stringify(parameters),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            location = variation + "/pages/training-search.aspx";
        },
        error: function(e) {
            alert("An error occured.");
        }
    });
}
function addAndGoBasket() {
    if (!couldSendData) {
        alert(strAlertElearning1);
        return;
    }
    var parameters = {"productId":product.id, "data":product.sessions};
    $.ajax({
        type: "POST",
        url: WS + "/AddToBasketStage",
        data: JSON.stringify(parameters),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            window.location = strBasketUrl;
        },
        error: function(e) {
            alert("An error occured.");
        }
    });
}


function initStageTemplate() {
    $('#add-and-continue', actionButtonsDefault).text(strAddAndContinue);
    $('#add-and-go-basket', actionButtonsDefault).text(strAddAndgoBasket);

    $("a.cancel", actionButtonsEdit).text(strCancel);
    $("a.addParticipant", actionButtonsEdit).text(strAddThisParticipant);

    if (product.price != null) {
        $('div.ajouter-date > div > span:first').html(product.price.priceValue + ' ' + product.price.symbol);
    }
    initOptions($('#templateCreateSession .options > ul', templates));
    initOptions($('#templateParticipant .options > ul', templates));
    initPrecisions($('#templateCreateSession div.options > ul ~ ul', templates));
    initPrecisions($('#templateParticipant div.options > ul ~ ul', templates));
}

function createNewSession() {
    var newSession = $('#templateCreateSession', templates).children().clone(true);
    $(newSession).insertBefore(actionButtons);
    refreshDdlVilles($('#ville', newSession));
    if (product.type.toUpperCase() == 'CYCLELONG') {
        $('#ville', newSession).change(function() {
            refreshDdlSessionsForCycle(this);
        });
    } else {
        $('#ville', newSession).change(function() {
            refreshDdlSessionsForStage(this);
        });
    }

    $('#ville', newSession).change();

    $('.ajouter', panier).hide();
    $('.modifier', panier).hide();
    $('.supprimer', panier).hide();
    $('a.ajouter', panier).show();
    $('a.ajouter-date', panier).hide();

    actionButtons.html(actionButtonsEdit);
    if (price === 0) {
        $("div.cancel", actionButtons).hide();
    }
    else {
        $("div.cancel", actionButtons).show();
    }

    $("a.addParticipant", actionButtons).click(actionButtonsEdit.insertSession);
    $("a.cancel", actionButtons).click(actionButtonsEdit.cancelInsertSession);

    $("a.addParticipant", actionButtons).text(strAddThisParticipant);

    if (typeof (DoCufon) != 'undefined') { DoCufon(); }

    $.fn.colorbox.resize();
}
function addNewSession(divBottom) {
    var newSession = $('#templateCreateSession', templates).children().clone(true);
    $(newSession).insertBefore($(divBottom));
    refreshDdlVilles($('#ville', newSession));
    if (product.type.toUpperCase() == 'CYCLELONG') {
        $('#ville', newSession).change(function() {
            refreshDdlSessionsForCycle(this);
        });
    } else {
        $('#ville', newSession).change(function() {
            refreshDdlSessionsForStage(this);
        });
    }
    $('#ville', newSession).change();
    $(divBottom).remove();
    $('.ajouter', panier).hide();
    $('.modifier', panier).hide();
    $('.supprimer', panier).hide();
    $('a.ajouter', panier).show();
    $('a.ajouter-date', panier).hide();
    $('.ajouter-date p strong', panier).show();
    /*if (refreshNbPersonAndPrice(divBottom) > 0) {
    $('<a class="annuler" href="" onclick="javascript:cancelAddSession(this);return false;">' + strCancel + '</a>').insertAfter($(newSession).find('a.validation').first());
    }*/

    actionButtons.html(actionButtonsEdit);
    if (price === 0) {
        $("div.cancel", actionButtons).hide();
    }
    else {
        $("div.cancel", actionButtons).show();
    }

    $("a.addParticipant", actionButtons).click(actionButtonsEdit.insertSession);
    $("a.cancel", actionButtons).click(actionButtonsEdit.cancelInsertSession);

    $("a.addParticipant", actionButtons).text(strAddThisParticipant);

    if (typeof (DoCufon) != 'undefined') { DoCufon(); }

    $.fn.colorbox.resize();
}
function cancelAddSession(a) {
    $(a).parents('div.ajouter-date').next().remove();
    $(a).parents('div.ajouter-date').remove();
    $('.ajouter', panier).show();
    $('.modifier', panier).show();
    $('.supprimer', panier).show();

    if (typeof (DoCufon) != 'undefined') { DoCufon(); }

    $.fn.colorbox.resize();
}
function createNewParticipant(div) {
    var newParticipant = $('#templateParticipant', templates).children().clone(true);
    var id = $(div).find('.participant').length;
    $(div).append($(newParticipant));
    return $(newParticipant);
}
function addNewParticipant(divLink) {
    var newParticipant = createNewParticipant($(divLink).parents('.session'));

    var sessionId = $(divLink).parents('.session').attr("sessionid");

    $(divLink).parent().remove();
    editParticipant(newParticipant);
    $(newParticipant).last().hide();

    actionButtons.html(actionButtonsEdit);
    if (price === 0) {
        $("div.cancel", actionButtons).hide();
    }
    else {
        $("div.cancel", actionButtons).show();
    }

    $("a.addParticipant", actionButtons).click(actionButtonsEdit.insertParticipant);
    $("a.cancel", actionButtons).click(actionButtonsEdit.cancelInsertParticipant);

    $("a.addParticipant", actionButtons).text(strAddThisParticipant);

    hideButtons();

    if (typeof (DoCufon) != 'undefined') { DoCufon(); }

    $.fn.colorbox.resize();
}

function refreshNbPersonAndPrice(a) {
    price = 0;
    var nb = 0;
    if (product != null && product.sessions != null && product.sessions.length > 0) {
        for (var i = 0; i < product.sessions.length; i++) {
            if (product.sessions[i].users != null && product.sessions[i].users.length > 0) {
                nb += product.sessions[i].users.length;

                for (var j = 0; j < product.sessions[i].users.length; j++) {
                    price += product.price.priceValue;
                    for (var k = 0; k < product.sessions[i].users[j].options.length; k++) {
                        for (var l = 0; l < product.options.length; l++) {
                            if (product.sessions[i].users[j].options[k] == product.options[l].id) {
                                price += (product.options[l].price * product.options[l].qty);
                            }
                        }
                    }
                }
            }
        }
    }
    if (nb == 0) {
        $('#panier-participants').text(strNoPerson);
        couldSendData = false;
    } else if (nb == 1) {
        $('#panier-participants').text(strSignglePerson);
        couldSendData = true;
    } else {
        $('#panier-participants').text(strMultiPerson.format(nb));
        couldSendData = true;
    }

    var txtPrice = "";
    if (typeof price == "number" && price !== 0) {
        txtPrice = price.toBasketPrice();
    }

    txtPrice += '<a href="" onclick="javascript:$.colorbox.close();return false;"><img src="/Style Library/WebFactory/images/btn-delete.gif" alt="supprimer" /></a>';

    $('#prix').html(txtPrice);
    if (typeof (DoCufon) != 'undefined') { DoCufon(); }
    return price;
}
function insertSession(div) {
    if (!participantIsValid($(div).find('#participantEdit'))) {
        return;
    }
    $(div).hide();
    var session = $(div).next();
    $(session).show();

    var currentSession = null;
    for (var a = 0; a < product.sessions.length; a++) {
        if (product.sessions[a].id == $(div).find('select#date').val()) {
            currentSession = product.sessions[a];
            break;
        }
    }
    $(session).attr('sessionId', currentSession.id);

    var prix = $(session).find('span:first');
    $(prix).html(product.price.priceValue + ' ' + product.price.symbol);
    $(prix).next().next().html(currentSession.place);
    $(prix).next().next().next().next().html(sessionDateTextFormat.format(currentSession.beginDate, currentSession.endDate));

    var newParticipant = createNewParticipant(session);
    var civil = $('#participantEdit select[name="civil"]', div);
    var ctrlPrenom = $('#participantEdit input[name="prenom"]', div);
    var ctrlNom = $('#participantEdit input[name="nom"]', div);
    var ctrlMail = $('#participantEdit input[name="mail"]', div);
    var ctrlFonction = $('#participantEdit input[name="fonction"]', div);


    if (product.type.toUpperCase() == "CYCLELONG") {
        $(session).find('.details-session').show();
        var ulInnerHTML = '';
        for (var s = 0; s < currentSession.detailSessions.length; s++) {
            ulInnerHTML += '<li>{0}</li>'.format(sessionDateTextFormat.format(currentSession.detailSessions[s].beginDate, currentSession.detailSessions[s].endDate));
        }
        $(session).find('.details-session').html(ulInnerHTML);
    }

    var data =
    {
        'id': 0,
        'civiliteId': $(civil).val(),
        'firstName': $(ctrlPrenom).val(),
        'lastName': $(ctrlNom).val(),
        'mail': $(ctrlMail).val(),
        'function': $(ctrlFonction).val(),
        'options': [],
        'precisions': []
    };
    $(div).find('.options > ul li input').each(function(index) {
        for (var a = 0; a < product.options.length; a++) {
            if (product.options[a].id == $(this).attr('value')) {
                if ($(this).attr('checked')) {
                    data.options.push(product.options[a].id);
                    $(newParticipant).find('.options > ul li input[value=' + $(this).attr('value') + ']').attr('checked');
                }
                break;
            }
        }
    });
    $(div).find('.options > ul ~ ul li input').each(function(index) {
        for (var a = 0; a < product.precisions.length; a++) {
            if (product.precisions[a].id == $(this).attr('value')) {
                if ($(this).attr('checked')) {
                    data.precisions.push(product.precisions[a].id);
                }
                break;
            }
        }
    });

    $(newParticipant).attr('participantId', 0);
    currentSession.users = [];
    currentSession.users.push(data);
    bindDataToParticipant(newParticipant, data);
    $(div).remove();
    refreshNbPersonAndPrice();
    $('.ajouter', panier).show();
    $('.modifier', panier).show();
    $('.supprimer', panier).show();
    $('#bottom', panier).show();
    
    addParticipantWidth();

    actionButtons.html(actionButtonsDefault);
    
    if (typeof (DoCufon) != 'undefined') { DoCufon(); }

    hideAddNewSession();
    
    $.fn.colorbox.resize();

//    for (var w = 0; w < product.sessions.length; w++) {
//        if (product.sessions[w].users == null || product.sessions[w].users.length == 0) {
//            return;
//        }
//    }
//    $('div.bottom', panier).hide();
//    $.fn.colorbox.resize();
}
function deleteSession(divTitre) {
    $(divTitre).parent().remove();

    getMySession(divTitre).users = [];
    refreshNbPersonAndPrice();

    var empty = true;
    for (var a = 0; a < product.sessions.length; a++) {
        if (product.sessions[a].users != null && product.sessions[a].users.length > 0) {
            empty = false;
            break;
        }
    }
    if (empty) {
        createNewSession();
        $('.bottom', panier).first().remove();
    }
    $('div.bottom', panier).show();
    $.fn.colorbox.resize();
}


function getCurrentSelectedSessions(a) {
    var r = [];
    for (var b = 0; b < product.sessions.length; b++) {
        if (product.sessions[b].users != null && product.sessions[b].users.length > 0) {
            r.push(product.sessions[b]);
        }
    }
    return r;
}
function getMySession(a) {
    if ($(a).parents('.session').length == 0) {
        return null;
    } else {
        for (var b = 0; b < product.sessions.length; b++) {
            if (product.sessions[b].id == $(a).parents('.session:first').attr('sessionId')) {
                return product.sessions[b];
            }
        }
    }
    return null;
}
function getCurrentSession(a) {
    var id = $(a).attr('sessionId');
    if (id == null) {
        id = $(a).parents('.session').attr('sessionId');
    }
    if (id == null) {
        return null;
    }
    return product.sessions[id];
}
