
/* - fafsea.js - */
id = 0;

function prefillMeetingTitle()
{
    if ($('#fafseameeting-base-edit #instance').length != 0) {
        var val = $('#fafseameeting-base-edit #instance').val();
        text = $('#fafseameeting-base-edit option[value='+val+']').text();
        $('#fafseameeting-base-edit #title')[0].value = text;
    }
}

/* Leftcolumn management */
$(document).ready(function(){
    regex = new RegExp("&","g");
    params = window.location.search.substring(1).split(regex);
    for (var i=0; i<params.length; i++) {
        var regInfo = new RegExp("=","g");
        var infos = params[i].split(regInfo);
        if (infos[0] == 'me')
        DivStatus( 'menu', infos[1] );
    }
});

function fill_attendees() {
    // Load potential attendees
    $('#attendees_options').html("");
    meeting_url = document.location.href.substring(0,document.location.href.length - 4)
    meeting_url += "meeting_ajax_potentialattendees"
    $.post(meeting_url, { instance: $('#instance').val() },
      function(data){
        var d = $(data);
        var e = d.children("option");
        $('#attendees_options').html( e );
        $('#attendees_clone').html( e.clone() );
        $('#attendees').children().remove();
      }, "html");
}

function hideTiret(val){
		var opts = $("option[value='"+val+"']");
		for (i=0;i<opts.length;i++){
			if(opts[i].innerHTML == "--" || opts[i].innerHTML == "----" ){
				opts[i].style.display = "none";
			}
		};
}

function setRightTab() {
    if ( $("input#sendNotification:checked").length == 0) {
        $("#fieldset-postmeeting").removeClass("hidden");
        $('select.formTabs').eq(0).attr('value', "fieldsetlegend-postmeeting");
        $('#fieldset-event').addClass('hidden');
    };
}
registerPloneFunction(setRightTab);

function displayErrorMessage(field, message) {
    /**
     *  Display an error message on the specified field
     *  Display the global error message
     */

    if (window.failedValidators == 0) {
        $("dl#kssPortalMessage").addClass("error");
        $("dl#kssPortalMessage").removeClass("info");
        $("dl#kssPortalMessage").css("display", "block");
        $("dl#kssPortalMessage > dd").eq(0).html("Veuillez corriger les erreurs indiqu&eacute;es.");
        $("input[name='form_submit']").attr("disabled", "disabled").addClass("standalone").removeClass("context");
    }
    if (!$("div" + field).hasClass("error")) {
        window.failedValidators++;
        $("div" + field).addClass("error");
    }
    $(field + "> div.fieldErrorBox").eq(0).html(message);
}

function removeErrorMessage(field) {
    /**
     *  Remove the error message on the specified field
     *  Remove the global error message if all's ok
     */

    if ($("div" + field).hasClass("error")) {
        window.failedValidators--;
        $("div" + field).removeClass("error");
    }
    $(field + "> div.fieldErrorBox").eq(0).html("");
    if (window.failedValidators == 0) {
        $("dl#kssPortalMessage").removeClass("error");
        $("dl#kssPortalMessage").css("display", "none");
        $("dl#kssPortalMessage > dd").eq(0).html("");
        $("input[name='form_submit']").removeAttr("disabled").addClass("context").removeClass("standalone");
    }
}

function checkBeginEndDates() {
    var startDate = $('input[name="startDate"]').attr('value').substring(0, 16).replace(/[\D\s]/g, "");
    var endDate = $('input[name="endDate"]').attr('value').substring(0, 16).replace(/[\D\s]/g, "");

    if (startDate > endDate) {
        displayErrorMessage("#archetypes-fieldname-endDate", "La date de fin doit &ecirc;tre post&eacute;rieure &agrave; la date de d&eacute;but.");
    } else {
        removeErrorMessage("#archetypes-fieldname-endDate");
    }
}

function checkAnswerLimitDate() {
    var startDate = $('input[name="startDate"]').attr('value').substring(0, 16).replace(/[\D\s]/g, "");
    var answerLimitDate = $('input[name="answerLimitDate"]').attr('value');

    if (!answerLimitDate) {
        answerLimitDate = startDate;
    } else {
        answerLimitDate = answerLimitDate.substring(0,16).replace(/[\D\s]/g, "");
    }
   
    if (answerLimitDate && answerLimitDate > startDate) {
        displayErrorMessage("#archetypes-fieldname-answerLimitDate", "La date limite de r&eacute;ponse doit &ecirc;tre avant la date de d&eacute;but de la r&eacute;union.");
    } else {
        removeErrorMessage("#archetypes-fieldname-answerLimitDate");
    }
}

