/* select */
(function($) {
    $.fn.selectable = function() {
        return this.each(function() {
            var value = $('.selectable_value', this);
            var select = $('.selectable_values', this);
            var id;

            $(this).bind('mousenter mouseleave', function(e) {
                if (e.type == 'mouseenter')
                    select.fadeIn(100);
                else
                    select.fadeOut(100);
            });

            value.html($('.selectable_item.selectable_item_current', this).text())
                    .mouseover(function() {
                select.fadeIn(100);
            });

            $('.selectable_item', this).click(function() {
                $(value).html($(this).text());
                $('.selectable_item.selectable_item_current', $(this).parents('.selectable'))
                        .removeClass('selectable_item_current');
                $(this).addClass('selectable_item_current');
                select.fadeOut(100);
            });
        })
    }
})(jQuery);


/* dialog */
(function($) {
    $.fn.confirmable = function(config) {

        if (!$('.dialog').length) {  // create & init dialog
            var d = $(getHtml()).appendTo(document.body);

            $('.dialog_button_cancel', d).click(function() {
                d.fadeOut(100);
            }).attr('title', '');
        }

        return this.each(function() {
            var el = $(this);
            if (el.attr('title') && /^confirm:/.test(el.attr('title'))) {
                el.data('_confirm', el.attr('title').replace(/^confirm:/i, '')).attr('title', '');
                el.click(onClick);
            }
        });

        function onClick(e) {
            var el = $(e.currentTarget),       
                    pos = el.offset(),
                    dialog = $('.dialog'),
                    text = $('.dialog_text', dialog);

            if($(this).hasClass('js_confirm_blocked'))
                return false;

            text.html(el.data('_confirm'));
            dialog.css('left', Math.min(e.clientX - 140, document.body.clientWidth - 280 - 14))
                    .css('top', Math.max(document.documentElement.scrollTop + 10, pos.top - 110));
            dialog.fadeOut(50).fadeIn();
            var target = el;

            $('.dialog_button_ok', dialog).unbind('click').click(function() {
                if (target) {
                    if (config && config.callback)
                        config.callback(target);

                    else if (target.attr('href'))
                        window.location = target.attr('href');

                    dialog.fadeOut(100);
                }
            });

            return false;
        }

        function getHtml() {
            return ' <div class="dialog">   \
                       <div class="dialog_bg"> </div>  \
                       <div class="dialog_content"> \
                            <div class="dialog_icon"></div> \
                            <div class="dialog_text"></div> \
                            <div class="dialog_footer"> \
                                <div class="dialog_buttons"> \
                                    <div class="dialog_button dialog_button_ok">OK</div> \
                                    <div class="dialog_button dialog_button_cancel">Cancel</div> \
                                </div>\
                            </div>\
                        </div>\
                    </div> ';
        }
    };

})(jQuery);


/* editable grid */
(function($) {
    $.fn.editableGrid = function(config) {

        return this.each(function() {
            config = config || { field_of_added: '', field_of_deleted: '', showDialogOnExtraAdd: null };

            var _this = this,
                    grid = $('table', this),
                    add_button = $('.grid_button', _this),
                    field_add = $('[name=' + config.field_of_added + ']', _this).val(''),
                    field_del = $('[name=' + config.field_of_deleted + ']', _this).val(''),
                    empty_row = $('tr.nodisplay:first', grid).detach();

            if(!$('tr.nodisplay', grid).length){
               add_button.hide();                 
            }

            function remove(el) {
                el = $(el);
                var tr = el.parents('tr');
                tr.fadeOut(300, function() {
                    empty_row.clone().appendTo(tr.parent());
                    updateFields(el.attr('id')); // must be string
                    tr.remove();
                });
            }

            function add() {
                if (config.showDialogOnExtraAdd && !isAddAllowed()) {
                    $('.js_change_plan_dialog_for_channels').dialog({
                        width: 430
                    });

                    return;
                }

                var tr = $('tr.nodisplay:first', grid).removeClass('nodisplay');
                var d = $('.grid_delete_button', tr);

                $(d).click(function(e) {
                    remove(e.currentTarget);
                });
                updateFields(null, 1);
            }

            function updateFields(id, num) {
                var v;

                if (id == '')
                    num = -1;

                if (id) { // delete by id
                    v = field_del.val();
                    v = v ? v.split(',') : [];

                    if ($.inArray(id, v) < 0)
                        v.push(id);

                    field_del.val(v.join(','));
                } else { // add/del new
                    v = field_add.val() * 1;
                    v = isNaN(v) ? 0 : v;
                    v += num;
                    field_add.val(v);
                }

                if(!config.showDialogOnExtraAdd){ // show/hide button if dialog css didn't defined
                    if (isAddAllowed())
                        add_button.fadeIn(300);
                    else
                        add_button.fadeOut(300);
                }
            }

            function isAddAllowed(){
                return $('tr.nodisplay', grid).length > 0;
            }

            (function() {  /* init */
                add_button.click(add);
                $('.grid_delete_button', grid).confirmable({
                    callback: remove
                })
            })()
        });
    }
})(jQuery);


