/*** functions ***/

function get_css(url, folder) {
    if (!folder) var folder = '/style/';
    $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
        rel: "stylesheet",
        type: "text/css",
        href: folder+url
    });
}

/*** Submit a form via Ajax. Response in Json format ***/
function submit_ajax_form(form, url, callback) {
    var data = new Object();
    $('input,select,textarea').each(function() {
        var name = $(this).attr('name');
        var type = $(this).attr('type');
        if (type == 'checkbox')
            var value = $(this).attr('checked')?1:0;
        else if (type == 'radio')
            var value = $('input:radio:checked[name='+name+']').val();
        else
            var value = $(this).val();
        data[name] = value;
    });

    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: data,
        success: callback
    });
}

/*** Create a sortable tree ***/
function create_tree() {
    toArray = $('ol.sortable').nestedSortable('toArray', {startDepthCount: 0, expression: (/(.+)[_](.+)/)});
    //console.log(toArray);
    toJson = $.toJSON(toArray);
    $('#tree').val(toJson);
}

/*** events ***/
$(document).ready(function() {

    /********** DCF ***************/
    $('.dcf_niv').change(function(){
       $(this).parent().parent().attr('class','l'+$(this).val());
    });

    $('#dcf_addrow').click(function(){
       var clonerow = $('.dcf_list tr:last').clone(true);
       clonerow.removeClass('hidden');
       $('.dcf_list').append(clonerow);
    });

    /**** autoresize ***/
    if (typeof $.fn.autoResize=='function') {
        $('textarea.autoresize').autoResize({
            // On resize:
            onResize : function() {
                $(this).css({opacity:0.8});
            },
            // After resize:
            animateCallback : function() {
                $(this).css({opacity:1});
            },
            // Quite slow animation:
            animateDuration : 300,
            // More extra space:
            extraSpace : 0
        }).trigger('change');
    }

    /**** editable ***/
    // session values are editable
    $('.sessions-value').addClass('editable');

    // add the editable feature to all elements
    // controller editable (pour un edit avec ajax)
    // editable (pour un edit simple)
    if (typeof $.fn.editInPlace=='function') {
        $('.editable').each( function(){
            var controller = $(this).attr('class').split('-',1)[0];
            var method = 'update_field';
            if ($(this).text().length > 80)
                var type = 'textarea';
            else
                var type = 'text';
            if (controller=='editable')
                var blur = 'null';
            else
                var blur = 'save';

            $(this).editInPlace({
                on_blur : blur,
                url: '/'+controller+'/'+method+'/',
                show_buttons: false,
                field_type: type,
                textarea_cols: 50,
                textarea_rows: 3
            });
        });
    }

    /*** duplicate ***/
    $('.duplicate').change(function() {
        id = $(this).attr('id');
        if ($('.'+id).val()=="") {
            $.ajax({
                type: 'POST',
                url: '/page/url_title/',
                data: {
                    str : $(this).val()
                },
                success: function(data) {
                    $('.'+id).val(data);
                }
            });
        }
    });

    /**** reduce expend ****/
    $('.reduce').live('click', function(){
            id = $(this).attr('id');
            $(this).next('.'+id).hide();
            $(this).removeClass('reduce');
            $(this).addClass('expend');
    });

    $('.expend').live('click', function(){
        id = $(this).attr('id');
        $(this).next('.'+id).show();
        $(this).removeClass('expend');
        $(this).addClass('reduce');
    });

    /**** datepicker ****/
    if (typeof $.fn.datepicker=='function') {
        $(function() {
            date_obj = new Date();
            date_obj_hours = date_obj.getHours();
            date_obj_mins = date_obj.getMinutes();
            date_obj_sec = date_obj.getSeconds();
            date_obj_time = date_obj_hours+':'+date_obj_mins+':'+date_obj_sec;

            $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
            $(".datetimepicker").datepicker({ dateFormat: 'yy-mm-dd '+date_obj_time });
            $(".datepicker_locale").datepicker({ dateFormat: 'dd/mm/yy' });
        });
    }

    /*** autocomplete ***/
    /*** <input id="controller-field-label" class="autocomplete type="text" /> ***/
    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }
    if (typeof $.fn.autocomplete=='function') {
        $(".autocomplete").each( function(){
            var cf = $(this).attr('id').split('-',4);
            var controller = cf[0];
            var method = 'autocomplete';
            var field = cf[1];
            if (cf[2]) var label = cf[2];
            else var label = cf[1];

            $(this).autocomplete({
                source: function(request, response) {
                  $.ajax({
                        type: 'POST',
                        url: '/'+controller+'/'+method,
                        dataType: 'json',
                        data: {
                            search : request.term,
                            field : field,
                            label : label
                        },
                        success: function(data){
                            response(data.message);
                        }
                    })
                },
                minLength: cf[3] || 2
            });
        });
        $(".autocomplete_multi").each( function(){
            var cf = $(this).attr('id').split('-',3);
            var controller = cf[0];
            var method = 'autocomplete';
            var field = cf[1];
            if (cf[2]) var label = cf[2];
            else var label = cf[1];

            $(this).autocomplete({
                source: function(request, response) {
                  $.ajax({
                        type: 'POST',
                        url: '/'+controller+'/'+method,
                        dataType: 'json',
                        data: {
                            search : request.term,
                            field : field,
                            label : label
                        },
                        success: function(data){
                            response(data.message);
                        }
                  })
                },
                minLength: 2,
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function(event, ui){
                   var terms = split( this.value );
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            });
        });
    }

    /**** upload && upload multi ***/
    $('.upload, .upload_multi').each(function(index){
        //var me = $(this);
        var id = $(this).attr('id')
        var cf = id.split('-',3);
        var controller = cf[0];
        var method = cf[1];
        var types = cf[2].replace(/_/g, '|');
        var button = $(this);

        new AjaxUpload(button,{
            action: '/'+controller+'/'+method,
            name: 'Filedata',
            onSubmit : function(file, ext){
                var regex = new RegExp('^'+types+'$', 'i');
                if (ext && regex.test(ext)){
                    button.addClass('loading');
                    this.disable();
                } else {
                    alert('Seuls les fichiers '+types.replace('|', ', ')+' de moins de 2Mo sont autorisés');
                    return false;
                }
            },
            onComplete: function(file, response){
                response = jQuery.parseJSON(response);
                button.removeClass('loading');
                this.enable();

                if (response.error != '') {
                    button.addClass('error');
                    alert(response.error);
                } else {
                    button.removeClass('error');
                    if (button.hasClass('upload_multi')) {
                        $('.upload_multi').before('<span class="mod_upload">\n\
                            <span class="btn_upload_delete" id="block_img-span"></span>\n\
                            <span class="btn_upload_img success"><img src="'+response.img_src+'"/></span>\n\
                            <input name="imgs[]" value="'+response.file_name+'" type="hidden"/>\n\
                            </span>');
                        $('.upload_form').append('');
                    } else {
                        button.addClass('success');
                        button.html('<img src="'+response.img_src+'"/>');
                        $('.'+button.attr('id')).val(response.file_name);
                    }
                }
            }
        });
    });

    $('.btn_upload_delete').live('click', function() {
        $(this).parents('.mod_upload').fadeOut().remove();
    });

    /**** clone a row ***/
    $('.addrow').click(function(){
        // id must contain :
        // 1st param the container element's id
        // 2nd param the type of element to clone
        // optional 3rd param : int max rows
        // optional 4th param : a class containing the counter
        var cf = $(this).attr('id').split('-', 4);
        var num = 0;
        if (cf[3]) {
            num = parseInt($('#'+cf[0]+' '+cf[1]+':last .'+cf[3]+':first').text());
            if (!num)
                num = parseInt($('#'+cf[0]+' '+cf[1]+':last .'+cf[3]+':first').val());
        }
        var clonerow = $('#'+cf[0]+' '+cf[1]+':last').clone(true);
        $(':input',clonerow).clearform();
        $('#'+cf[0]).append(clonerow);
        if (cf[1] != 'tr') {
            clonerow.hide();
            clonerow.slideDown();
        }
        if (cf[2] && cf[2] > 0 && num+1 >= cf[2]) {
            $(this).hide();
        }
        if (cf[3]) {
            $('#'+cf[0]+' '+cf[1]+':last .'+cf[3]).text(num+1);
            $('#'+cf[0]+' '+cf[1]+':last .'+cf[3]).val(num+1);
        }
    });

    $('.removerow').live('click', function(){
        // id must contain :
        // 1st param the container element's id
        // 2nd param the type of element to clone
        var cf = $(this).attr('id').split('-', 2);
        var num = $('#'+cf[0]+' '+cf[1]).size();
        if (num > 2) {
            $(this).parents('#'+cf[0]+' '+cf[1]).fadeOut();
            $(this).parents('#'+cf[0]+' '+cf[1]).remove();
        }
    });

    /**** clear form inside a container ***/
    $.fn.clearform = function() {
        return this.each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearform();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select') {
            this.selectedIndex = 0;
            $(this).find('option:disabled').attr('disabled', '');
        }
        });
    };

    /*** Generate Select ***/
    $('.generate_select').live('change', function() {
        var cf = $(this).attr('id').split('-',3);
        var controller = cf[0];
        var method = 'generate_select';
        var condition = cf[1];
        var field = cf[2];
        if (cf[3]) var label = cf[3];
        else var label = cf[2];

        var current = $(this).index('.linked');

        if ($(this).val() == '') {
            $('.linked:gt('+(current)+')').empty();
            $('.linked:gt('+(current)+')').attr('disabled', 'disabled');
        } else {
            var select = $('.linked').eq(current+1).attr('options');
            $('.linked:lt('+(current+2)+')').attr('disabled', '');
            $('.linked:gt('+(current+1)+')').attr('disabled', 'disabled');

            $.ajax({
                type: 'POST',
                url: '/'+controller+'/'+method,
                dataType: 'json',
                data: {
                    condition : condition,
                    search : $(this).val(),
                    field : field,
                    label : label
                },
                success: function(data){
                    select.length = 0;
                    select[select.length] = new Option('', '', true, true);
                    $.each(data.message, function () {
                        select[select.length] = new Option(this.label, this.value, false, false);
                    });
                }
            });
        }
    });

    if (typeof $.fn.lightbox_me=='function') {
        /*** Lightbox something ! ***/
        $('.lightbox_link').click(function() {
            var id = $(this).attr('id').split('-')[1];
            $("#lightbox-"+id).lightbox_me({
                centered: true,
                onLoad: function() {$("#lightbox-"+id).find("input:first").focus();},
                closeSelector: '.close'
            });
            return false;
        });

        /*** Lightbox something and display ajax content ! ***/
        /*** Usage: <a class="ajax_lightbox_link" href="l'url de la page">***/
        /*** Dans le controlleur $this->load->view(TEMPLATE.(isset($_POST['ajax']) ? 'ajax' : 'home'), $data); ***/
        $('.ajax_lightbox_link').click(function() {
            var url = $(this).attr('href');
            $('#ajax_lightbox').html('');
            $('#ajax_lightbox').attr('style', 'background:url(/images/admin/fs2/ajax-loader.gif) center center no-repeat;');
            $.ajax({
                type: 'POST',
                url: url,
                data: "ajax=1",
                success: function(data){
                    $('#ajax_lightbox').attr('style', '');
                    $('#ajax_lightbox').html(data);
                    $('#ajax_lightbox').lightbox_me({
                        centered: true,
                        onLoad: function() {
                            $('#ajax_lightbox').find('input:first').focus();
                        },
                        closeSelector: '.close'
                    });
                }
            });
            return false;
        });
    }

    /*** Lightbox images ***/
    if (typeof $.fn.lightBox=='function') {
        $('.gallery a[class!="nogallery"]').lightBox({
            imageLoading: '/images/lightbox/ico-loading.gif',
            imageBtnClose: '/images/lightbox/btn-close.gif',
            imageBtnPrev: '/images/lightbox/btn-prev.gif',
            imageBtnNext: '/images/lightbox/btn-next.gif',
            containerResizeSpeed: 350,
            txtImage: 'Image',
            txtOf: 'de'
        });
    }

    /*** Simple carousel ***/
    if ($('.carousel').length > 0) {
        $.getScript('/javascript/jcarousellite_1.0.1.min.js', function() {
            $('.carousel').jCarouselLite({
                btnNext: '.next',
                btnPrev: '.prev',
                auto: 2000,
                visible: 1
            });
            $('.carousel').hide();
            $('.carousel').show();
        });
    }

    /*** Fade out ***/
    //$('.fade_out').delay(3200).fadeOut('slow');

    /*** Slide toggle ***/
    /*** Usage: <a class="slidetoggle" href="#anchor"></a>***/
    $('.slidetoggle').live('click', function() {
    var id = $(this).attr('href');
    $(id).slideToggle(0);
    if ($(id).is(':visible')) {
        $(this).text($(this).text().replace('▼', '▲'));
        $('html, body').animate({
            scrollTop: $($(this).attr('href')).offset().top
        }, 500);
    } else {
        $(this).text($(this).text().replace('▲', '▼'));
    }
    return false;
    });

    /*** sortable ***/
    /*$('ol.sortable').nestedSortable({
        disableNesting: 'no-nest',
        forcePlaceholderSize: true,
        handle: 'div',
        items: 'li',
        opacity: .6,
        placeholder: 'placeholder',
        tabSize: 25,
        tolerance: 'pointer',
        toleranceElement: '> div',
        receive: function(e,ui) {
            copyHelper= null;
        },
        update: create_tree
    })

    $('ol.sortable2').nestedSortable({
            disableNesting: 'no-nest',
            forcePlaceholderSize: true,
            handle: 'div',
            items: 'li',
            opacity: .6,
            placeholder: 'hidden_placeholder',
            tabSize: 25,
            tolerance: 'pointer',
            toleranceElement: '> div',
            connectWith: '.sortable_connected',
            helper: function(e,li) {
                copyHelper= li.clone().insertAfter(li);
                return li.clone();
            },
            stop: function() {
                copyHelper && copyHelper.remove();
            }
    }).disableSelection();*/

    $('.removeli').live('click', function(){
        $(this).parent('div').parent('li').remove();
        create_tree();
    });

    $('.sortable input').live('change', function() {
        create_tree();
    });

    /*** Input default value ***/
    /*** To configure default inactive color use class "default-value-inactive" ***/
    $('input.default-value').addClass('default-value-inactive');
    var default_values = new Array();
    $('input.default-value').live('focus', function() {
        if (!default_values[this.id]) {
            default_values[this.id] = this.value;
        }
        if (this.value == default_values[this.id]) {
            this.value = '';
            $(this).removeClass('default-value-inactive');
        }
        $(this).blur(function() {
            if (this.value == '') {
                $(this).addClass('default-value-inactive');
                this.value = default_values[this.id];
            }
        });
    });

    /*** Multi columns ***/
    if ($.fn.columnize) {
        $('.3columns').columnize({ columns: 3 });
    }

    /*** tipsy ***/
    if ($.fn.tipsy) {
        get_css('tipsy.css');

        $('a[title]').tipsy({gravity: $.fn.tipsy.autoNS, html: true, delayIn: 50, delayOut: 0});
        //$('img[title]').tipsy({gravity: $.fn.tipsy.autoNS, html: true, live: true, delayIn: 50, delayOut: 0});
        $('span[title]').tipsy({gravity: $.fn.tipsy.autoNS, html: true, live: true, delayIn: 50, delayOut: 0});
    }

    // By suppling no content attribute, the library uses each elements title attribute by default
    /*if (typeof $.fn.qtip=='function') {
        $('.qtip[title]').qtip({
            content: {
                text: false // Use each elements title attribute
            },
            position: {
                corner: {
                    target: 'topRight',
                    tooltip: 'bottomLeft'
                }
            },
            style: {
                background: '#DCEAF5',
                color: '#333',
                textAlign: 'center',

                border: {
                    radius: 3,
                    color: '#4B98C6',
                    width: 1
                },
                tip: 'bottomLeft',
                name: 'dark' // Inherit the rest of the attributes from the preset dark style
            }
        });
        $('.qtip').click(function(){return false;});
    }*/

    /*** Autoselect ***/
    $('.autochecked').live('click', function(){
        $(this).find('input').attr('checked', 'checked');
    });

    /*** Calcul prix TTC ***/
    $('.calcul_ttc').keyup(function(){
        calcul_ttc($(this))
    });
    $('.calcul_ttc').each(function(){
        calcul_ttc($(this))
    });

    function calcul_ttc(element) {
        var id = element.attr('id');
        var ht = parseFloat(element.val());
        if (!isNaN(ht)) {
            var tva = $('#tva').val();
            var ttc = Math.round((ht * tva)*100)/100;
            $('#'+id+'_ttc').text(ttc);
        }
    }

    /*** Lightbox images ***/
    /*** Usage: <div class="gallery"><a href="image">Link</a></div> ***/
    /*** Usage multiple gallery: <div class="gallery" id="g1"><a href="image">Link</a></div><div class="gallery" id="g2"><a href="image">Link</a></div> ***/
    var lightbox_options = {
        imageLoading: '/images/lightbox/ico-loading.gif',
        imageBtnClose: '/images/lightbox/btn-close.gif',
        imageBtnPrev: '/images/lightbox/btn-prev.gif',
        imageBtnNext: '/images/lightbox/btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: 'Image',
        txtOf: 'de'
    };
    $('.gallery').each(function() {
        var id = $(this).attr('id');
        if (id) {
            $('#'+id+' a[class!="nogallery"]').lightBox(lightbox_options);
        } else {
            $('.gallery a[class!="nogallery"]').lightBox(lightbox_options);
            return false;
        }
    });


    /********** EPLAQUE ***************/
    $('.dcf_produits').change(function(){
       var intitule = $(this).find('option[value='+$(this).val()+']').text();
       $(this).parent().parent().find('.dcf_intitule').attr('value', intitule);
    });

    $('#adresse_livraison_copy').click(function(){
        $('#adresse_livraison').find('input').each(function(i) {
            $("#adresse_facturation input:eq("+i+")").val($(this).val());
        });
    });

    $('#datepicker_ok').click(function(){
        s=$('#datepicker_date_condition').val();
        e=$('#datepicker_date_condition_end').val();
        document.location.href='/commandes_livraison_et_facturation/liste/date_condition/'+s+'/date_condition_end/'+e+'.html';
        return false;
    });

    $('.departement.seo h3').click(function(){
        $('ul.departements:visible').slideUp();
        $(this).next().slideDown();
    });
    $('.departement.seo ul.departements').hide();
    $('.departement.seo ul.departements.selected').show();

    /*** tabulation ***/
    /*** ATTENTION ceci doit toujours être le dernier script appelé ***/
    if (typeof $.fn.idTabs=='function') {
        $("#usual ul").idTabs();
    }
});