function checkUrl() {
    var URL_RE = "(http|ftp|irc|news|imap|gopher|jabber|webdav|smb|fish|ldap|pop3|smtp|sftp|ssh)s?://[^\\s\\r\\n]+";
    
    var eventUrl = $('input[name="eventUrl"]').attr('value');
    if (eventUrl && (!eventUrl.match(URL_RE))) {
        displayErrorMessage("#archetypes-fieldname-eventUrl", "Cette URL est invalide.");
    } else {
        removeErrorMessage("#archetypes-fieldname-eventUrl");
    }
}

function checkEmail() {
    var EMAIL_RE = "([0-9a-zA-Z_&.+-]+!)*[0-9a-zA-Z_&.+-]+@(([0-9a-zA-Z]([0-9a-zA-Z-]*[0-9a-z-A-Z])?\.)+[a-zA-Z]{2,6}|([0-9]{1,3}\.){3}[0-9]{1,3})$";

    var contactEmail = $('input[name="contactEmail"]').attr('value');
    if (contactEmail && (!contactEmail.match(EMAIL_RE))) {
        displayErrorMessage("#archetypes-fieldname-contactEmail", "Cette adresse est invalide.");
    } else {
        removeErrorMessage("#archetypes-fieldname-contactEmail");
    }
}

function checkMultiFileFieldValues(field) {
    master_elem_id = "#archetypes-fieldname-" + field;
    var titleFields = $('input[name="' + field + '.title:records"][type=text]:not(:last)');
    titleFields = titleFields.add(master_elem_id + ' table:not(:last) input[type=file]');
    for (var i = 0; i < titleFields.length; i++) {
        elem = titleFields.eq(i);
        if (elem.hasClass("last")) {
            break;
        }
        var elemVal = elem.attr("value");
        if (elemVal == undefined) {
            elemVal = "";
        }
        if (elemVal.strip().length == 0) {
            displayErrorMessage(master_elem_id, "Veuillez remplir ou d&eacute;truire les champs suivants.");
            return;
        }
    }
    removeErrorMessage(master_elem_id);
}

function completeCheck() {
    checkBeginEndDates();
    checkAnswerLimitDate();
    checkEmail();
    checkUrl();
    checkMultiFileFieldValues('businessOrder');
    checkMultiFileFieldValues('otherPreparatoryDocument');
    setTimeout('completeCheck()', 3000);
}