/* form plugin *
 /* 1. To make field required - set title="jsform_req"
 2. A field ending on .width/.length/.left/.top is numeric
 3. A field containing 'email' is email-field
 4. Confirmation password field must have id="[password field id]_confirm"
 5. To mark an element as a submit button - put title="jsform_submit"
 6. Invalid form item has additional css class: class="form_item form_item_invalid"
 */
(function($) {
    $.fn.formable = function() {
        return this.each(function() {
            var form = $(this),
                    validateOnSubmit = false,
                    inputs = $('input[type=text], input[type=password]', form),
                    submit = $('[title=jsform_submit]', form).attr('title', ''),
                    isFormValid = true;

            // mark required
            inputs.each(function() {
                if ($(this).attr('title') == 'jsform_req')
                    $(this).data('_required', true).attr('title', '');
                //                            .addClass('required');
            });

            // assign listeners
            inputs.bind('blur', validate)
                    .focus(function() {
                $(this).parents('.form_item').removeClass('form_item_invalid');
            });


            $('.jabber_select input[type=radio]', form).click(function(){
                if($('.jsform_jabber').val() || $('.jsform_jabber').data('_activated')) // if it was shown
                    validate(null, $('.jsform_jabber'))
            });

            $('.jsform_jabber', form).focus(function(){
               $(this).data('_activated', true);
            });
                        
            form.submit(function () {                
                isFormValid = true;
                validateOnSubmit = true;
                $(inputs).each(function() {
                    var v = validate(null, this);
                    isFormValid = isFormValid && v;
                });

                validateOnSubmit = false;
                
                return isFormValid;
            });

            submit.click(function(){
                form.submit();
            });

            $(':input', form).keydown(function(e){
               if(e.keyCode == 13)
                    form.submit();
            });

            function validate(e, el) {
                el = $(e ? e.currentTarget : el);
                if (!el.hasClass('jsform_jabber') && (el.attr('disabled') || el.css('display') == 'none')) {
                    setValid(el, true);
                    return true;
                }

                var type = getType(el),
                        val = el.val(),
                        required = el.data('_required'),
                        isValid = !required || (required && !!val);

                if(val){
                    switch (type) {
                        case 'num':
                            val = val.trim();
                            isValid = isValid && !/\D/.test(val);
                            break;

                        case 'pageCount':
                            val = val.trim();
                            isValid = isValid && !/\D/.test(val)&&val>0;
                            break;

                        case 'email':
                            val = val.trim();
                            isValid = isValid && /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test(val);
                            break;

                        case 'password_confirm':
                            var p = $('#' + el.attr('id').replace(/_confirm$/, ''), form); // find original pass field

                            if (p.length)
                                isValid = p.val() ? val == p.val() : true;
                            break;

                        case 'jabber':
                            var jabber = ($('input[type=radio]:checked', $('.jabber_select')).attr('id') || '').replace(/^\w*_/, '') || 'p3chat',
                            reg = { // default jabber value used in my info
                                p3chat: /^[A-Z0-9._%+-]+$/i,
                                gTalk: /^[_A-Z0-9-]+(\.[_A-Z0-9-]+)*@GMAIL\.COM$/i,
                                MSN: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i,
                                Yahoo: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i,
                                Jabber: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i,
                                ICQ: /\d{5,10}/i
                            }[jabber];

                            isValid = reg ? reg.test(val.trim()) : true;
                    }
                }
                
                setValid(el, isValid);
                return isValid;
            }

            function setValid(el, isValid) {
                $(el).parents('.form_item').toggleClass('form_item_invalid', !isValid);
                if(validateOnSubmit && !isValid){
                   var ac_item = $(el).parents('.accordeon_item');
                    if(!ac_item.hasClass('accordeon_item_open'))
                       $('.accordeon_item_head', ac_item).trigger('click');
                }
            }

            function getType(el) {
                var name = $(el).attr('name'),
                        id = $(el).attr('id');

                if (name.match(/email/i))
                    return 'email';
                else if (name.match(/\.width|\.height|\.left|\.top/i))
                    return 'num';
                else if(name.match(/\.pageCount/i))
                    return 'pageCount';
                else if (el.attr('type') == 'password')
                    return /_confirm/.test(id) ? 'password_confirm' : 'password';
                else if (el.attr('class').match(/jsform_jabber/))
                    return 'jabber';
                else
                    return 'text';
            }
        });
    };
})(jQuery);

/* hint plugin */
(function($) {
    $.fn.hintable = function() {
        var hint = $(getHtml()).appendTo(document.body);
        var hint_text = $('.hint_body_center div', hint);
        var hint_t = $('.hint_top', hint);
        var hint_b = $('.hint_bottom', hint);
        var MIN_WIDTH = 300;
        var MAX_WIDTH = 400;

        if (!hint.length)
            return this;

        function toggleHint(e) {
            if (e.type == 'mouseleave') {
                hint.fadeOut(100);
            } else {
                var el = $(e.currentTarget),
                        pos = el.offset(),
                        top, left, width, desire_width, invert;


                hint_text.html(el.data('_hint'));

                hint.css('visibility', 'visible')
                    .css('display', 'block').width(MAX_WIDTH);

                hint_text.css('display', 'inline');
                desire_width = Math.min(MIN_WIDTH, hint_text.width());
                hint_text.css('display', 'block');

                top = pos.top + el.height() + 7;
                left = Math.max(0, pos.left - 50);
                width = Math.min(desire_width + 80, MAX_WIDTH);

                if(left + width >= document.body.clientWidth)
                    left = document.body.clientWidth - width;

                hint.css('width', width);
                hint.height(hint_t.height() + hint_b.height() + hint_text.height());

                invert = top + hint.height() + 3 > $(document.body).height() + document.documentElement.scrollTop;
                hint.toggleClass('hint_inverted', invert);

                hint.css('left', left)                            
                    .css('top', invert ? pos.top - hint.height() - 7 : top);

                hint.hide().css('visibility', 'visible').fadeIn(200);
            }
        }

        function getHtml() {
            return ' \
            <div class="hint"> \
                <div class="hint_top">  \
                        <div class="hint_top_right"></div>\
                        <div class="hint_top_center"></div> \
                        <div class="hint_top_left"></div>   \
                </div>\
                <div class="hint_body">\
                        <div class="hint_body_right"></div>\
                        <div class="hint_body_center"><div></div></div>\
                        <div class="hint_body_left"></div>\
                </div>\
                <div class="hint_bottom">\
                        <div class="hint_bottom_right"></div>\
                        <div class="hint_bottom_center"></div>\
                        <div class="hint_bottom_left"></div> \
                </div>\
            </div>  ';
        }

        return this.each(function() {
            var el = $(this);
            if (el.attr('title') || el.hasClass('hintable_content')) {
                var id;

                el.data('_hint', el.hasClass('hintable_content') ? el.html() : el.attr('title')).attr('title', '');
                el.bind('mouseenter mouseleave', function(e) {
                    if (id)
                        window.clearTimeout(id);

                    if (e.type == "mouseenter")
                        id = window.setTimeout(function() {
                            toggleHint(e);
                        }, 200);
                    else
                        toggleHint(e);
                });
            }
        });
    };
})(jQuery);

/* sortable grid plugin
 1. put <small></small> into thead td to make column sortable
 2. set type of td-data by title=""
 3. to set rot always on the top set <tr title="sort_top">
 */