$(document).ready(function(){
    if ($('#fafseameeting-base-edit #title').eq(0).val() == '') {
        prefillMeetingTitle();
    }
    
    if ($('#fafseameeting-base-edit').length > 0) {
		hideTiret("00");
		hideTiret("0000");
        if ($('#instance').length > 0){
            // creation of a meeting
            fill_attendees();
        }
        $('#instance').change(function(){
            // pre-fill title field
            if ($('#fafseameeting-base-edit #instance').length != 0) {
                prefillMeetingTitle();
                fill_attendees();
            }
        });
        
        //// Begin validation code ////
        
        // avoid validator on cancel
        window.dontTest = false;
        window.failedValidators = 0; // at the beginning, all validators are ok


        $("input[name='form.button.cancel']").click(function() {
            window.dontTest = true;
        });

        $('#fafseameeting-base-edit').submit(function() {
            if (window.dontTest) {
                return true;
            }
            return true;
        });
        
        
        /*
        $("#edit_form_startDate_0").parent().mouseout(checkBeginEndDates);
        $("#edit_form_endDate_1").parent().mouseout(checkBeginEndDates);
        $("#edit_form_answerLimitDate_2").parent().mouseout(checkAnswerLimitDate);
        $("#edit_form_startDate_0").parent().change(checkBeginEndDates);
        $("#edit_form_endDate_1").parent().change(checkBeginEndDates);
        $("#edit_form_answerLimitDate_2").parent().change(checkAnswerLimitDate);
        $("#contactEmail").blur(checkEmail);
        $("#eventUrl").blur(checkUrl);
        $("#businessOrder").parent().change(checkMultiFileField).find("img.rowDeleter").click(checkMultiFileField).mouseout(checkMultiFileField);
        $("#otherPreparatoryDocument").parent().change(checkMultiFileField).find("img.rowDeleter").click(checkMultiFileField).mouseout(checkMultiFileField);
        */
        completeCheck();
        
        // XXX install blur events handlers
    };

    $("li#siteaction-plone_setup > a").attr("href", "manage_vocabularies");


    $('#fafseacontact-base-edit').submit(function() {
        if (window.opener != null) {
            var address = $('[name=address]')[0].value + '<br />'
            address += $('[name=zipcode]')[0].value + ' - '
            address += $('[name=city]')[0].value + '<br />'
            address += $('[name=cellphone]')[0].value + '<br />'

            var address_corporate = $('[name=corporateName]')[0].value + '<br />'
            address_corporate += $('[name=corporateAddress]')[0].value + '<br />'
            address_corporate += $('[name=postalCode]')[0].value + ' '
            address_corporate += $('[name=corporateCity]')[0].value + '<br />'
            address_corporate += $('[name=corporatePhoneNumber]')[0].value

            if ($('#user_address_detail', window.opener.parent.document).length != 0)
                { $('#user_address_detail', window.opener.parent.document).html(address) }
            if ($('#company_address_text',window.opener.parent.document).length != 0)
                { $('#company_address_text',window.opener.parent.document).html(address_corporate) }
            window.close()
        }
    })

    if (window.opener != null) {
        $('.contentViews').hide();
    }

    $(document).keypress(function(e) {
        if (e.target.id == 'filter') {
            if (e.which == 13) {
                filter();
                return false;
            }
        }
    });
    $(document).keyup(function(e) {
        if (e.target.id == 'filter') {
            if (e.which == 13) {
                return false;
            }
            else
                timedOutFilter();
        }
    });

    $(document).click(function(e) {
        if (e.target.id == 'all_contacts' )
        {
            $("#filter").eq(0).val("");
            filter();
            return false;
        }
    });

    function _filter() {
        id += 1;
        var select = $('#attendees_options')

        select.children().remove();

        var name = $("#filter").val();

        var clone = $('#attendees_clone');
        var options = clone.children();
        for(var i=0; i<options.length; i++) {
            var option = $(options[i]);
            if (option.html().toLowerCase().indexOf(name.toLowerCase()) != -1) {
                if ($("option[value='" + option.val() + "']", $('#attendees')).length == 0) {
                    select.append('<option value="' + option.val() + '">' + option.html() + '</option>');
                }
            }
        }
        select.children().attr('selected', 'selected');
    }

    function filter() {
        var select = $('#attendees_options')
        select.children().remove();
        select.prepend("<option>(Loading ...)</option>");
        setTimeout(_filter, 0);
    }

    function timedOutFilter() {
        id += 1;
        var local_id = id;
        setTimeout(function() {
            if (id == local_id) {
                filter();
            }
        }, 500);
    }

});


var Fafsea = {};