(function($) {
    $.fn.sortableGrid = function() {
        return this.each(function() {
            var grid = this;
            init();

            function init() {
                $('thead tr td', grid).each(function(i) {
                    if ($('small', this).length) {
                        $('div', this).css('cursor', 'pointer')
                                .click(function() {
                            sortBy(i);
                        })
                    }
                });

                if (!$('.no_auto_sort',grid).length) {
                    sortBy();
                }
                $(grid).css('visibility', 'visible');
            }

            function sortBy(col) {
                var up, toggle;

                if (col == null) {
                    var cookie = (Util.cookie('_gridsort') || "0,0").split(',');
                    col = cookie[0] * 1;
                    up = cookie[1] * 1 == 0;
                }

                toggle = $('thead td:eq(' + col + ') small', grid);
                up = up == null ? !toggle.hasClass('up') : up;
                Util.cookie('_gridsort', [col, up ? 0 : 1].join(','));

                var type = $('thead td:eq(' + col + ') div', grid).attr('title');
                var trs = $('tbody tr', grid).sort(function(a, b) {
                    var tda = $('td:eq(' + col + ')', a);
                    var tdb = $('td:eq(' + col + ')', b);
                    var top_a = $(a).attr('title') == 'sort_top';
                    var top_b = $(b).attr('title') == 'sort_top';
                    var va, vb;

                    switch (type) {
                        case 'sort_checkbox':
                            va = $('input[type="checkbox"]', tda).get(0).checked ? 1 : 0;
                            vb = $('input[type="checkbox"]', tdb).get(0).checked ? 1 : 0;
                            break;

                        case 'sort_online_offline':
                            va = $('div', tda).hasClass('operator_online') ? 1 : 0;
                            vb = $('div', tdb).hasClass('operator_online') ? 1 : 0;
                            break;

                        case 'number':
                            va = tda.text() * 1;
                            vb = tdb.text() * 1;
                            va = isNaN(va) ? 0 : va;
                            vb = isNaN(vb) ? 0 : vb;
                            break;

                        default: // by text
                            va = $.trim($('td:eq(' + col + ')', a).text().toLowerCase());
                            vb = $.trim($('td:eq(' + col + ')', b).text().toLowerCase());
                    }

                    if (top_a || top_b)
                        return top_a ? -1 : 1;

                    if (up)
                        return va < vb ? -1 : (va == vb ? 0 : 1);
                    else
                        return vb < va ? -1 : (va == vb ? 0 : 1);
                });

                //               show with pause
                trs.detach().appendTo($('tbody', grid));
                $('thead small', grid).removeClass('up down');
                toggle.addClass(up ? 'up' : 'down');
                $('tbody', grid).fadeIn(300);
            }
        });
    };
})(jQuery);

/*  multiselect control plugin */
(function($) {
    $.fn.multiselectGrid = function() {
        return this.each(function() {
            var _this = this,
                    hash = {},
                    grid = $('table', _this),
                    input = $('input[type="hidden"]', _this),
                    select = $('select', $(this)),
                    options = $('option', select),
                    warning = $(this).nextAll('.warning');

            init();

            function refresh() {
                var v = input.val().split(',');
                v = v[0] == '' ? [] : v;
                input.val('');

                $(v).each(function(i) {
                    updateValue(v[i], true)
                });

                if (!v.length)
                    warning.fadeIn();
            }

            function updateValue(id, add) {
                if (id * 1 == 0 || isNaN(id * 1))
                    return;

                var v = input.val().split(',');
                v = v[0] == '' ? [] : v;

                var i = $.inArray(id, v);

                /* Add */
                if (add && i < 0) {
                    v.push(id);
                    adjustOption(id, true);

                    if (hash[id]) {
                        hash[id].css('display', '');
                    }

                } else if (!add && i >= 0) {
                    v.splice(i, 1);
                    hash[id].css('display', 'none');
                    adjustOption(id, false);
                }

                input.val(v.join(','));

                if (v.length)
                    warning.fadeOut();
                else
                    warning.fadeIn();

                if (!add && id == select.val()) {
                    select.get(0).selectedIndex = 0;
                }
            }

            function adjustOption(id, onAdd) {
                $('option[value="' + id + '"]', select)
                        .toggleClass('blue', onAdd)
                        .css('padding-left', onAdd ? '10px' : 0)
                        .css('font-weight', onAdd ? 'bold' : 'normal');
            }

            function init() {
                /* build a hash & select content*/
                $('tr', grid).each(function() {
                    var id = this.id;
                    if (id != null) {
                        this.id = null;
                        hash[id] = $(this);
                        $(this).data('_id', id);
                        $(this).css('display', 'none');
                        $('<option></option>').appendTo(select)
                                .attr('value', id)
                                .html($('b', this).html());
                    }
                });

                /* delete handler */
                $('.grid_delete_button', grid).click(function(e) {
                    var el = $(e.currentTarget).parents('tr');

                    $(el).fadeOut(200, function() {
                        updateValue($(el).data('_id'), false);
                    });
                });

                refresh();
                grid.removeClass('no-display');
                select.get(0).selectedIndex = 0;
                select.bind('change', function() {
                    if (select.get(0).selectedIndex > 0)
                        updateValue($(this).val(), true);
                })
            }
        });
    }
})(jQuery);