Fafsea.init = function() {
    $('.contentActions').hide();
    var field = document.getElementById('archetypes-fieldname-businessOrder01');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {
            labels[1].style.margin = '0 0 0 -72px';
            labels[2].style.margin = '0 0 0 -64px';
            labels[3].style.margin = '0 0 0 -16px';
        }
    }

    var field = document.getElementById('archetypes-fieldname-businessOrder02');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
    if (labels.length != 1) {

        labels[1].style.margin = '0 0 0 -72px';
        labels[2].style.margin = '0 0 0 -64px';
        labels[3].style.margin = '0 0 0 -16px';
        }
    }

    var field = document.getElementById('archetypes-fieldname-businessOrder03');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {
            labels[1].style.margin = '0 0 0 -72px';
            labels[2].style.margin = '0 0 0 -64px';
            labels[3].style.margin = '0 0 0 -16px';
        }
    }

    var field = document.getElementById('archetypes-fieldname-businessOrder04');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {

            labels[1].style.margin = '0 0 0 -72px';
            labels[2].style.margin = '0 0 0 -64px';
            labels[3].style.margin = '0 0 0 -16px';
        }
    }


    var field = document.getElementById('archetypes-fieldname-tempPostMeetingDocument');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {

            labels[1].style.margin = '0 0 0 -72px';
            labels[2].style.margin = '0 0 0 -64px';
            labels[3].style.margin = '0 0 0 -16px';
        }
    }

    var field = document.getElementById('archetypes-fieldname-postMeetingDocument');
    if (field) {
        var divs = field.getElementsByTagName('div');
        divs[2].style.padding = '0 0 0 0';
        divs[3].style.padding = '0 0 0 0';
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {
            labels[1].style.margin = '0 0 0 -72px';
            labels[2].style.margin = '0 0 0 -64px';
            labels[3].style.margin = '0 0 0 -16px';
        }
    }

    var field = document.getElementById('archetypes-fieldname-state');
    if (field) {
        var labels = field.getElementsByTagName('label');
        labels[1].style.margin = '0 0 0 -0px';
        labels[1].style.textAlign = 'left';
        labels[2].style.margin = '0 0 0 -0px';
        labels[2].style.textAlign = 'left';
    }

    var field = document.getElementById('archetypes-fieldname-photo');
    if (field) {
        var labels = field.getElementsByTagName('label');
        if (labels.length != 1) {
            labels[1].style.margin = '0 0 0 -73px';
            labels[2].style.margin = '0 0 0 -62px';
            labels[3].style.margin = '0 0 0 -9px';
        }
    }

    $('input',$('#placeInTheCollection')).checked='checked'

}


    /*
    * Montre / Cache un div
    */
    function DivStatus( nom, numero )
        {
            var divID = nom + numero;
            if ( document.getElementById && document.getElementById( divID ) ) // Pour les navigateurs recents
                {
                    Pdiv = document.getElementById( divID );
                    PcH = true;
                 }
            else if ( document.all && document.all[ divID ] ) // Pour les veilles versions
                {
                    Pdiv = document.all[ divID ];
                    PcH = true;
                }
            else if ( document.layers && document.layers[ divID ] ) // Pour les tres veilles versions
                {
                    Pdiv = document.layers[ divID ];
                    PcH = true;
                }
            else
                {

                    PcH = false;
                }
            if ( PcH )
                {
                    Pdiv.className = ( Pdiv.className == 'cachediv' ) ? '' : 'cachediv';
                }
        }

    /*
    * Cache tous les divs ayant le meme prefixe
    */
    function CacheTout( nom )
        {
            var NumDiv = 1;
            if ( document.getElementById ) // Pour les navigateurs recents
                {
                    while ( document.getElementById( nom + NumDiv) )
                        {
                            SetDiv = document.getElementById( nom + NumDiv );
                            if ( SetDiv && SetDiv.className != 'cachediv' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
            else if ( document.all ) // Pour les veilles versions
                {
                    while ( document.all[ nom + NumDiv ] )
                        {
                            SetDiv = document.all[ nom + NumDiv ];
                            if ( SetDiv && SetDiv.className != 'cachediv' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
            else if ( document.layers ) // Pour les tres veilles versions
                {
                    while ( document.layers[ nom + NumDiv ] )
                        {
                            SetDiv = document.layers[ nom + NumDiv ];
                            if ( SetDiv && SetDiv.className != 'cachediv' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
        }

    /*
    * Montre tous les divs ayant le meme prefixe
    */
    function MontreTout( nom )
        {
            var NumDiv = 1;
            if ( document.getElementById ) // Pour les navigateurs recents
                {
                    while ( document.getElementById( nom + NumDiv) )
                        {
                            SetDiv = document.getElementById( nom + NumDiv );
                            if ( SetDiv && SetDiv.className != '' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
            else if ( document.all ) // Pour les veilles versions
                {
                    while ( document.all[ nom + NumDiv ] )
                        {
                            SetDiv = document.all[ nom + NumDiv ];
                            if ( SetDiv && SetDiv.className != '' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
            else if ( document.layers ) // Pour les tres veilles versions
                {
                    while ( document.layers[ nom + NumDiv ] )
                        {
                            SetDiv = document.layers[ nom + NumDiv ];
                            if ( SetDiv && SetDiv.className != '' )
                                {
                                    DivStatus( nom, NumDiv );
                                }
                            NumDiv++;
                        }
                }
        }

    /*
    * Inverse les divs: Cache les divs visible et montre le divs caches :)
    */
    function InverseTout( nom )
        {
            var NumDiv = 1;
            if ( document.getElementById ) // Pour les navigateurs recents
                {
                    while ( document.getElementById( nom + NumDiv ) )
                        {
                            SetDiv = document.getElementById( nom + NumDiv );
                            DivStatus( nom, NumDiv );
                            NumDiv++;
                        }
                }
            else if ( document.all ) // Pour les veilles versions
                {
                    while ( document.all[ nom + NumDiv ] )
                        {
                            SetDiv = document.all[ nom + NumDiv ];
                            DivStatus( nom, NumDiv );
                            NumDiv++;
                        }
                }
            else if ( document.layers ) // Pour les tres veilles versions
                {
                    while ( document.layers[ nom + NumDiv ] )
                        {
                            SetDiv = document.layers[ nom + NumDiv ];
                            DivStatus( nom, NumDiv );
                            NumDiv++;
                        }
                }
        }

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function phone_addRow(template,place) {
      newLine = $(template).clone().show();
      newLine.removeAttr("id");
      newLine.removeAttr("style");
      place = place + ":last"
      $(place).after(newLine);
}

registerPloneFunction(Fafsea.init);