/* pricing tarifs */
(function($) {
    $.fn.pricable = function() {
        return this.each(function() {
            var discounts = {
                1: 0,
                3: 0.05,
                6: 0.10,
                12: 0.20
            };
            var extraMoney = 37;
            var link = $('.tarif_signup', this);
            var price_box = $('.tarif_price span', this);
            var radios = $('.tarif_discounts input[type="radio"]', this);
            var fullprice_box = $('.tarif_price b', this);

            if(!radios.length)
                return;

            var tarif_num = radios.first().attr('name').replace(/\D/g,'');
            var origin_price = new Number(price_box.html().replace(/\D/g,''));
            
            $(radios).each(function(obj){
                if($(this).get(0).checked){
                    updatePrice($(this).attr('value'));
                }
            });

            radios.bind('change', function(){
                updatePrice($(this).attr('value'));
            });

            function updatePrice(months){
                months = new Number(months);
                var full_price = origin_price * months;
                
                fullprice_box.html(discounts[months] > 0 ? '$' + full_price/100 : '');
                price_box.html('$' + Math.floor(full_price * (1 - discounts[months]))/100);
                var href = link.attr('href');
                href = href.replace(/\?.*/,'') + '?tarif=' + tarif_num + '&months=' + months;
                link.attr('href', href);
            }
        });
    }
})(jQuery);

/* checkbox column with selectAll checkbox  */
(function($) {
    $.fn.checkboxColumn = function() {
        return this.each(function() {
            var grid = $('#checkboxColumnGrid');
            var input = $('#checkboxColumnCheckedItems');
            var deleteSubmit = $("#checkboxColumnDeleteSubmit");
            var checkboxes = [];
            var selectAll = $('input[name=selectAll]', grid);

            if($(deleteSubmit).length && $(deleteSubmit).attr('title').match(/^confirm:/)){
                $(deleteSubmit).confirmable({
                    callback: function(){
                        $(input).parents('form').submit()
                    }
                })
            }

            $('input[type=checkbox]', grid).each(function() {
                if ($(this).attr('name') != 'selectAll')
                    checkboxes.push(this);
            });

            $(selectAll).change(function(){
               var checked = $(this).attr('checked');
               $(checkboxes).attr('checked', checked);
               refreshResult();
            });

            $(checkboxes).change(function() {
                var checkedAll = true;

                $(checkboxes).each(function() {
                    if(!$(this).attr('checked')){
                        checkedAll = false;
                        return false;
                    }
                });

                $(selectAll).attr('checked', checkedAll);
                refreshResult();
            });

            function refreshResult() {

                var checked = [];
                $(checkboxes).each(function() {
                    if ($(this).attr('checked'))
                        checked.push($(this).attr('name'));
                });

                $(deleteSubmit)[checkboxes.length ? 'show' : 'hide']().css('opacity', checked.length ? 1 : 0.6);
                $(deleteSubmit).toggleClass('js_confirm_blocked', !checked.length);
                $(input).val(checked.join(','));
            }

           $(selectAll).trigger('change');
           refreshResult();
        });
    }
})(jQuery);

$(document).ready(function(){
    $('.tarif_disabled input[type=radio]').attr('checked', false).attr('disabled',true);
    $('.tarif').pricable();
}); 




