/*!
 * main.js
 *
 * Copyright (c) 2010 http://wwww.openfilm.com/
 * Dual licensed under the MIT and GPL licenses. 
 * 
 * http://wwww.openfilm.com/design/js/main.js
 */
 
$.fn.backgroundBlink = function (options){
    var options = $.extend({
        from: 'black',
        to: 'white',
        speed: 1500,
        delay: 3000
    },options);
    var _this = $(this);
    _this.data('backgroundBlink', true);
    _this.bind('mouseover.backgroundBlink', function(){
        _this.data('backgroundBlink', false);
        _this.stop(true,true).animate({
            backgroundColor: options.to
        }, 100);
        _this.unbind('mouseover.backgroundBlink');
    });
    function from(){
        if(!_this.data('backgroundBlink')){
            return;
        }
        _this.delay(options.delay).animate({
            backgroundColor: options.from
        }, options.speed, to);
    }
    function to(){
        if(!_this.data('backgroundBlink')){
            return;
        }
        _this.delay(options.delay).animate({
            backgroundColor: options.to
        }, options.speed, from);
    }
    from();
    return this;
} 
 
$.fn.iconStatus = function (options){
    var options = $.extend({
        count: 0,
        title: '',
        href: false
    },options);
    var _this = $(this);

    if(!eval(options.count)){
        _this.hide();
    }
    if(options.href){
        _this.bind('click', function(event){
            window.location = options.href;
            event.stopPropagation();
            return false;
        });
    }
    _this.attr('title', options.title.supplant({
        number:eval(options.count)
    }));
    _this.bind('updateStatus', function(){
        if(!parseInt(eval(options.count))){
            _this.hide();
        }
        else{
            _this.show();
        }
        _this.attr('title', options.title.supplant({
            number:eval(options.count)
        }));
    });
    return this;
}

$.fn.sortableSubList = function (options){
    var options = $.extend({
        copy: false,
        del: false,
        count: false
    },options);
    return this.each(function(i) {
        var _this = $(this);

        var _icon = $('<span class="icon9 icon9-minus" />');
        if(options.copy){
            _this[0].elcopy = false;
            $(window.document).bind('keydown.sortable-' + i, function(event){
                if (event.keyCode == 17){
                    _this[0].elcopy = true;
                    _icon.removeClass('icon9-minus').addClass('icon9-plus');
                    
                }
            }).bind('keyup.sortable-' + i, function(event){
                if (event.keyCode == 17){
                    _this[0].elcopy = false;
                    _icon.removeClass('icon9-plus').addClass('icon9-minus');
                }
            });
        }
        var _lis = $('li>ul>li',_this);

        var el_is = -1;
        var cancel = 0;
        var _sort = $('li>ul',_this);
        _sort.sortable({
            helper: 'clone',
            revert: 'invalid',
            connectWith: _sort,
            cancel: ':input,button,.disabled',
            items: 'li:not(.disabled)',
            opacity: 0.9,
            stop: function(event, ui) {
                if(!_this[0].elcopy && !ui.sender && !cancel){
                    ui.item.parents('li').addClass('updated');
                }else{
                    cancel = 0;
                }
            },
            receive: function(event, ui) {
                if(el_is >= 0){
                    $(ui.sender).sortable('cancel');
                    cancel = 1;
                    return;
                }
                if(_this[0].elcopy){
                    $(ui.sender).sortable('cancel');
                }else{ 
                    if(options.count){
                        ui.item.parents('li').find('.count').text(ui.item.parent().find('li').length);
                        ui.sender.parent().find('.count').text(ui.sender.find('li').length);            
                    }
                    ui.sender.parent().addClass('updated');
                    ui.item.parents('li').addClass('updated');
                }
            },
            sort: function(event, ui) {
                if(_this[0].elcopy){
                    var arr = [];
                    ui.placeholder.parent().find('li:not(.ui-sortable-placeholder)').each(function(i){
                        arr[i] = $(this).text();
                    });
                    el_is = $.inArray(ui.item.text(), arr);
                }
            },
            over: function(event, ui) {
                var arr = [];
                ui.placeholder.parent().find('li:not(.ui-sortable-placeholder)').each(function(i){
                    arr[i] = $(this).text();
                });
                el_is = $.inArray(ui.item.text(), arr);
            },
            beforeStop: function(event, ui) {
                if(_this[0].elcopy && el_is == -1){
                    var clone = ui.item.clone();
                    ui.placeholder.after(clone);
                    var li = ui.placeholder.parents('li');
                    li.addClass('updated');
                    if(options.count){
                        var cnt = li.find('.count');
                        cnt.text(parseInt(cnt.text()) + 1)
                    }
                }
            },
            start: function(event, ui){
                ui.helper.prepend(_icon);
            }
        });

        if(options.del){
            var _icon_del = $('<span class="icon9 icon9-delete" />')
            _lis.prepend(_icon_del);
            _this.bind('click', function(event){
                var el = $(event.target);
                if(el.is('.icon9-delete')){
                    var _li = el.parent().parent().parent();
                    _li.addClass('updated');
                    if(options.count){
                        var cnt = _li.find('.count');
                        cnt.text(parseInt(cnt.text()) - 1)
                    }
                    el.parent().remove();
                }
            });
        }

        ('ul, li', _this).disableSelection();

    });
}

$.fn.checkNewRows = function (options){
    var options = $.extend({
        newRows: 'new',
        checkEl: '.check',
        action: null
    },options);
    var _this = $(this);
    _this.bind('click', function(event){
        var el = $(event.target);
        if(el.parent().is('tr.' + options.newRows) && !el.is(':checkbox')){
            var _tr = el.parents('tr.' + options.newRows);
            _tr.removeClass(options.newRows);
            if($.isFunction(options.action)){
                var id = _tr.find(options.checkEl).val();
                options.action(id);
            }
        }
    })
    return _this;
}
$.fn.showSubRows = function (options){
    var _this = $(this);
    _this.bind('click.selectRows', function(event){
        var el = $(event.target);

        if(el.parent().is('tr:first-child') && !el.is(':checkbox')){
            var _current = el.parents('tr');
            if(_current.is('.show')){
                _current.removeClass('show');
                _current.next('tr').hide();
            }else{
                $('tbody tr:first-child', _this).removeClass('show').next('tr').hide();
                _current.addClass('show');
                _current.next('tr').show();
            }
            
        }
    });
    return _this;
}

$.fn.selectRows = function (options){
    var options = $.extend({
        selectedEl: 'tr',
        checkAllEl: '.checkAll',
        checkEl: '.check'
    },options);
    var _this = $(this),
    _check_all_el = $(options.checkAllEl, _this),
    _check_el = $(options.checkEl, _this);
    _this.bind('click.selectRows', function(event){
        
        var el = $(event.target);
        if(el.is(options.checkAllEl)){
            _check_el.attr('checked', el.is(':checked') ? 'checked' : '');
            if(el.is(':checked')){
                _check_el.parents(options.selectedEl).addClass('selected');
            }
            else{
                _check_el.parents(options.selectedEl).removeClass('selected');
            }
        }
        if(el.is(options.checkEl)){
            _check_all_el.attr('checked', $(options.checkEl + ':checked', _this).length == _check_el.length  ? 'checked' : '');
            if(el.is(':checked')){
                el.parents(options.selectedEl).addClass('selected');
            }
            else{
                el.parents(options.selectedEl).removeClass('selected');
            }
        }
        
    });
    return _this;
}
$.fn.bounds = function (){
    var bounds = {
        left: Number.POSITIVE_INFINITY, 
        top: Number.POSITIVE_INFINITY,
        right: Number.NEGATIVE_INFINITY, 
        bottom: Number.NEGATIVE_INFINITY
    };
    this.each(function (i,el) {
        var elQ = $(el);
        var off = elQ.offset();
        off.right = off.left + $(elQ).width();
        off.bottom = off.top + $(elQ).height();
        if (off.left < bounds.left){
            bounds.left = off.left;
        }
        if (off.top < bounds.top){
            bounds.top = off.top;
        }
        if (off.right > bounds.right){
            bounds.right = off.right;
        }
        if (off.bottom > bounds.bottom){
            bounds.bottom = off.bottom;
        }
    });
    return bounds;
}
$.fn.boundsBacklight = function (options){
    var options = $.extend({
        opacity: 0.85,
        hideAction: null,
        zIndex: 9999
    },options);
    var _this = $(this);
    if(_this.length){
        var _top = $('<div class="boundsBacklight" />'),
        _left = $('<div class="boundsBacklight" />'),
        _right = $('<div class="boundsBacklight" />'),
        _bottom = $('<div class="boundsBacklight" />');
        _this[0].bounds_backlight = false;
        function hideBoundsBacklight(){
            _top.remove();
            _left.remove();
            _right.remove();
            _bottom.remove();
            $(window).unbind('resize.boundsBacklight');
            if(typeof options.hideAction == 'function'){
                options.hideAction();
            }
            _this[0].bounds_backlight = false;
        }
        function sizes(){
            var el_height = _this.height(),
            body_width = $(document.body).width(),
            bounds = _this.bounds();
            _top.css({
                'top': 0,
                'left': 0,
                'width': body_width,
                'height': bounds.top,
                'opacity': options.opacity,
                'z-index': options.zIndex
            });
            _left.css({
                'top': bounds.top,
                'left': 0,
                'width': bounds.left,
                'height': el_height,
                'opacity': options.opacity,
                'z-index': options.zIndex
            });
            _right.css({
                'top': bounds.top,
                'left': bounds.right,
                'width': body_width - bounds.right,
                'height': el_height,
                'opacity': options.opacity,
                'z-index': options.zIndex
            });
            _bottom.css({
                'top': bounds.bottom,
                'left': 0,
                'width': body_width,
                'height': $(document).height() - bounds.top - el_height,
                'opacity': options.opacity,
                'z-index': options.zIndex
            });
        }
        function showBoundsBacklight(){
            sizes();
            $('body').append(_top, _left, _right, _bottom);
            $(window).bind('resize.boundsBacklight', sizes);
            _top.bind('click', hideBoundsBacklight);
            _left.bind('click', hideBoundsBacklight);
            _right.bind('click', hideBoundsBacklight);
            _bottom.bind('click', hideBoundsBacklight);
            _this[0].bounds_backlight = true;
        }
        _this.live('showBoundsBacklight', function(){
            showBoundsBacklight();
        });
        _this.live('hideBoundsBacklight', function(){
            hideBoundsBacklight();
        });
        _this.live('toggleBoundsBacklight', function(){
            if(_this[0].bounds_backlight){
                hideBoundsBacklight();
            }else{
                showBoundsBacklight();
            }
        });
    }
}
 
$.fn.paypalButton = function(options){
    var options = $.extend({
        height: 21
    },options);
    
    var _box = $(this);
    if(_box.length){
        _box.addClass('paypalButton').attr('title', 'PayPal - The safer, easier way to pay online!').text('donate').bind('click', function(event){
            var _form = $('<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"><div><input type="hidden" name="cmd" value="_donations"/><input type="hidden" name="business" value="' + options.email + '"/><input type="hidden" name="lc" value="US"/><input type="hidden" name="item_name" value="Donation to ' + options.user + '"/><input type="hidden" name="currency_code" value="USD"/><input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest"/></div></form>');
            _form.appendTo(_box);
            _form.submit();
            _form.remove();
        });
    }
    
}
$.fn.fbLikeButton = function(options){
    var options = $.extend({
        height: 21,
        width: 150,
        siteName: 'Openfilm.com',
        title: false,
        image: false
    },options);

    var _box = $(this);
    if(_box.length){
        if(options.siteName != ''){
            $('<meta property="og:site_name" content="' + options.siteName + '"/>').appendTo('head');
        }
        if(options.title && options.title != ''){
            $('<meta property="og:title" content="' + options.title + '"/>').appendTo('head');
        }
        if(options.image && options.image != ''){
            $('<meta property="og:image" content="' + options.image + '"/>').appendTo('head');
        }
        var iframe = $('<iframe src="http://www.facebook.com/plugins/like.php?href=' + encodeURI(window.location.href) + '&amp;layout=button_count&amp;show_faces=false&amp;width=' + options.width + '&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=' + options.height + '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' + options.width + 'px; height:' + options.height + 'px;" allowTransparency="true" />');
    
        _box.append(iframe);
    }
}
$.fn.twitterLikeButton = function(options){
    var options = $.extend({
        data_count: 'none',
        data_via: 'openfilm'
    },options);

    var _box = $(this);
    if(_box.length){
        var likeBlock = $('<a href="http://twitter.com/share" class="twitter-share-button" data-count="' + options.data_count + '" data-via="' + options.data_via + '">Tweet</a>');
        _box.append(likeBlock);
    }
}
$.fn.addThisBox = function(options){
    var options = $.extend({
        svcs: {
            twitter: '',
            facebook: '',
            separator: '|',
            expanded: i18n.m462 + '&#8230;'
        },
        styleClass: 'addthis_toolbox addthis_default_style',
        info: {},
        settings: {}
    },options);
    
    var _box = $(this);
    if(_box.length){
        var str = '';
        for (var s in options.svcs) {
            if(s == 'separator'){
                str += '<span class="addthis_separator">'+options.svcs[s]+'</span>';
                continue;
            }
            str += '<a class="addthis_button_'+s+'">'+options.svcs[s]+'</a>';
        }
        _box.append(str).addClass(options.styleClass);
    }
    addthis.toolbox(_box.selector, options.settings, options.info);
}
$.captchaDialog = function(options){
    var options = $.extend({
        action: false
    },options);

    var captchaForm = $(templates.captchaForm());

    var validator_captcha;

    $.modalDialog({
        content: captchaForm,
        onComplete: function(){
            $('#captcha_field', captchaForm).focus();
            validator_captcha = captchaForm.validate(formActions.captchaForm);
            formActions.captchaForm.captchaAction = options.action;
            captchaForm.submitAjaxIndikator();
            actions.captchaLoad(captchaForm, validator_captcha);
        
            $('a[href$="#captcha_reload"]', captchaForm).unbind().bind('click',
                function(event){
                    event.preventDefault();
                    //$('#captcha_string', captchaForm).attr('src', '/captcha/' + actions.captchaLoad() + '.png');
                    actions.captchaLoad(captchaForm, validator_captcha);
                });

            $('.buttonClose', captchaForm).unbind().bind('click', function(){
                $.fn.colorbox.close();
            });
        },
        onCleanup: function(){
            validator_captcha.resetForm();
        },
        title: i18n.m358
    });
}
    
$.modalDialog = function(options){
    var options = $.extend({
        width: false,
        height: false,
        content: '',
        onComplete: false,
        onCleanup: false,
        title: false,
        opacity: 0.85
    },options);
    if(options.title){
        options.title = '<h3>' + options.title + '</h3>';
    }
    $.fn.colorbox({
        width: options.width,
        height: options.height,
        inline:true,
        href: options.content,
        onComplete: options.onComplete,
        onCleanup: options.onCleanup,
        speed: 100,
        title: options.title,
        scrolling: false,
        opacity: options.opacity
    });
}   

$.fn.groupChexboxLimiter = function(options){
    var options = $.extend({
        limit: 3
    },options);
    var group = $(this);
    group[0].items = [];
    $(':checked',group).each(function(i){
        //if( i >= options.limit) return;        
        group[0].items.push($(this));
    });
    group.bind('change', function(event){
        var _this = $(this),
        el = $(event.target);
        if(el.is(':checkbox')){
            if(el.is(':checked')){
                if(group[0].items.length >= options.limit){
                    var old = group[0].items.shift();
                    if(old){
                        old[0].checked = false;
                    }
                }
                group[0].items.push(el);
            }else{
                group[0].items.pop();
            }
        }
    });
    return this;
}

$.fn.radioTab = function(options){
    var options = $.extend({
        items: null,
        form: null
    },options);
    var group = $(this),
    radio = $(':radio',group);
    if(radio.length && $.isArray(options.items)){
        group.bind('change', function(event, fast){
            var _this = $(this),
            el = $(event.target);
            
            if(el.is(':radio') || !el.is(':checked')){
                var selectors = [];
                for(var i=0, c=options.items.length; i<c; ++i){
                    selectors[i] = options.items[i].join(',')
                }
                $(selectors.join(','), options.form).hide();
                var ch = 0;
                $(':radio',_this).filter(function(index){
                    if($(this).is(':checked')){
                        ch = index;
                    }
                });
                var show = options.items[ch].join(',');
                if(fast){
                    $(show, options.form).show();
                }else{
                    $(show, options.form).fadeIn();
                }
            }
        });
        $(':radio:checked',group).trigger('change',true);
    }
    
    return this;
}

$.fn.stylizedInputFile = function(options){
    var options = $.extend({
        styleClass: false,
        buttonTitle: i18n.m347
    },options);
    
    var _this = $(this);
    _this.wrap('<span class="fileButton button"></span>');
    var _fileButton = _this.parent('.fileButton'),
    _fileText = $('<span class="fileText"></span>').attr('title',_this.val()).text(utils.fileName(_this.val()));

    _this.addClass('fileInput').css({
        opacity: 0
    })/*.width('auto')*/.show();
    
    _fileButton.prepend('<span>' + options.buttonTitle + '</span>');
    _fileButton.wrap('<span class="inputFile ' + (options.styleClass ? options.styleClass : '') + '"></span>');
    _fileButton.after(_fileText);
    
    _this.bind('change', function(){
        var _this = $(this),
        _fileText = _this.parent('.fileButton').next('.fileText');
        _fileText.attr('title',_this.val()).text(utils.fileName(_this.val()));
        
    });
    return this;
}

$.fn.submitAjaxIndikator = function(options){
    var options = $.extend({
        eq: 0,
        ns: false,
        styleClass: 'loaderBW'
    },options);
    
    var _this = $(this),
    _submit = $('[type="submit"]',_this).eq(options.eq),
    _reset = $('a[href="#form_reset"]',_this);
    if(_submit.length){
        var ns = options.ns ? '.s-' + options.eq : ''
        _this.bind('submitAjaxIndikatorShow' + ns, function(){
            _submit.addClass(options.styleClass).attr('disabled','disabled');
            if(_reset.length){
                _reset.hide();
            }
        });
        _this.bind('submitAjaxIndikatorHide' + ns, function(){
            _submit.removeClass(options.styleClass).removeAttr('disabled');
            if(_reset.length){
                _reset.show();
            }
        });
        _this.bind('submitDisable' + ns, function(){
            _submit.attr('disabled','disabled');
        });
        _this.bind('submitEnable' + ns, function(){
            _submit.removeAttr('disabled');
        });
    }
}
$.fn.rotateIconSubMenu = function(options){
    var options = $.extend({
        items: null,
        current: 0,
        speed: 5000,
        delay: 10000,
        styleClass: 'icon',
        rotate: false,
        store: false,
        title: '&#160;'
    },options);
    if(options.items.length){
        var _this = $(this),
        _ul = $('<ul></ul>'),
        _li = null,
        _id = _this.attr('id');
        _this[0].interval = null;
        _this.append($('<a>' + options.title + '</a>').append('<span class="' + options.styleClass + '"></span>'));
        for(var i=0, c = options.items.length; i<c; i++){
            _li = $('<li><a class="' + options.items[i].id + '" href="' + options.items[i].href + '">' + options.items[i].title + '</a></li>').appendTo(_ul);
            if($.isFunction(options.items[i].action)){
                $('>a',_li).bind('click.action',options.items[i].action);
                if(options.store && _id){
                    $('>a',_li).bind('click.store',function(){
                        store.set(_id,$(this).parent().index());
                    })
                }

            }
            $('>a',_li).bind('mouseenter',function(){
                _this.trigger('changeitem', {
                    'index': $(this).parent().index()
                });
            });
        }
        _this.append($('<div></div>').append(_ul));
        _this.bind('changeitem',function(event,item){
            var _this = $(this),
            _items = options.items;
            if(item.index >=0 && item.index < _items.length){
                var _link = $('>a',_this),
                _icon = $('.' + options.styleClass,_link),
                _lis = $('>div>ul>li',this);
                _link.attr('href',_items[item.index].href);
                if($.isFunction(_items[item.index].action)){
                    _link.unbind().bind('click',/*_items[item.index].action*/function(event){
                        event.preventDefault();
                        $('>a',_lis[item.index]).trigger('click');
                    });
                }
                if(item.fx){
                    _icon.animate({
                        'opacity': 0
                    },function(){
                        $(this).removeAttr('class').addClass(options.styleClass + ' ' + options.styleClass + '-' + _items[item.index].id).animate({
                            'opacity': 1
                        });
                    });
                }else{
                    _icon.removeAttr('class').addClass(options.styleClass + ' ' + options.styleClass + '-' + _items[item.index].id);
                }
                _lis.removeClass('current');
                _lis.eq(item.index).addClass('current');
                _this[0].current = item.index;
            }
        }).bind('rotate',function(){
            var _this = $(this);
            _this[0].interval = setInterval(function(){
                var _next = $('>div>ul>li',_this).eq(_this[0].current).next().index();
                _this.trigger('changeitem', {
                    'index': _next == -1 ? 0 : _next,
                    'fx': true
                });
            },options.speed);
        }).bind('mouseover',function(){
        
            clearInterval($(this)[0].interval);
            $(this)[0].interval = 'stop';
        });       
        _this.trigger('changeitem', {
            'index': options.current
        });
        if(options.rotate){
            setTimeout(function(){
                if(_this[0].interval != 'stop'){
                    _this.trigger('rotate');
                }
            },options.delay);
        }
    }
    return this;
}
/**
 * charging [R] 27.04.2010
 * 
 * The method create charging animateded box.
 * Applies to the container.
 * 
 */
$.fn.charging = function(options){
    var options = $.extend({
        items: null,
        current: false,
        speed: 800,
        action: null
    },options);
    var _this = $(this);
    
    if($.isArray(options.items)){
        var _track = $('<div class="track"><div class="left"></div><div class="right"></div><div class="center"></div></div>'),
        _segments = $('<ul></ul>'),
        _labels = $('<ul></ul>'),
        its = '';
        for(var i=0, c=options.items.length; i<c; ++i){
            its += '<li style="width:' + options.items[i].width + ';"><a href="' + (options.items[i].href ? options.items[i].href : '#') + '">' + options.items[i].label + '</a></li>';
        }
        _segments.append(its).addClass('segments');
        _labels.append(its).addClass('labels');

        _labels.bind('click',function(event){
            event.preventDefault();
            var el = $(event.target);
            if(el.is('a') && !el.parent().is('.current')){
                var href = el.attr('href'),
                text = el.text(),
                index = el.parent().index();
                if(typeof options.action == 'function'){
                    options.action(href,text,index,this);
                }
            }
            return false;
        });

        _this.append(_track,_segments,_labels);
        _this.bind('position',function(event, current){
            var _this = $(this),
            _track = $('.track',_this),
            _its = $('.segments > li',_this),
            _itsl = $('.labels > li',_this);
            if(current >= 0 && current <= _its.length){
                var _current = _its.eq(current),
                _currentl = _itsl.eq(current);
                _itsl.removeClass('current');
                _currentl.addClass('current');
                _track.stop().animate({
                    'width': _current.position().left + _current.width() + 30
                },options.speed,'easeOutQuad');
            }
        });
        var _its = $('>li',_segments);
        if(options.current !== false && options.current >= 0 && options.current <= _its.length){
            _this.trigger('position',options.current);
        }
    }
    return this;
}
/**
 * remainingCharacterCount [R] 2.04.2010
 * 
 * The method finds the container and generates in him the remaining number of characters to input.
 * Applies to the <textarea>.
 * 
 */
$.fn.remainingCharacterCount = function(options){
    var options = $.extend({
        characterCount: 1000,                     // Maximum number of characters.
        characterCountSelector: '.characterCount' // Container insert.
    },options);
    this.bind('keyup',function(event){
        $(this).trigger('recalcCharacterCount');
    })
    .bind('recalcCharacterCount',function(event){
        var _this = $(this),
        _count_box = _this.parents('form').find(options.characterCountSelector),
        t = options.characterCount - $.trim(_this.val()).length;
        _count_box.text(t); 
    });
    return this;
}

/**
 * dropDownMenu [R] 2.04.2010
 * 
 * The method creates a drop-down menu.
 * Applies to the <ul>.
 * 
 */
$.fn.dropDownMenu = function(options){
    var options = $.extend({
        fx: 'slide', // Effect - slide || fade. 
        speed: 300   // Speed
    },options);
    if(($.browser.msie && parseInt($.browser.version) <= 7) || $.browser.opera){
        options.fx = 'fade';
    }
    var intervals = {
        removeHover: null,
        showDrop: null
    };
    $('>li',this).bind('mouseover',function(event){
        var el = $(event.target),
        li = el.parent(),
        lis = li.parent().find('>li');
        if(el.is('a') && !li.is('.drop')){
            clearTimeout(intervals.removeHover);
            clearTimeout(intervals.showDrop);
            lis.removeClass('drop iconRight-drop current-drop').find('div').stop(true,true).slideUp(0);
            var _div  = $('>div',li);
            if(_div.length){
                intervals.showDrop = setTimeout(function(){
                    li.addClass('drop');
                    if(li.is('.current')){
                        li.addClass('current-drop');
                    }
                    if(li.is('.iconRight')){
                        li.addClass('iconRight-drop');
                    }
                    _div.css({
                        'min-height':'10px'
                    });
                    switch(options.fx){
                        case 'fade':
                            _div.fadeIn(options.speed);
                            break;
                        default:
                            _div.slideDown(options.speed,'easeOutCirc');
                    }
                }, 100);
            }
        }
        else if(el.is('li') && !el.is('.drop')){
            clearTimeout(intervals.removeHover);
            clearTimeout(intervals.showDrop);
            intervals.removeHover = setTimeout(function(){
                lis.removeClass('drop iconRight-drop current-drop').find('div').stop(true,true).slideUp(0);
            }, 500);
        }
    });
    this.bind('mouseleave',function(event){
        $('>li',this).removeClass('drop iconRight-drop current-drop').find('div').stop(true,true).slideUp(0);
        clearTimeout(intervals.removeHover);
        clearTimeout(intervals.showDrop);
    });
}
/**
 * collapceMenu [R] 2.04.2010
 * 
 * The method creates a collapce menu.
 * Applies to the <ul>.
 * 
 */
$.fn.collapceMenu = function(options){
    var options = $.extend({
        toggleButton: false,
        expandCurrent: false,
        header: false,
        store: false
    },options);

    return this.each(function() {
        var _ul = $(this),
        _id = _ul.attr('id');
            
        _ul[0].open_items = [];
        if(options.store && _id){
            store.get(_id,function(ok, val) {
                _ul[0].open_items = val ? val.split(',') : [];
            });    
        }
        var _button = $('<span class="icon16 icon16-expand" title="' + i18n.m215 + '" />');
        var _li = $('>li',_ul);
        _li.prepend(_button);
        _li.filter(function(index){
            return $('>ul', this).length < 1;
        }).find('span.icon16:first-child').addClass('icon16-spacer').attr('title', '');
        if(options.expandCurrent){
            $('>li:not(.current)>ul',_ul).hide();
        }else{
            $('>li>ul',_ul).hide();
        }
        if(_ul[0].open_items.length){
            $('>li:eq(' + _ul[0].open_items.join(')>ul,>li:eq(') + ')>ul',_ul)
            .show().parent()
            .find('>.icon16').toggleClass('icon16-expand icon16-collapse').attr('title', i18n.m213);
        }
        $('>li.current>.icon16',_ul).removeClass('icon16-expand').addClass('icon16-collapse');
        if(options.toggleButton){
            _buttonAll = $('<span class="buttonCM"></span>');
            _buttonAll.bind({
                'view.cm':function(){
                    var _this = $(this),
                    _ul = _this.next('ul'),
                    _li = $('>li',_ul);
                    if(_li.length <= _ul[0].open_items.length){
                        _this.html('<span class="icon16 icon16-collapseAll" /><span class="label">' + i18n.m212 + '</span>');
                    }
                    else{
                        _this.html('<span class="icon16 icon16-expandAll" /><span class="label">' + i18n.m214 + '</span>');
                    }
                },
                'click':function(){
                    var _this = $(this),
                    _ico = $('.icon16',_this),
                    _ul = _this.next('ul'),
                    _buttons = $('>li>.icon16',_ul);
                    if(_ico.is('.icon16-expandAll')){
                        _buttons.removeClass('icon16-collapse').addClass('icon16-expand');
                    }else if(_ico.is('.icon16-collapseAll')){
                        _buttons.removeClass('icon16-expand').addClass('icon16-collapse');
                    }
                    _buttons.trigger('click');
                    $(this).trigger('view.cm');
                }
            });
            _ul.before(_buttonAll);
            _buttonAll.trigger('view.cm');
        }
        
        var _icon = $('>li>.icon16:first-child',_ul);
        
        _icon.bind('click',function(){
            var _this = $(this),
            _ul = _this.parents('ul'),
            li = _this.parent(),
            index = li.index();
            li.find('>ul').stop(true,true);
            if(_this.is('.icon16-expand')){
                //li.find('>ul').slideDown('fast');
                $('.icon16', li).not('.icon16-spacer').parent().find('>ul').slideDown('fast', function(){
                    _this.attr('title', i18n.m213);
                });
                _ul[0].open_items.push(index);
            }else if(_this.is('.icon16-collapse')){
                //li.find('>ul').slideUp('fast');
                $('.icon16', li).not('.icon16-spacer').parent().find('>ul').slideUp('fast', function(){
                    _this.attr('title', i18n.m215);
                });
                for(var t = [], k = _ul[0].open_items.length; k--;){
                    if(_ul[0].open_items[k] != index){
                        t.push(_ul[0].open_items[k]);
                    }
                }
                _ul[0].open_items = t;
            }
            _ul[0].open_items = _ul[0].open_items.unique();
            _this.toggleClass('icon16-expand icon16-collapse');
            if(options.store && _id){
                store.set(_id,_ul[0].open_items.join(','));
            }
            if(options.toggleButton){
                _ul.prev('.buttonCM').trigger('view.cm');
            }
        });
        if(options.header){
            _icon.next('.header').bind('click', function(event){
                event.preventDefault();
                $(this).prev().trigger('click');
            });
        }
    });
}
Array.prototype.unique = function() {
    var a = [], i, l = this.length;
    for( i=0; i<l; i++ ) {
        if( !a.in_array(this[i]))  {
            a.push( this[i] );
        }
    }
    return a;
};

Array.prototype.in_array =  function(needle) {
    var key = '';
    for (key in this) {
        if (this[key] == needle) {
            return true;
        }
    }
    return false;
}


/**
 * dropDownMenuItemScroll [R] 2.04.2010
 * 
 * The method creates a scroll area for drop-down menu items.
 * Applies to the <ul>.
 * 
 */
$.fn.dropDownMenuItemScroll = function(options){
    var options = $.extend({
        items: false, //{items:{0:{width:120,height:250},2:{width:100,height:150}}}
        jScrollPane: {
            showArrows:false,
            arrowSize:0,
            scrollbarWidth:3,
            dragMinHeight:10
        }
    },options);
    var _this = null,
    _items = options.items;
    for(var i in options.items){
        _this = $('>li',this).filter('.' + i).find('>div');
        if(_this.length){
            _this.bind('mousewheel',function(event){
                event.stopPropagation();
                return false;
            }).css({
                'display':'block'
            });
            _this.find('>ul').wrapInner('<p></p>');
            _this.find('>ul>p').css({
                'height':_items[i].height,
                'width':_items[i].width,
                'overflow':'auto'
            }).jScrollPane(options.jScrollPane);
            _this.css({
                'display':'none'
            });
        }
    }
    return this;
}
/**
 * thumbPanel [R] 2.04.2010
 * 
 * The method creates a buttons panel for thumb.
 * Applies to the thumb.
 * 
 */
$.fn.thumbPanel = function(options){
    var options = $.extend({
        stopRollImage: false,
        buttons: [
    /*{
                styleClass: 'icon16-info',
                title: 'Test',
                actions:{
                    click: function(event){
                        alert('info click')
                        event.stopPropagation();
                        return false;
                    },
                    mouseover: function(){
                        alert('info mouseover');
                    },
                    mouseout: function(){
                        alert('info mouseout');
                    }
                }
                }*/
    ]
    },options);
    this.bind('mouseenter', function(){
        var _this = $(this)
        _panel = $('.panel',_this);
        if(!_panel.length){
            _panel = $('<span class="panel"></span>');
            _this.append(_panel);
            if(options.stopRollImage){
                _panel.bind('mouseenter',function(event){
                    var _par = $(this).parent();
                    _par[0].enter = 0;
                    clearInterval($('img',_par)[0].interval);
                })
                .bind('mouseleave',function(event){
                    var _par = $(this).parent();
                    _par[0].enter = 1;
                    rollImages($('img',_par));
                });
            }
            if(options.buttons.length){
                for(var i = 0, k = options.buttons.length; i < k; ++i){
                    var _btn = $('<span class="icon16 ' + options.buttons[i].styleClass + '"></span>');
                    _panel.append(_btn);
                    _btn.attr('title', (options.buttons[i].title || ''));
                    if(options.buttons[i].actions){
                        for(var j in options.buttons[i].actions){
                            _btn.bind(j, options.buttons[i].actions[j]);
                        }
                    }
                }
            }
        }
        _panel.stop(true,true).fadeIn('normal');
    }).bind('mouseleave', function(){
        $('.panel',this).stop(true,true).fadeOut('normal');
    });
    return this;
}
/**
 * thumbLoadControl [R] 2.04.2010
 * 
 * The method controls the download of pictures for the thumb. In the absence of pictures, replaces the default.
 * Applies to the thumb.
 * 
 */
$.fn.thumbLoadControl = function(){
    return this.each(function() {
        var thumb = $(this);
        $('img',thumb).bind('error',function(){
            var _this = $(this);
            thumb.addClass('noImage');
            _this[0].bad_src = _this[0].src;
            _this[0].src = '/design/images/1px_t.gif';
        //console.log(thumb)
        });   
    });
}
/**
 * rollImages [R] 2.04.2010
 * 
 * Function rotates the image src.
 * 
 */
function rollImages(_img){
    var _a = _img.parent();
    function roll(){
        var t = _a[0]._img_obj.shift();
        _img[0].src = t.src;
        _a[0]._img_obj.push(t);
    }
    if(_a[0]._img_obj.length)
    {
        _img[0].interval = setInterval(roll, 500);
        _a[0]._img_obj.push(_a[0]._img_obj.shift());
    }
//roll();
}
/**
 * thumbRoll [R] 2.04.2010
 * 
 * The method rotates the image for the thumb.
 * Applies to the thumb.
 * 
 */
$.fn.thumbRoll = function(){
    function indicator(length){
        var str = '<span class="indicator">';
        for(var i=0; i < length; i++){
            str += '<span></span>'
        }
        str += '</span>';
        return str;
    }
    return this.each(function() {
        var _this = $(this);
        if(_this.attr('rel').length){

            _this.bind('mouseenter', function(){
                var _this = $(this),
                _img = $('img',_this);
                _this[0].enter = 1;
                clearInterval(_img[0].interval);
                switch(_this[0].state){
                    case 1:
                        $('.indicator',_this).stop(true,true).fadeIn('normal');
                        break;
                    case 2:
                        rollImages(_img);
                        break;
                    default:
                        var _images = _this.attr('rel').split(','),
                        _indc = $(indicator(_images.length));
                        _this.append(_indc);
                        _indc.stop(true,true).fadeIn('normal');
                        _this[0]._img_obj = [];
                        _this[0].state = 1;
                        var _src = _img.attr('src').replace(/(_)\d+(\.jpg)/, '$1{ID}$2');
                        
                        if(_img[0].bad_src){
                            _src = _img[0].bad_src.replace(/(_)\d+(\.jpg)/, '$1{ID}$2');
                        }
                        var _height = _img.attr('height'),
                        _width = _img.attr('width');
                        _this[0].num = 0;
                        for(var i = 0, k = _images.length; i < k; ++i){
                            _this[0]._img_obj[i] = new Image(_width, _height);
                            _this[0]._img_obj[i].onerror = function(){
                                _this[0].num++;
                                var t2 = [];
                                for(var i=0,j=0, l=_this[0]._img_obj.length; i<l; ++i){
                                    if(_this[0]._img_obj[i].src != this.src){
                                        t2[j] = _this[0]._img_obj[i];
                                        ++j;
                                    }
                                }
                                _this[0]._img_obj = t2;
                                if(_this[0].num == k){
                                    _this[0].state = 2;
                                    _indc.hide();
                                    if (_this[0].enter){
                                        rollImages(_img);
                                    }
                                }
                            }
                            _this[0]._img_obj[i].onload = function(){
                            
                                $('>span:eq(' + (_this[0].num++) + ')',_indc).addClass('done');
                                if(_this[0].num == k){
                                    _this[0].state = 2;
                                    _indc.hide();
                                    if (_this[0].enter){
                                        rollImages(_img);
                                    }
                                }
                            }
                            //_this[0]._img_obj[i].src = _src.replace(/(i)\d*(.+){ID}/, '$1' + (i%8) + '$2' + _images[i]);
                            _this[0]._img_obj[i].src = _src.replace(/{ID}/, _images[i]);
                        }
                }
            }).bind('mouseleave', function(){
                var _this = $(this);
                $('.indicator',_this).stop(true,true).fadeOut('normal');
                _this[0].enter = 0;
                clearInterval($('img',_this)[0].interval);
            });
        }
    });
}
/**
 * ajaxIndikator [R] 3.05.2010
 * 
 * Method creates and manage indicator data load.
 * Applies to the container.
 * 
 */
$.fn.ajaxIndikator = function(options){
    var options = $.extend({
        title: i18n.m56,
        styleClass: false,
        orientation: 'center',
        position: 'absolute',
        backlight: true,
        opacity: 0.75,
        offset: 30
    },options);
    var _body = $(document.body),
    _box = $(this),
    _window = $(window);
    _body[0].indicators = _body[0].indicators ? ++_body[0].indicators : 1;   
    if(options.backlight){   
        var backlight = $('<div id="aib_' + _body[0].indicators + '" class="ajaxIndicatorBacklight"></div>');
        _box.append(backlight);
        backlight.css({
            'opacity': options.opacity,
            'display': 'none',
            'z-index': '9997'
        });
        if($.browser.msie && parseInt($.browser.version) <= 6){
            backlight.css('height', _box.height() + 'px');
            backlight.css('width', _box.width() + 'px');
        }
    }
    var indicator = $('<div id="ai_' + _body[0].indicators + '" class="ajaxIndicator' + (options.styleClass ? ' ' + options.styleClass : '') + '">' + options.title + '</div>');
    _box.append(indicator);
    indicator.css({
        'position':options.position,
        'z-index':'9998'
    });
    var indicatorPos = function(){  
        indicator.stop(true,false);    
        var _box_ofs_top = _box.offset().top,
        _box_h = _box.height(),
        pos = _window.height()/2 + (_window.scrollTop() - _box_ofs_top),
        minPos = indicator.height()/2+options.offset,
        maxPos = _box_h-options.offset-indicator.height()/2;
        if(pos < minPos){
            pos = minPos;
        }
        else if (pos > maxPos){
            pos = maxPos;
        }
        indicator.animate({
            top: pos + 'px'
        },100);
    }
    
    if(typeof (options.orientation) == 'object'){
        if(options.orientation.left){
            indicator.css('left',options.orientation.left);
        }
        if(options.orientation.right){
            indicator.css('right',options.orientation.right);
        }
        if(options.orientation.top){
            indicator.css('top',options.orientation.top);
        }
        if(options.orientation.left){
            indicator.css('bottom',options.orientation.bottom);
        }

    }else{
        switch(options.orientation){
            case 'left top':
            case 'top left':
                indicator.css({
                    'top':'0',
                    'left':'0'
                });
                break;
            case 'center top':
            case 'top center':
                indicator.css({
                    'top':'0',
                    'left':'50%'
                });
                break;
            case 'right top':
            case 'top right':
                indicator.css({
                    'top':'0',
                    'right':'0'
                });
                break;
            case 'center left':
            case 'left center':
                indicator.css({
                    'top':'50%',
                    'left':'0'
                });
                break;
            case 'center right':
            case 'right center':
                indicator.css({
                    'top':'50%',
                    'right':'0'
                });
                break;
            case 'left bottom':
            case 'bottom left':
                indicator.css({
                    'bottom':'0',
                    'left':'0'
                });
                break;
            case 'center bottom':
            case 'bottom center':
                indicator.css({
                    'bottom':'0',
                    'left':'50%'
                });
                break;
            case 'right bottom':
            case 'bottom right':
                indicator.css({
                    'bottom':'0',
                    'right':'0'
                });
                break;
            case 'center scroll':
            case 'scroll center':
                indicator.css({
                    'top':'50%',
                    'left':'50%'
                });
                break;
            default:
                indicator.css({
                    'top':'50%',
                    'left':'50%'
                });
        }
    }
    indicator.hide();
    _box.bind('ajaxIndikatorShow',function(event){
        event.stopPropagation();
        
        if(typeof (options.orientation) != 'object'){
            switch(options.orientation){
                case 'center left':
                case 'left center':
                case 'center right':
                case 'right center':
                    indicator.css({
                        'margin-top':-indicator.outerHeight()/2
                    });
                    break;
                case 'top center':
                case 'center top':
                case 'center bottom':
                case 'bottom center':
                    indicator.css({
                        'margin-left':-indicator.outerWidth()/2
                    });
                    break;
                default:
                    indicator.css({
                        'margin-left':-indicator.outerWidth()/2,
                        'margin-top':-indicator.outerHeight()/2
                    });
            }
        }
        var title = options.title;

        if(arguments[1] && typeof arguments[1].title == 'string'){
            title = arguments[1].title;
            indicator.html(title);
        }           
        if(arguments[1] && typeof arguments[1].titleData == 'object'){
            indicator.html(title.supplant(arguments[1].titleData));
        }
        if(arguments[1] && arguments[1].lock == true){
            indicator.addClass('ajaxIndicatorLock').wrapInner('<div></div>').prepend('<span class="icon64 icon64-lock"></span>');
        }
        if(options.backlight){
            backlight.fadeIn('fast');
        }
        if(options.orientation == 'center scroll' || options.orientation == 'scroll center'){
            indicatorPos();
            _window.scroll(indicatorPos);
            _window.resize(indicatorPos);
        }
        if(arguments[1] && arguments[1].title == false){
            return;
        }
        //indicator.fadeIn('fast');
        indicator.css('display','block');
    });
    this.bind('ajaxIndikatorHide',function(){
        if(options.backlight){
            backlight.fadeOut('fast');
        }
        if(options.orientation == 'center scroll' || options.orientation == 'scroll center'){
            _window.unbind('scroll',indicatorPos);
            _window.unbind('resize',indicatorPos);
        }
        indicator.fadeOut('fast',function(){
            indicator.removeClass('ajaxIndicatorLock').html(options.title);
        });
        

    });
    return this;
}
/**
 * lastLIWidthCorrect [R] 6.04.2010
 * 
 * Method calculates and sets the width of the last element for the horizontal list.
 * Applies to the ul.
 * 
 */
$.fn.lastLIWidthCorrect = function(){
    var _this = $(this),
    all_width = 0,
    last = $('li:last-child',_this);
    $('>li',_this).each(function(){
        all_width += $(this).outerWidth();
    });
    last.width(_this.outerWidth() - all_width + last.width());
    return this;
}
/**
 * supplant [R] 6.04.2010
 * 
 * Templating.
 * Applies to the string.
 * 
 */
String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
        );
}
/**
 * blockClick [R] 6.04.2010
 * 
 * The method blocks booble click event and default actions.
 * Applies to the <a>.
 * 
 */
$.fn.blockClick = function(){
    this.bind('click',function(event){
        event.stopPropagation();
        return false;
    }); 
}
/**
 * tabsMenu [R] 6.04.2010
 * 
 * The method creates a Tabs menu.
 * Based on clickMenu.
 * Applies to the <ul>.
 * 
 */
$.fn.tabsMenu = function(options){
    var options = $.extend({
        current: 0,
        action: null,
        store: false,
        speed: 'fast',
        hash: false
    },options);
    var _this = $(this);
    var _tabs = _this.next('.tabs');
    $('.tab',_tabs).hide();
    var current = options.current;
    if(options.hash && $.isArray(options.hash)){
        var hash = window.location.hash.replace(/.*#/,'');
        var inar = $.inArray(hash, options.hash);
        if(inar != -1){
            current = inar;
        }
    }
    $('.tab',_tabs).eq(current).show();
    _this.clickMenu({
        current: current,
        store: options.store,
        action: function(){
            var href = arguments[0],
            text = arguments[1],
            index = arguments[2];    
            $('.tab:visible',_tabs).fadeOut(options.speed,function(){
                $('.tab',_tabs).eq(href.replace(/.*#/,'')).fadeIn(options.speed);
                if(options.hash && $.isArray(options.hash)){
                    if(options.hash[index]){
                        window.location.hash = options.hash[index];
                    }else{
                        window.location.hash = index;
                    }
                }
            });
            if(typeof options.action == 'function'){
                options.action(href,text,index,_this);
            }
        }
    });
    return this;
}
/**
 * clickMenu [R] 6.04.2010
 * 
 * The method creates a menu.
 * Applies to the <ul>.
 * 
 */
$.fn.clickMenu = function(options){

    var _this = $(this);

    if (!_this.length) {
        return this;
    }

    var options = $.extend({
        current: 0,
        action: null,
        store: false
    },options);

    _this[0].old_current = options.current;
    if(options.current !== false){
        $('li',_this).eq(options.current).addClass('current');
    }
    _this.bind('currentBack',function(){
        var _this = $(this);
        $('.current',_this).removeClass('current');
        $('li',_this).eq(_this[0].old_current).addClass('current');       
    })
    .bind('click',function(event){
        $(document.body).trigger('click');
        var _this = $(this),
        el = $(event.target);
        if(el.is('a') && el.attr('href') != '#' && !el.parent().is('.current')){
            var href = el.attr('href'),
            text = el.text(),
            _parent = el.parent(),
            index = _parent.index(),
            _current = $('.current',_this),
            _id = _this.attr('id');
            _this[0].old_current = _current.index();
            if(typeof options.action == 'function'){
                options.action(href,text,index,this);
            }
            _current.removeClass('current');
            _parent.addClass('current');
            if(options.store && _id){
                store.set(_id,href.replace(/.*#/,''));
            }
        }
        event.stopPropagation();
        return false;
    });
    return this;
}
/**
 * sortToggleMenu [R] 6.04.2010
 * 
 * The method creates a sorting menu.
 * Applies to the <ul>.
 * 
 */
$.fn.sortToggleMenu = function(options){
    var options = $.extend({
        current: 0,
        action: null
    },options);
    var _this = $(this);
    if(!_this.length){
        return false;
    }
    _this[0].old_current = options.current;
    if(options.current !== false){
        $('li',_this).eq(options.current).addClass('current');
    }
    _this.bind('currentBack',function(){
        var _this = $(this),
        _current = $('.current',_this);
        _current.removeClass('current');
        $('li', _this).eq(_this[0].old_current).addClass('current');
        if(_this[0].old_current == _current.index()){
            $('>a', _current).toggleClass('asc desc');
        }
    })
    .bind('click',function(event){
        var _this = $(this),
        _current = $('.current',_this),
        el = $(event.target),
        _parent = el.parent();
        if(el.is('a')){
            event.preventDefault();
            var href = el.attr('href'),
            text = el.text();
            _this[0].old_current = _current.index();
            if(_parent.is('.current')){
                el.toggleClass('asc desc');
            }
            var sort = el.attr('class');
            if(typeof options.action == 'function'){
                options.action(href,sort,text,this);
            }
            _current.removeClass('current');
            _parent.addClass('current');
        }
    });
    return this;
}
/**
 * toggleButton [R] 6.04.2010
 * 
 * The method creates a toggle button.
 * Applies to the <a>.
 * 
 */
$.fn.toggleButton = function(options){
    var options = $.extend({
        styleClass: false,
        labelFirst: 'firs',
        labelSecond: 'second',
        first: '#firs',
        second: '#second',
        tooltipFirst: false,
        tooltipSecond: false,
        action: null,
        actionSecond: null,
        state: 0,
        bodyClick: false,
        store: false,
        lockAction: null,
        prohibition: null
    },options);
    return this.each(function(){
        var _this = $(this);
        if(options.state == 0){
            _this.html(options.labelFirst).attr('href',options.first);
            if(options.tooltipFirst){
                _this.attr('title', options.tooltipFirst);
            }
        }else{
            _this.html(options.labelSecond).attr('href',options.second);
            if(options.tooltipSecond){
                _this.attr('title', options.tooltipSecond);
            }
        }
        if(options.styleClass){
            _this.addClass(options.styleClass);
        }
        if($.isFunction(options.lockAction)){
            _this.addClass('lock');
        }
        _this.bind('click', function(event){
            var _this = $(this);
            if($.isFunction(options.lockAction)){
                options.lockAction(event);
                return;
                
            }
            if ($.isFunction(options.prohibition)) {
                var prohib = options.prohibition(event, _this);
                if (!prohib){
                    return;
                }
            }
            if(options.bodyClick){
                $(document.body).trigger('click');
            }
            var href = _this.attr('href');
            if(href == options.first){
                _this.html(options.labelSecond).attr('href',options.second);
                if(options.tooltipSecond){
                    _this.attr('title', options.tooltipSecond);
                }
            }else{
                _this.html(options.labelFirst).attr('href',options.first);
                if(options.tooltipFirst){
                    _this.attr('title', options.tooltipFirst);
                }
                
            }
            var phref = _this.attr('href'),
            rel = _this.attr('rel'),
            html = _this.html();
                
                
            if(href == options.first || typeof options.actionSecond != 'function') {
                if(typeof options.action == 'function'){
                    options.action(href,phref,html,rel,_this);
                }
            } else if(typeof options.actionSecond == 'function'){
                options.actionSecond(href,phref,html,rel,_this);
            }

            
            var _id = _this.attr('id');
            if(options.store && _id){
                store.set(_id,href.replace(/.*#/,''));
            }
            event.stopPropagation();
            return false;
        });
    });
}
/**
 * carousel [R] 6.04.2010
 * 
 * The method creates a carousel list.
 * Applies to the container.
 * 
 */
$.fn.carousel = function(options){

    var _this = $(this),
    items = _this.children('.item').length,
    _pager = _this.parent().prev('.pagerTop'),
    _body = $('body'),
    _box = _this.parent().parent(),
    page_count = parseInt($('.pageCount', _pager).text()) || 1,
    current_page = $('li.current a', _pager).text() || 1,
    per_page = parseInt($('.perPage', _pager).text()) || items,
    item_width = _this.find('.item').outerWidth(true),
    clip_width = items*item_width;

        
    var options = $.extend({
        visible:3,
        scroll:3,
        speed: 600,
        index: _box.length ? _box[0].carousel_index : 0,
        controls: true
    },options);

    this.wrap('<div class="carousel"/>');
    var carousel = this.parent();
    this.wrap('<div class="carouselWrapper"/>');
    var carousel_clip = this.addClass('carouselClip');
    carousel_clip.width(clip_width).css({
        'position':'relative'
    });

    carousel.prepend('<span class="carouselPrev" /><span class="carouselNext" />');
    var prev_button = $('.carouselPrev',carousel).hide();
    var next_button = $('.carouselNext',carousel).hide();
    if(options.controls){
        prev_button.fadeIn('fast');
        next_button.fadeIn('fast');
    }
    if(current_page == 1 && !options.index){
        prev_button.addClass('carouselPrev-disabled');
    }
    if(page_count == current_page && items <= options.visible){
        //prev_button.addClass('carouselPrev-disabled');
        next_button.addClass('carouselNext-disabled');
    }
    var offset = 0;
    prev_button.bind('click',function(){
        if(offset){
            if(options.scroll > offset/item_width){
                offset-=item_width*(offset/item_width);
            }else{
                offset-=item_width*options.scroll;
            }
            carousel_clip.animate({
                'left': -offset
            },options.speed,'easeOutQuad');
            next_button.removeClass('carouselNext-disabled');
        }else if(current_page != 1){
            $('li.prev a', _pager).trigger('click');
            _box[0].carousel_index = per_page;
        }
        if(current_page == 1 && !offset){
            $(this).addClass('carouselPrev-disabled');
        }
    });
    next_button.bind('click',function(){
    
        if(offset < clip_width-options.visible*item_width){
            if(options.scroll > (clip_width-offset)/item_width-options.visible){
                offset+=item_width*((clip_width-offset)/item_width-options.visible);
            }else{
                offset+=item_width*options.scroll;
            }
            carousel_clip.animate({
                'left':-offset
            },options.speed,'easeOutQuad');
            prev_button.removeClass('carouselPrev-disabled');
        }else if(current_page < page_count){
            $('li.next a', _pager).trigger('click');
            _box[0].carousel_index = 0;
        }
        if(page_count == current_page && !((clip_width-offset)/item_width-options.visible) ){
            $(this).addClass('carouselNext-disabled');
            
        }
    });
    if(options.index){
        var tmp = options.scroll;
        options.scroll = options.index; 
        next_button.trigger('click');
        options.scroll = tmp;  
    }
    if(_box.length && _box[0].carousel_index > 0){
        _box[0].carousel_index = 0;
    }
    return this;
}
/**
 * moreTextShowHide [R] 6.04.2010
 * 
 * The method creates a more/less button.
 * Applies to the container.
 * 
 */
$.fn.moreTextShowHide = function(options){
    var options = $.extend({
        labelMore: i18n.m63,
        labelLess: i18n.m64
    },options);
    var _this = $(this),
    lab = '<span class="sep">... </span><span class="actionTextLink show">' + options.labelMore + '</span><span class="more">&#155;</span>';
    if(!_this.next().is('span.moreLabel')){
        _this.css('display','none')
        .after('<span class="moreLabel">' + lab + '</span>');
    }else{
        _this.next().html(lab);
    }
    _this.next().find('.actionTextLink')
    .bind('click', function(){
        var _this = $(this),
        _parent = _this.parent(),
        _box = _parent.prev();
        if(_this.is('.show')){
            if($.browser.msie){
                _box.css({
                    display:'inline',
                    zoom:'normal'
                });
            }            
            _box.fadeIn('fast');
            _this.removeClass('show').addClass('hide').html(options.labelLess);
            $('span.sep',_parent).html(' ');
            $('span.more',_parent).remove();
            _this.before('<span class="less">&#139;</span>')
        } else if(_this.is('.hide')){
            _this.empty();
            $('span.less',_parent).remove();
            _box.fadeOut('fast',function(){
                _this.removeClass('hide').addClass('show');
                _this.html(options.labelMore);
                $('span.sep',_parent).text('... ');
                _this.after('<span class="more">&#155;</span>');
            });
        }
    });
    return this;
}
/**
 * moreTextHide [R] 6.04.2010
 * 
 * The method hide more text.
 * Applies to the container.
 * 
 */
$.fn.moreTextHide = function(){
    var _this = $(this),
    _next = _this.next();
    _this.css('display','none');
    var sep = '<span class="sep">... </span>';
    if(_next.is('span.moreLabel')){
        _next.html(sep);
    }else{
        _this.after('<span class="moreLabel">' + sep + '</span>');   
    }
    return this;
}
/**
 * initVote [R] 6.04.2010
 * 
 * The method creates a simple voting.
 * Applies to the <a>.
 * 
 */
$.fn.initVote = function(options){
    var options = $.extend({
        action: null
    },options);
    return this.each(function() {
        var voteBox = $(this),
        voteValue = voteBox.text(),
        vote = null;
        if(!voteBox.next().is('.vote')){
            vote = voteBox.clone().attr('class','').addClass('vote').empty();
            voteBox.after(vote);
        }else{
            vote = voteBox.next();
            vote.empty();
        }
        voteBox.css('display','none');   
        if(vote.is('a') && typeof(options.action) == 'function'){
            vote.append('<span>+</span><i>' + voteValue + '</i><span>-</span>');
            vote.bind('click',function(event){
                var el = $(event.target).closest('span');
                if(el.length) { 
                    var vl = el.text() == '+' ? 1 : -1
                    options.action({
                        id: vote.attr('rel'),
                        href: vote.attr('href'),
                        vote: vl,
                        obj: vote,
                        value: voteValue
                    }, event);
                }
                event.stopPropagation();
                return false; 
            })
        }
    });    
}
/**
 * initStars [R] 6.04.2010
 * 
 * The method creates a stars voting.
 * Applies to the <a>.
 * 
 */
$.fn.initStars = function(options){
    var options = $.extend({
        action: null,
        lockAction: null
    },options);
    return this.each(function() {
        var rating = $(this),
        ratingValue = rating.text(),
        ratingClass = ratingValue.replace('\.','-'),
        stars = null;
        if(!rating.next().is('.stars')){
            stars = rating.clone().attr('class','').addClass('stars stars-' + ratingClass).empty();
            rating.after(stars);
        }else{
            stars = rating.next();
            stars.empty();
        }
        rating.css('display','none');
        if(rating.is('a') && typeof(options.action) == 'function'){
            for(var i=1,str=''; i <= 5; i++){
                str += '<span>' + i + '</span>';
            }
            stars.html(str).css('cursor', 'pointer');
            if($.isFunction(options.lockAction)){
                stars.addClass('lock');
            }
            $('span',stars).hover(function(event){
                var _this = $(this);
                _this.parent().toggleClass('stars-' + ratingClass + ' ' +'stars-' + _this.text());
            });
            stars.bind('click',function(event){
                if($.isFunction(options.lockAction)){
                    options.lockAction(event);
                    return;
                }
                var _this = $(this),
                el = $(event.target).closest('span'),
                ext = options.action({
                    id:_this.attr('rel'),
                    href:_this.attr('href'),
                    rating:el.text(),
                    status: !!el.length,
                    obj: stars
                });
                if(el.length) {             
                    if(ext){
                        _this.prev().text(el.text());
                        _this.empty();
                    }
                }
                event.stopPropagation();
                return false;                
            });  
        }
    });
    return this;
}
/**
 * cloneInfo [R] 7.04.2010
 * 
 * The method cloning the information, sorted in the correct order and creates a new list.
 * Applies to the container.
 * 
 */
$.fn.cloneInfo = function(options){
    var options = $.extend({
        header: true,
        description: true,
        items: false,
        wrapper: 'ul'
    },options);
    var _this = $(this),
    _box = $('<div></div>'),
    _ul = $(document.createElement(options.wrapper)),
    items = options.items;
    for(var i=0,k=items.length; i<k; ++i){
        _ul.append(_this.find('.' + items[i]).clone());
    }
    if(options.header){
        _box.append(_this.find('h3').clone().show());
    }
    if(items.length){
        _box.append(_ul);
    }
    if(options.description){
        _box.append(_this.find('.description').clone().show());
    }
    return _box;
}
/**
 * toggleNextBox [R] 7.04.2010
 * 
 * The method creates (show / hide) a box after the object on which the clicked.
 * Applies to the container.
 * 
 */ 
$.fn.toggleNextBox = function(options){
    var options = $.extend({
        selector: '',
        content: '',
        styleClass: false,
        slide: 'down',  /*right*/
        afterShow: false,
        afterHide: false
    },options);
    var id = '#toggle_box',
    _box = $(id),
    _this = $(this),
    _body = $(document.body)[0];
    if(_this.next(id).length){
        if(_this[0].show){
            if(options.slide == 'down'){
                _box.slideUp(300,options.afterHide,'easeInCirc');
            }else{
                _box.slideLineOut(300,options.afterHide,'easeInCirc');
            }
            _this[0].show = false;
        }else{
            if(options.slide == 'down'){
                if($.browser.msie && parseInt($.browser.version) == 8){
                    _box.show();
                }
                _box.slideDown(400,options.afterShow,'easeOutCirc');
            }else{
                _box.slideLineIn(400,options.afterShow,'easeOutCirc');
            }
            _this[0].show = true;
        }
    }else{   
        if(_box.attr('id')){
            if(_body.next_box_target[0].show){
                _body.next_box_target.trigger('click');
            }
            _box.remove();
        }
        var _box = $('<div></div>').append(options.content);
        _box.attr('id','toggle_box').attr('tabindex','1');
        _box.bind('mousewheel',function(event){
            return false;
        });
        _body.next_box_target = _this;
        if(options.styleClass){
            _box.addClass(options.styleClass);
        }
        _this.after(_box.hide());
        if(options.slide == 'down'){
            if($.browser.msie && parseInt($.browser.version) == 8){
                _box.show();
            }
            _box.slideDown(400,options.afterShow,'easeOutCirc');
        }else{
            _box.slideLineIn(400,options.afterShow,'easeOutCirc');
        }
        _this[0].show = true;
    }
}
$.fn.slideLineIn = function( speed, easing, callback ) {
    return this.animate( {
        width:'show',
        paddingLeft: 'show',
        paddingRight: 'show',
        marginLeft: 'show',
        marginRight: 'show'
    }, speed, easing, callback);
};
$.fn.slideLineOut = function( speed, easing, callback ) {
    return this.animate( {
        width:'hide',
        paddingLeft: 'hide',
        paddingRight: 'hide',
        marginLeft: 'hide',
        marginRight: 'hide'
    }, speed, easing, callback);
};
$.fn.slideLineToggle = function( speed, easing, callback ) {
    return this.animate( {
        width:'toggle',
        paddingLeft: 'toggle',
        paddingRight: 'toggle',
        marginLeft: 'toggle',
        marginRight: 'toggle'
    }, speed, easing, callback);
                
};

//
/**
 * stickBox [R] 17.05.2010
 * 
 * The method creates (show / hide) a box attached...
 * Applies to the container.
 * 
 */
$.fn.stickBox = function(options){
    var options = $.extend({
        content: '',
        orientation: '',
        styleClass: false,
        zIndex: 9999,
        afterShow: false,
        beforeRemove: false,
        speed: 'fast'
    },options);
    var _this = $(this);

    
    _this.bind('orientation', function(){
        var _this = $(this),
        _box = $('#stick_box'),
        offset = _this.offset(),
        ttop = offset.top,
        tleft = offset.left,
        twidth = _this.outerWidth(),
        theight = _this.outerHeight(),
        bwidth = _box.outerWidth(),
        bheight = _box.outerHeight();
        switch(options.orientation){
            //TODO: other orientation
            case 'right bottom':
            case 'bottom right':
                _box.css({
                    top: ttop + theight,
                    left: tleft - (bwidth - twidth)
                });
                break;
            case 'center bottom':
            case 'bottom center':
                _box.css({
                    top: ttop + theight,
                    left: tleft + twidth/2 - bwidth/2
                });
                break;
            default:
                _box.css({
                    top: ttop + theight,
                    left: tleft
                });
                
        }
    });
    _this.bind('stickBoxShow',function(){
        _button_close = $('<span title="' + i18n.m144 + '" class="buttonClose icon16 icon16-close" style="cursor: pointer;"/>'),
        _box_content = $('<div class="boxContent"></div>');
        if($('#stick_box').attr('id')){
            $('#stick_box').trigger('stickBoxHide');
        }
        var _box = $('<div></div>');
        _box.attr('id','stick_box');
        _box.bind('stickBoxHide', function(){
            _this.trigger('stickBoxHide');
        });
        _box[0].creator = _this;
        if(options.styleClass){
            _box.addClass(options.styleClass);
        }
        _box.append(_button_close);
        _button_close.bind('click', function(){
            _this.trigger('stickBoxHide');
        });
        
        _box_content.append(options.content)
        _box.append(_box_content);
        _box.hide();
        $(document.body).append(_box);

        _this.addClass('sticked');
        
        $(window).bind('resize.stick_box',function(){
            _this.trigger('orientation');
        });
        _this.trigger('orientation');
        _box.fadeIn(options.speed,function(){
            if($.isFunction(options.afterShow)){
                options.afterShow();
            } 
        });
    });
    _this.bind('stickBoxHide',function(){
        var _this = $(this);
        $(window).unbind('resize.stick_box');
        _this.removeClass('sticked');
        $('#stick_box').fadeOut(options.speed, function(){
            if($.isFunction(options.beforeRemove)){
                options.beforeRemove();
            }            
            $(this).remove();
        });
        _this.unbind('stickBoxHide').unbind('stickBoxShow');
    });
    
    //_this.trigger('stickBoxShow');

    return this;
}    

/**
 * targetBox [R] 7.04.2010
 * 
 * The method creates (show / hide) a box attached to the coordinates of the object on which the clicked.
 * Applies to the container.
 * 
 */
$.fn.targetBox = function(options){
    var options = $.extend({
        content: '',
        orientation: 'center',
        styleClass: false,
        zIndex: 9999
    },options);

    var removeTargetBox = function(){
        _box.trigger('targetBoxHide');
    }

    var _box = $('#target_box');
    if(!_box.attr('id')){
        _box = $('<div></div>');
        _box.attr('id','target_box');
        $(document.body).append(_box);
        $(document).bind('click',removeTargetBox);
        $(window).bind('resize',removeTargetBox);
    }
    if(options.styleClass){
        _box.attr('class','').addClass(options.styleClass);
    }
    _box.unbind();
    var target = $(this);
    _box.css({
        'display':'none',
        'z-index':options.zIndex
    });
    _box.bind('targetBoxShow',function(){        
        var offset = target.offset(),
        height = target.height(),
        width = target.width();
        _box.css({
            top:offset.top + height
        });
        if(options.orientation == 'right'){
            _box.css({
                left:offset.left - (_box.width() - height)
            }).addClass('targetBoxRight');
        }else if(options.orientation == 'left'){
            _box.css({
                left:offset.left
            }).addClass('targetBoxLeft');
        }else{
            _box.css({
                left:offset.left - (_box.width()/2 - width/2)
            }).addClass('targetBoxCenter');
        }
        var _button_close = $('<span title="' + i18n.m144 + '" class="buttonClose icon16 icon16-close" style="cursor: pointer;"/>'),
        _box_content = $('<div class="boxContent"></div>');
        _box.html(_button_close.add(_box_content.html(options.content)));
        _button_close.bind('click',function(){
            _box.trigger('targetBoxHide');
        });
        _box.fadeIn('fast');
    });
    _box.bind('targetBoxHide',function(){
        $(document).unbind('click',removeTargetBox);
        $(window).unbind('resize',removeTargetBox);
        if(_box[0].target){
            _box[0].target.flag = false;
        }
        _box.remove();
    });
    _box.bind('click',function(event){
        event.stopPropagation();
    });
    if(!target[0].flag){
        if(_box[0].target){
            _box[0].target.flag = false;
        }
        _box.trigger('targetBoxShow');
        _box[0].target = target[0];
        target[0].flag = true;
    }else{
        _box.trigger('targetBoxHide');
        target[0].flag = false;
    }
    return _box;
}


    
jQuery.extend({
    lineBoxPos: function(options){
        var options = $.extend({
            start: 0,
            orientation: 'top',
            dimension: 'height', /*width*/ 
            separator: 0,
            elements: false,
            selector: false,
            msieFilter: false
        },options);        
        
        if(options.elements && $.isPlainObject(options.elements)){
            var t = 0;
            var obj = null;
            for (var i in options.elements){
                obj = $(options.elements[i]);
                if(options.selector){
                    obj = $(options.selector, options.elements[i]);
                }
                obj.css(options.orientation, t + options.start);

                if(options.dimension == 'height'){
                    t += obj.height();
                }else{
                    t += obj.width();
                }
                if($.browser.msie && parseInt($.browser.version) <= 7 && options.msieFilter){   
                    
                    obj.css({
                        'height':'auto'
                    });
                    t += obj.height() - obj.width();
                    obj.css({
                        'height':0
                    });
                }
                t += options.separator;
            }
            return true;
        }
        return false;
    },
    slidePanel: function(options){
        var _body = $(document.body);
        _body[0].slide_panels = _body[0].slide_panels ? ++_body[0].slide_panels : 1;
        var options = $.extend({
            orientation: 'left', /* left | right | top | bottom */
            position: 'top', /* top | middle | bottom - for orientation left || right , left | center | right - for orientation top || bottom*/
            offset: 0,
            width: function(){
                return (options.orientation == 'left' || options.orientation == 'right') ? 300 : '100%';
            },
            height: function(){
                return (options.orientation == 'top' || options.orientation == 'bottom') ? 300 : '100%';
            },
            title: false,
            titleChange: false,
            titleHidden: false,
            content: '',
            contentFixed: false,
            heightAuto: false,
            topBar: false,
            bottomBar: false,
            zIndex: 1000,
            tabIndex: 100 + _body[0].slide_panels,
            styleClass: false,
            speed: 'normal',
            closeAll: true,
            buttonClose: true,
            jScrollPane: false
        },options);
        
        if($.browser.msie && parseInt($.browser.version) <= 6){
            return $(document);
        }               
        var id = 'slide_panel_' + _body[0].slide_panels,
        style = 'slidePanel slidePanel-' + options.orientation;
        
        if(!$(id).attr('id')){
            var _panel = $('<div id="' + id + '" class="'+ style + (options.styleClass ? ' '+options.styleClass : '') +'"></div>')
            .appendTo(_body)
            .css({
                'position':'fixed',
                'width': options.width,
                'height': options.height,
                'z-index': 9977
            });
            var _panel_height = _panel.height();
            var _title = $('<div class="slidePanelTitle"></div>')
            .html('<span class="title">' + options.title + '</span><span class="pointer"></span>')
            .css({
                'position':'absolute'
            })
            .appendTo(_panel);
            if(!options.title){
                _title.detach();
            }
            var _top_bar = $('<div class="slidePanelTopBar"></div>').html('<div class="block"></div>');
            $('.block',_top_bar).append(options.topBar).append(options.buttonClose ? '<span class="buttonClose icon16 icon16-close" title="' + i18n.m144 + '"></span>' : '');
            _top_bar.appendTo(_panel);
            if(!options.topBar){
                _top_bar.detach();
            }
            var _content = $('<div class="slidePanelContent"></div>')
            .css({
                'overflow':'auto'
            })
            .html('<div class="block"></div>');
            if(options.contentFixed){
                _content.css({
                    'overflow':'hidden'
                });
            }
            $('.block',_content).append(options.content);
            _content.appendTo(_panel);
            var _bottom_bar = $('<div class="slidePanelBottomBar"></div>')
            .html('<div class="block"></div>');
            $('.block',_bottom_bar).append(options.bottomBar);
            _bottom_bar.appendTo(_panel);
            if(!options.bottomBar){
                _bottom_bar.detach();
            }
            _content.css({
                'height':function(){
                    return _panel_height - (options.topBar ? _top_bar.height() : 0) - (options.bottomBar ? _bottom_bar.height() : 0);
                } 
            });
            if(options.jScrollPane){
                if(options.jScrollPane.scrollbarOnLeft){
                    _panel.addClass('scrollbarOnLeft');
                }
                _content.jScrollPane(options.jScrollPane);
            }
            if(!options.heightAuto){
                $(window).bind('resize.' + id + '_recalc',function(){
                   
                    var _panel_height = _panel.height(),
                    _top_bar = _panel.find('.slidePanelTopBar'),
                    _bottom_bar = _panel.find('.slidePanelBottomBar'),
                    _content = $('.slidePanelContent',_panel);
                    /*if(options.jScrollPane){
                        _content.jScrollPaneRemove();
                    }*/
                    _content.css('height',function(){
                        return _panel_height - _top_bar.height() - _bottom_bar.height();
                    });
                    if(options.jScrollPane){
                        _content.jScrollPane(options.jScrollPane);
                    }
                    
                });
            }
            switch(options.orientation){
                case 'right':
                    _panel.css({
                        'left':'auto',
                        'right':0
                    });
                    _title.css({
                        'left':-_title.width()
                    });
                    break;
                case 'top':
                    _panel.css({
                        'top':0,
                        'bottom':'auto'
                    });
                    _title.css({
                        'bottom':-_title.height()
                    });
                    break;
                case 'bottom':
                    _panel.css({
                        'top':'auto',
                        'bottom':0
                    });
                    _title.css({
                        'top':-_title.height()
                    });
                    break;
                default:
                    _panel.css({
                        'left':0,
                        'right':'auto'
                    });
                    _title.css({
                        'right': -_title.width()
                    });
            }
            if(options.orientation == 'left' || options.orientation == 'right'){
                switch(options.position){
                    case 'bottom':
                        _panel.css({
                            'bottom': 0 + options.offset,
                            'top': 'auto'
                        })
                        break;
                    case 'middle':
                        function middlePos(){
                            _panel.css({
                                'top': '50%',
                                'margin-top': -_panel.height()/2,
                                'bottom': 'auto'
                            });
                        }
                        middlePos();
                        $(window).resize(middlePos);
                        break;
                    default:
                        _panel.css({
                            'top': 0 + options.offset,
                            'bottom': 'auto'
                        });
                }
            }
            if(options.orientation == 'top' || options.orientation == 'bottom'){
                switch(options.position){
                    case 'right':
                        _panel.css({
                            'right': 0 + options.offset,
                            'left': 'auto'
                        })
                        break;
                    case 'center':
                        function centerPos(){
                            _panel.css({
                                'left': '50%',
                                'margin-left': -_panel.width()/2,
                                'right': 'auto'
                            });
                        }
                        centerPos();
                        $(window).resize(centerPos);
                        break;
                    default:
                        _panel.css({
                            'left': 0 + options.offset,
                            'right': 'auto'
                        });
                }
            }            
        }
        _panel.bind('hide',function(){
            var _this = $(this);
            _this.stop(true,true);
            switch(options.orientation){
                case 'right':
                    _this.css('right', -_this.width());
                    break;
                case 'top':
                    _this.css('top', -_this.height());
                    break;
                case 'bottom':
                    _this.css('bottom', -_this.height());
                    break;
                default:
                    _this.css('left', -_this.width());
            }
            _this.css('z-index',options.zIndex);
            _this.find('.slidePanelTitle').removeClass('current');
            if(options.titleHidden){
                $('.slidePanelTitle',_this).hide();
            }
            _this[0].show = false;
        }).bind('slideOut',function(){
            var _this = $(this);
            _this.stop(true,true);
            function aa(){
                _this.css('z-index',options.zIndex);
                $('.slidePanelTitle',_this).removeClass('current');
                if(options.titleHidden){
                    $('.slidePanelTitle',_this).hide();
                }
            }
            switch(options.orientation){
                case 'right':
                    _this.animate({
                        'right': -_this.width()
                    },options.speed,aa);
                    break;
                case 'top':
                    _this.animate({
                        'top': -_this.height()
                    },options.speed,aa);
                    break;
                case 'bottom':
                    _this.animate({
                        'bottom': -_this.height()
                    },options.speed,aa);
                    break;
                default:
                    _this.animate({
                        'left': -_this.width()
                    },options.speed,aa);
            }
            _this[0].show = false;
        }).bind('show',function(){
            var _this = $(this);
            _this.stop(true,true);
            switch(options.orientation){
                case 'right':
                    _this.css('right', 0);
                    break;
                case 'top':
                    _this.css('top', 0);
                    break;
                case 'bottom':
                    _this.css('bottom', 0);
                    break;
                default:
                    _this.css('left', 0);
            }        
            _this.css('z-index',9988);
            _this.find('.slidePanelTitle').addClass('current');
            if(options.titleHidden){
                _this.find('.slidePanelTitle').show();
            }
            _this[0].show = true;
        }).bind('slideIn',function(){

            var _this = $(this);
            if(options.closeAll){
                $('.slidePanel').not(_this).trigger('hide');
            }
            _this.stop(true,true);
            switch(options.orientation){
                case 'right':
                    _this.animate({
                        'right':0
                    },options.speed);
                    break;
                case 'top':
                    _this.animate({
                        'top':0
                    },options.speed);
                    break;
                case 'bottom':
                    _this.animate({
                        'bottom':0
                    },options.speed);
                    break;
                default:
                    _this.animate({
                        'left':0
                    },options.speed);
            }     
           
            _this.css('z-index',9988);
            $('.slidePanelTitle',_this).addClass('current');
            if(options.titleHidden){
                $('.slidePanelTitle',_this).show();
            }
            _this[0].show = true;
        }).bind('toggle',function(){
            var _this = $(this);
            if(_this[0].show){
                _this.trigger('slideOut');
            }else{

                _this.trigger('slideIn');
            }            
        });
        if(options.titleChange){
            _panel.bind('titleChange',function(){
                if(arguments[1] && typeof arguments[1].title == 'string'){
                    $('.title',_title).text(arguments[1].title);
                    switch(options.orientation){
                        case 'right':
                            _title.css({
                                'left':-_title.width()
                            });
                            break;
                        default:
                            _panel.css({
                                'left':0,
                                'right':'auto'
                            });
                            _title.css({
                                'right': -_title.width()
                            });
                    }
                }
            })
        }
        _panel.trigger('hide');
        $('.title',_title).bind('click',function(){
            $(this).parent().trigger('toggle');
        });
        $('.buttonClose',_panel).bind('click',function(){
            $(this).parent().parent().trigger('toggle');
        });
        _panel.bind('mousewheel',function(event){
            event.stopPropagation();
            return false;
        });
        _panel.attr('tabindex',options.tabIndex);//.focus();
        _panel.bind('keydown.panel_close', function (event) {
            if (event.keyCode == 27 && $(this)[0].show) {
                event.preventDefault();
                _panel.trigger('hide');
            }
        });   
        if(options.heightAuto){
            _content.height('auto');
            _panel.height('auto');
        }        
        return _panel;
    },
    flowAlert: function(options){
        var options = $.extend({
            styleClass: 'error',
            text: i18n.m62,
            buttonClose: true
        },options);
        
        var _box = $('<div></div>')
        .addClass('flowAlert flowAlert-' + options.styleClass)
        .append(options.text);
        
        if(options.buttonClose){
            var _button_close  = $('<span class="buttonClose icon16 icon16-close" title="' + i18n.m144 + '"></span>');
            _button_close.bind('click', function(){
                $(this).parent().fadeOut(function(){
                    $(this).remove();
                });
                
            });
            _box.prepend(_button_close);
        }
        return _box;
    },
    ajaxAlert: function(options){
        var options = $.extend({
            title: i18n.m62,
            styleClass: 'error',
            text: i18n.m62,
            buttonClose: false,
            speedClose: 3000,
            speedOpen: 500,
            orientation: 'right' /* center */
        },options);
        var _body = $(document.body),
        ajax_alert_box = $('#ajax_alert_box_' + options.orientation);
        if (!ajax_alert_box.attr('id')) {
            ajax_alert_box = $('<div id="ajax_alert_box_' + options.orientation + '" class="ajaxAlertBox"></div>')
            .appendTo(_body);
        }
        switch(options.orientation){
            case 'center':
                ajax_alert_box.css({
                    'left':'50%',
                    'margin-left':-(ajax_alert_box.width()/2)
                });
                break;
            default:
                ajax_alert_box.css('right',(_body.width() - $("#header_top").width())/2);
        }
        $('<div class="item ' + options.styleClass + '"><span class="icon icon48"></span>' + (options.buttonClose ? '<span class="buttonClose icon16 icon16-close" title="' + i18n.m144 + '"></span>' : '') + '<h3>' + options.title + '</h3><p>' + options.text + '</p></div>')
        .prependTo(ajax_alert_box)
        .hide(function(){
            var _this = $(this);
            _this.css('margin-top',-_this.innerHeight());
        })
        .show()
        .animate({
            marginTop: '0'
        },options.speedOpen)
        .delay(options.speedClose)
        .fadeOut('slow', function() {
            $(this).remove();
        })
        .find('.buttonClose').css('cursor','pointer').bind('click',function(){
            $(this).parent().stop(true,true).fadeOut('fast',function(){
                $(this).remove();
            });
        });
        return this;
    },
    /* jQuery Alert Dialogs Plugin
* Version 1.1
* Cory S.N. LaViska
* A Beautiful Site (http://abeautifulsite.net/)
* 14 May 2009
* Visit http://abeautifulsite.net/notebook/87 for more information
* License:
* This plugin is dual-licensed under the GNU General Public License and the MIT License and
* is copyright 2008 A Beautiful Site, LLC.
*/
    dialog: {

        // These properties can be read/written by accessing $.dialog.propertyName from your scripts at any time
		
        verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
        horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
        repositionOnResize: true,           // re-centers the dialog on window resize
        overlayOpacity: .9,                // transparency level of overlay
        overlayColor: '#FFF',               // base color of overlay
        draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
        okButton: i18n.m65,         // text for the OK button
        cancelButton: i18n.m344, // text for the Cancel button
        dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
        // Public methods
		
        alert: function(message, title, callback) {
            if( title == null ) title = i18n.m67;
            $.dialog._show(title, message, null, 'alert', function(result) {
                if( callback ) callback(result);
            });
        },
		
        confirm: function(message, title, callback) {
        
            if( title == null ) title = i18n.m68;
            $.dialog._show(title, message, null, 'confirm', function(result) {
                if( callback ) callback(result);
            });
        },
			
        prompt: function(message, value, title, callback) {
            if( title == null ) title = i18n.m69;
            $.dialog._show(title, message, value, 'prompt', function(result) {
                if( callback ) callback(result);
            });
        },
		
        // Private methods
		
        _show: function(title, msg, value, type, callback) {
            var display = false;
            if($('#popup_container').attr('id')){
                display = true;
            }
            $.dialog._hide();
            $.dialog._overlay('show');
			
            var popup_container = $(
                '<div id="popup_container" class="formBlack">' +
                (title === false ? '' : '<h1 id="popup_title"></h1>') +
                '<div id="popup_content">' +
                '<span class="icon icon48"/>' +
                '<div id="popup_message"></div>' +
                '</div>' +
                '</div>'
                ).hide();
			
            $('body').append(popup_container);
			
            if( $.dialog.dialogClass ) popup_container.addClass($.dialog.dialogClass);
			
            // IE6 Fix
            var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';
			
            popup_container.css({
                position: pos,
                zIndex: 99999,
                padding: 0,
                margin: 0
            });
            
            popup_container.addClass(type);
            if(title !== false){
                $("#popup_title").text(title);
            }
            $("#popup_message").text(msg);
            $("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
            popup_container.css({
                minWidth: popup_container.outerWidth(),
                maxWidth: popup_container.outerWidth()
            });
			
            $.dialog._reposition();
            $.dialog._maintainPosition(true);
            switch( type ) {
                case 'alert':
                    $("#popup_content").after('<div id="popup_panel"><input class="button" type="button" value="' + $.dialog.okButton + '" id="popup_ok" /></div>');
                    $("#popup_ok").click( function() {
                        $.dialog._hideFX();
                        callback(true);
                    });
                    if(display){
                        popup_container.show();
                    }else{
                        popup_container.css({
                            'margin-top':-70,
                            'opacity':0
                        }).show().animate({
                            'margin-top':0,
                            'opacity':1
                        }, 'fast');
                    }
                    $("#popup_ok").focus().keypress( function(e) {
                        if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
                    });
                    break;
                case 'confirm':
                    $("#popup_content").after('<div id="popup_panel"><input type="button" class="button" value="' + $.dialog.okButton + '" id="popup_ok" /> <input type="button" class="button" value="' + $.dialog.cancelButton + '" id="popup_cancel" /></div>');
                    $("#popup_ok").click( function() {
                        $.dialog._hideFX();
                        if( callback ) callback(true);
                    });
                    $("#popup_cancel").click( function() {
                        $.dialog._hideFX();
                        if( callback ) callback(false);
                    });
                    if(display){
                        popup_container.show();
                    }else{
                        popup_container.css({
                            'margin-top':-70,
                            'opacity':0
                        }).show().animate({
                            'margin-top':0,
                            'opacity':1
                        }, 'fast');
                    }
                    $("#popup_ok").focus();
                    $("#popup_ok, #popup_cancel").keypress( function(e) {
                        if( e.keyCode == 13 && $('#popup_ok:focus').length){
                            $("#popup_ok").trigger('click');
                            e.stopPropagation();
                            return false;
                        }
                        if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
                    });
                    break;
                case 'prompt':
                    $("#popup_content").append('<div id="popup_prompt_box"><input type="text" size="30" id="popup_prompt" /></div>').after('<div id="popup_panel"><input type="button" class="button" value="' + $.dialog.okButton + '" id="popup_ok" /> <input type="button" class="button" value="' + $.dialog.cancelButton + '" id="popup_cancel" /></div>');
                    $("#popup_prompt").width( $("#popup_message").width() -80);
                    $("#popup_ok").click( function() {
                        var val = $("#popup_prompt").val();
                        $.dialog._hideFX();
                        if( callback ) callback( val );
                    });
                    $("#popup_cancel").click( function() {
                        $.dialog._hideFX();
                        if( callback ) callback( null );
                    });
                    if(display){
                        popup_container.show();
                    }else{
                        popup_container.css({
                            'margin-top':-70,
                            'opacity':0
                        }).show().animate({
                            'margin-top':0,
                            'opacity':1
                        }, 'fast');
                    }
                    $("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
                        if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
                        if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
                    });
                    if( value ) $("#popup_prompt").val(value);
                    $("#popup_prompt").focus().select();
                    break;
            }

            // Make draggable
            if( $.dialog.draggable ) {
                try {
                    popup_container.draggable({
                        handle: $("#popup_title")
                    });
                    $("#popup_title").css({
                        cursor: 'move'
                    });
                } catch(e) { /* requires jQuery UI draggables */ }
            }
        },
        _hide: function() {
            $("#popup_container").remove();
            $.dialog._overlay('hide');
            $.dialog._maintainPosition(false);
        },		
        _hideFX: function() {
            $("#popup_container").stop(true,true).animate(
            {
                'margin-top':50,
                'opacity':0
            },
            'fast',
            function(){
                $(this).remove();
            }
            );
            $.dialog._overlay('hide');
            $.dialog._maintainPosition(false);
        },		
        _overlay: function(status) {
            switch( status ) {
                case 'show':
                    $.dialog._overlay('hide');
                    $("BODY").append('<div id="popup_overlay"></div>');
                    $("#popup_overlay").css({
                        position: 'absolute',
                        zIndex: 99998,
                        top: '0px',
                        left: '0px',
                        width: '100%',
                        height: $(document).height(),
                        /*background: $.dialog.overlayColor,*/
                        opacity: $.dialog.overlayOpacity
                    });
                    break;
                case 'hide':
                    $("#popup_overlay").remove();
                    break;
            }
        },
		
        _reposition: function() {
            var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.dialog.verticalOffset;
            var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.dialog.horizontalOffset;
            if( top < 0 ) top = 0;
            if( left < 0 ) left = 0;
			
            // IE6 fix
            if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
            $("#popup_container").css({
                top: top + 'px',
                left: left + 'px'
            });
            $("#popup_overlay").height( $(document).height() );
        },
		
        _maintainPosition: function(status) {
            if( $.dialog.repositionOnResize ) {
                switch(status) {
                    case true:
                        $(window).bind('resize', $.dialog._reposition);
                        break;
                    case false:
                        $(window).unbind('resize', $.dialog._reposition);
                        break;
                }
            }
        }
		
    }
});
$.fn.shuffle = function() {

    var allElems = this.get(),
    getRandom = function(max) {
        return Math.floor(Math.random() * max);
    },
    shuffled = $.map(allElems, function(){
        var random = getRandom(allElems.length),
        randEl = $(allElems[random]).clone(true)[0];
        allElems.splice(random, 1);
        return randEl;
    });

    this.each(function(i){
        $(this).replaceWith($(shuffled[i]));
    });

    return $(shuffled);

};

var test = {
    getMoreContent: function(word, count){
        for(var i=0,str = ''; i<count; ++i){
            str += word;
        }
        return str;
    }
}



var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    },
    {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    },
    {
        prop: window.opera,
        identity: "Opera"
    },
    {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    },
    {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    },
    {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    },
    {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    },
    {		// for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    },
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    },
    {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    },
    { 		// for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }
    ],
    dataOS : [
    {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    },
    {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    },
    {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
    },
    {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }
    ]
	
};
/* ##### START passStrength ##### */

/*
 * passStrength
 * version 0.9.1
 * author Ritchie Comley
 * Copyright (c) 2010 Bug Software Limited (bugsoftware.co.uk)
 * Copyright (c) 2009 myPocket technologies (www.mypocket-technologies.com)
 * View the GNU General Public License http://www.gnu.org/licenses/.
*/



$.fn.passStrengthener = function(options){
    var defaults = {
        badLimit: 10,
        goodLimit: 20,
        shortLimit: 6,
        shortPass: i18n.m351,
        badPass: i18n.m352,
        goodPass: i18n.m353,
        strongPass: i18n.m354,
        samePass: i18n.m355,
        css:{
            bad: "badPass",
            good: "goodPass",
            strong: "strongPass"
        },
        baseStyle: "passStrengthener",
        userid: false,
        messageloc: 1, /*before == 0 or after == 1*/
        strengthCallback: function(score, strength) {}
    };
    var opts = $.extend(defaults, options);
    var strengths = {
        tooshort: {
            message:opts.shortPass,
            cssclass:opts.css.bad
        },
        bad: {
            message:opts.badPass,
            cssclass:opts.css.bad
        },
        good: {
            message:opts.goodPass,
            cssclass:opts.css.good
        },
        strong: {
            message:opts.strongPass,
            cssclass:opts.css.strong
        },
        same: {
            message:opts.samePass,
            cssclass:opts.css.bad
        }
    };
    var allCSSArr = [];
    $.each(opts.css, function(i, val){
        allCSSArr.push(val);
    });
    function teststrength(password, username, option){
        if (password.length < option.shortLimit){
            return 'tooshort';
        }
        if (password.toLowerCase()==username.toLowerCase()){
            return 'same';
        }
        var score = 0; 
        score += password.length * 4;
        score += ( checkRepetition(1,password).length - password.length ) * 1;
        score += ( checkRepetition(2,password).length - password.length ) * 1;
        score += ( checkRepetition(3,password).length - password.length ) * 1;
        score += ( checkRepetition(4,password).length - password.length ) * 1;
        if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){
            score += 5;
        } 
        /*password has 2 symbols*/
        if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){
            score += 5;
        }
        /*password has Upper and Lower chars*/
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){
            score += 10;
        } 
        /*password has number and chars*/
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){
            score += 15;
        }
        /*password has number and symbol*/
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){
            score += 15;
        } 
        /*password has char and symbol*/
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){
            score += 15;
        }
        /*password is just a numbers or chars*/
        if (password.match(/^\w+$/) || password.match(/^\d+$/)){
            score -= 10;
        }
        /*verifying 0 < score < 100*/
        if (score < 0){
            score = 0;
        }
        if (score > 100)
        {
            score = 100;
        } 
        return score;
    }
    function checkRepetition(pLen,str){
        var res = '';
        for (var i = 0; i < str.length; i++) 
        {
            var repeated = true;
            for (var j=0;j < pLen && (j+i+pLen) < str.length;j++){
                repeated = repeated && (str.charAt(j+i)==str.charAt(j+i+pLen));
            }
            if (j<pLen){
                repeated = false;
            }
            if (repeated){
                i += pLen-1;
                repeated = false;
            }else{
                res += str.charAt(i);
            }
        }
        return res;
    }
    return this.each(function() { 
        var obj = $(this);
        $(obj).unbind().bind('keyup', function(){

            var jPass = $(this);
            var password = jPass.val();            
            var userID = opts.userid ? $(opts.userid).val() : '';
            var score = teststrength(jPass.val(), userID, opts);
            if(typeof(score) == 'string'){
                strength = score;
                score = 0;
            }else if (score < opts.badLimit){
                strength = 'bad';
            }else if (score < opts.goodLimit){
                strength = 'good';
            }else{
                strength = 'strong';
            }
            var cssClass = strengths[strength].cssclass;
            var message = strengths[strength].message;
            var jFeedback = jPass.parent().find("span." + opts.baseStyle);
            if(!jFeedback.size()){
                jFeedback = $('<span class="' + opts.baseStyle + '"><span class="score"><span class="track"></span><span class="bars"></span></span></span>');
                if(opts.messageloc === 1){
                    jFeedback.insertAfter(jPass);
                }else{
                    jFeedback.insertBefore(jPass);
                }
            }
            if(!jFeedback.hasClass(cssClass)){
                jFeedback.removeClass(allCSSArr.join(' ')).addClass(cssClass);
            }
            jFeedback.find('span.score span.track').html('&nbsp;' + message);
            jFeedback.find('span.score span.bars').html('&nbsp;' + message);
            jFeedback.find('span.score span.bars').css({
                width: score + '%'
            });
            opts.strengthCallback(score, strength);
        });
    });
};  

/* ##### END passStrength ##### */

/* ##### START jQuery Easing ##### */

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        //alert(jQuery.easing.default);
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c*(t/=d)*t*t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t + b;
        return c/2*((t-=2)*t*t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t*t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t*t*t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
        return c/2*((t-=2)*t*t*t*t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t==0) return b;
        if (t==d) return b+c;
        if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
        return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
    },
    easeInOutCirc: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
        return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
    },
    easeInElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    easeOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    easeInOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d/2)==2) return b+c;
        if (!p) p=d*(.3*1.5);
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
    },
    easeInBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    easeOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    easeInOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    easeInBounce: function (x, t, b, c, d) {
        return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
    },
    easeOutBounce: function (x, t, b, c, d) {
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        } else {
            return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
        }
    },
    easeInOutBounce: function (x, t, b, c, d) {
        if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
        return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
    }
});
/*
jswing def
easeInQuad easeOutQuad easeInOutQuad
easeInCubic easeOutCubic easeInOutCubic
easeInQuart easeOutQuart easeInOutQuart
easeInQuint easeOutQuint easeInOutQuint
easeInSine easeOutSine easeInOutSine
easeInExpo easeOutExpo easeInOutExpo
easeInCirc easeOutCirc easeInOutCirc
easeInElastic easeOutElastic easeInOutElastic
easeInBack easeOutBack easeInOutBack
easeInBounce easeOutBounce easeInOutBounce
*/

/* ##### END jQuery Easing ##### */


String.prototype.ellipsis = function(toLength, ellipsis){
    ellipsis = ellipsis || '\u2026';
    if (toLength < 1) {
        return this + '';
    }
    if (this.length < toLength) {
        return this + '';
    }
    return this.substr(0, toLength) + ellipsis;
}

var utils = {
    selectedRows: function(selector){
        if(selector.length){
            var arr = [];
            selector.each(function(i){
                arr[i] = $(this).val();
            })
            return arr;
        }else{
            $.ajaxAlert({
                title: '',
                text:i18n.m504,
                styleClass: 'message',
                buttonClose: true,
                speedClose: 3000
            });
            return false;
        }
    },
    fileName: function(file){
        var fileName = file.replace(/.*\\(.*)/, "$1"); 
        fileName = fileName.replace(/.*\/(.*)/, "$1");
        return fileName;
    },
    formErrorAlert: function(form, validator) {
        var errors = validator.numberOfInvalids();
        var _form = $(form.target)
        if (errors) {
            var first = $(validator.errorList[0].element);
            box_fx.boxScrollToTop(first, 30);
            
            var message = errors == 1 ? i18n.m277 : i18n.m278.supplant({
                number:errors
            });
            $.ajaxAlert({
                title: '',
                text: message,
                styleClass: 'error',
                buttonClose: true,
                speedClose: 5000
            });
        }
    },
    formErorHighlight: function(element, errorClass) {
    /*$(element).fadeOut('fast', function() {
            $(element).fadeIn('fast');
        });*/
    },
    socialConnectingPanel: function(element){
        var _this = $(element).parent(),
        data = links.social_connecting[_this.index()],
        _h = $('.slidePanelTopBar h3', global.soccon_login_panel),
        _c = $('.slidePanelContent .block', global.soccon_login_panel),
        _icon = $('.iconServ',_h),
        _name = $('.name',_h);
            
        _icon.removeAttr('class').addClass('iconServ iconServ-' + data.id);
        _name.html(i18n.m290.supplant({
            name:data.title
        }));
        var o = {
            action: data.formAction || '/',
            type: data.id,
            styleClass: 'labelsSmall labelsAuto socconFormLogin-' + data.id,
            labelBefore: data.labelBefore,
            labelAfter: data.labelAfter
        }
        _c.html(templates.socconLoginForm(o));
    },
    getNiceValue: function (size) {
        var metrics = ['b', 'KB', 'MB', 'GB'],
        metric = 0;
        while (Math.floor(size/1024) > 0){
            ++metric;
            size /= 1024;
        }
        return size.toFixed(2) + ' ' + metrics[metric];
    }

}
var box_fx = {
    boxScrollToTop: function(selector, topOffset){
        var obj = $(selector);
        if(($(document).scrollTop() - obj.offset().top) > 0){
            $('html, body').animate({
                scrollTop:obj.offset().top - (topOffset ? topOffset : 0)
            }, 'normal','easeOutQuart');
        }  
    },
    listViewModeSlide: function(box,view,v1,v2,reload_box,reload_box_height,reload_box_height_s){
        var offset = box.offset();
        var speed = 300;
        if(!ie(8)){
            if(view == v1){
                $('html, body').animate({
                    scrollTop:offset.top
                }, speed,'easeOutQuart');
                reload_box.height(reload_box.height())
                .animate({
                    'height': reload_box_height_s
                },speed,'easeOutQuart',function(){
                    reload_box.height('auto');
                    box.trigger('initBox');
                });
            }else if(view == v2){

                reload_box.height(reload_box.height())
                .animate({
                    'height': reload_box_height
                },speed,'easeInQuad',function(){
                    reload_box.height('auto');
                });
                box.trigger('initBox');
            }
        }else{
            box.trigger('initBox');
            $('html, body').scrollTop(offset.top);
        }
    }
}

var ie = function(v){
    if($.browser.msie && parseInt($.browser.version) <= v){
        return true;
    }else{
        return false;
    }
}

var global = {
    user: {
        // TODO: завязать на базу
        role: {
            guest: 0,
            viewer: 1,
            publisher: 2,
            staff: 3,
            admin: 4
        }
    },
    flashParams: {
        scale: "noscale",
        wmode: "opaque",
        allowFullScreen: "true",
        allowScriptAccess: "always",
        bgcolor: '#000000',
        quality: "high"
    },
    statesChecker: function (el)
    {
        // US
        if($(el).val() == 228)
        {
            $('#cart_pay_form_state_fieldset').show();
            $('#cart_pay_form_states_us').show();
            $('#cart_pay_form_states_ca').hide();
        }
        // CA
        else if($(el).val() == 39)
        {
            $('#cart_pay_form_state_fieldset').show();
            $('#cart_pay_form_states_us').hide();
            $('#cart_pay_form_states_ca').show();
        }
        // another country
        else
        {
            $('#cart_pay_form_state_fieldset').hide();
        }
    },
    newStatesChecker: function (idPrefix)
    {
        // US
        if($(idPrefix + 'country').val() == 228)
        {
            $(idPrefix + 'state_fieldset').show();
            $(idPrefix + 'states_us').show();
            $(idPrefix + 'states_ca').hide();
        }
        // CA
        else if($(idPrefix + 'country').val() == 39)
        {
            $(idPrefix + 'state_fieldset').show();
            $(idPrefix + 'states_us').hide();
            $(idPrefix + 'states_ca').show();
        }
        // another country
        else
        {
            $(idPrefix + 'state_fieldset').hide();
        }
    },
    rules:{
        cart_pay:
        {
            email: {
                required: true,
                email: true
            },
            cctype: {
                required: true
            },
            ccnumber: {
                required: true
            },
            exp_month: {
                required: true
            },
            exp_year: {
                required: true
            },
            first_name: {
                required: true
            },
            last_name: {
                required: true
            },
            street_address: {
                required: true
            },
            city: {
                required: true
            },
            zip: {
                required: true
            },
            country: {
                required: true
            },
            state: {
                required: false
            }
        }
    },
    messages:{
        cart_pay:
        {
            email: {
                required: i18n.m197,
                email: i18n.m286
            },
            /*cctype: {
                required: i18n.m197
            },*/
            ccnumber: {
                required: i18n.m197
            },
            /*exp_month: {
                required: i18n.m197
            },
            exp_year: {
                required: i18n.m197
            },*/
            first_name: {
                required: i18n.m197
            },
            last_name: {
                required: i18n.m197
            },
            street_address: {
                required: i18n.m197
            },
            city: {
                required: i18n.m197
            },
            zip: {
                required: i18n.m197
            },
            country: {
                required: i18n.m197
            }
        }
    }
};
    
links = {
    search_menu: {
        'films': i18n.m1,
        'music': i18n.m291,
        'channels': i18n.m70,
        'users': i18n.m73,
        'reviews/videos': i18n.m74,
        'blogs': i18n.m40,
        'film-festivals': i18n.m4
    },
    video_full_list_view: {
        'quickView': i18n.m79,
        'detailedView': i18n.m80
    },
    social_connecting: [
    {
        'id': 'facebook',
        'title': 'Facebook Connect',
        'href': 'http://facebook.com/',
        'action': function(event){
            event.preventDefault();
            global.soccon_login_panel.trigger('hide');
            document.cookie = '_http_referer=' + document.location.href + '; path=/';
            /*FB.Connect.requireSession(function() {
                    FB.Connect.showPermissionDialog('offline_access, read_stream, publish_stream, status_update',
                        function(perms){
                            window.location='/connect/facebook/';
                        }
                    );
                });*/
            //FB.init({appId: "119285718113865", status: false, cookie: true, xfbml: false});
            FB.login(function(response) {
                if (response && response.authResponse) {
                    document.location = '/connect/facebook/';
                }
            },
            {
                scope: 'read_stream,publish_stream,offline_access'
            }
            );

        //return false;
        //window.open('http://www.facebook.com/login.php?api_key=6f9204e9d95c0febdd31c96a489d6a64&display=popup&extern=2&fbconnect=1&req_perms=publish_stream&return_session=1&v=1.0&next=http%3A%2F%2Fof2.nvoronin-vb.ua.openfilm.com%2Fconnect%2Ffacebook&fb_connect=1&cancel_url=http%3A%2F%2Fof2.nvoronin-vb.ua.openfilm.com%2Fconnect%2Ffacebook', '_blank', 'top=442,width=480,height=460,resizable=yes', true);
        //FB.Connect.requireSession(); return false;
        //$.dialog.alert('TODO: open new window for Facebook connect', i18n.m290.supplant({name:'Facebook Connect'}));
        }
    },
    {
        'id': 'twitter',
        'title': 'Twitter',
        'href': '/connect/twitter/',
        'action': function(event){
            event.preventDefault();
            global.soccon_login_panel.trigger('hide');
            document.cookie = '_http_referer=' + document.location.href + '; path=/';
            document.location.href = '/connect/twitter/';
        //$.dialog.alert('TODO: redirect to twitter', i18n.m290.supplant({name:'Twitter'}));
        }
    }/*,
        {
            'id': 'google',
            'title': 'Google',
            'href': '#',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('hide');
                $.dialog.alert('TODO: redirect to Google', i18n.m290.supplant({name:'Google'}));
            }
        },
        {
            'id': 'yahoo',
            'title': 'Yahoo',
            'href': '#',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('hide');
                $.dialog.alert('TODO: redirect to Yahoo', i18n.m290.supplant({name:'Yahoo'}));
            }
        },
        {
            'id': 'aol',
            'title': 'AOL Screen Name',
            'href': '#',
            'labelBefore': 'http://openid.aol.com/',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('slideIn');
                utils.socialConnectingPanel(this);
            }
        }*/,
    {
        'id': 'myspace',
        'title': 'Myspace Username',
        'href': '#',
        'formAction': '/connect/myspace/',
        'labelBefore': 'http://myspace.com/',
        'action': function(event){
            event.preventDefault();
            global.soccon_login_panel.trigger('slideIn');
            document.cookie = '_http_referer=' + document.location.href + '; path=/';
            utils.socialConnectingPanel(this);
        }
    }/*,
        {
            'id': 'openid',
            'title': 'OpenId',
            'href': '#',
            'labelBefore': 'OpenId',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('slideIn');
                utils.socialConnectingPanel(this);
            }
        },
        {
            'id': 'livejournal',
            'title': 'Livejournal Blog Name',
            'href': '#',
            'labelBefore': 'http://',
            'labelAfter': '.livejournal.com',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('slideIn');
                utils.socialConnectingPanel(this);
            }
        },
        {
            'id': 'blogger',
            'title': 'Blogger Blog Name',
            'href': '#',
            'labelBefore': 'http://',
            'labelAfter': '.blogspot.com',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('slideIn');
                utils.socialConnectingPanel(this);
            }
        },
        {
            'id': 'wordpress',
            'title': 'Wordpress Blog Name',
            'href': '#',
            'labelBefore': 'http://',
            'labelAfter': '.wordpress.com',
            'action': function(event){
                event.preventDefault();
                global.soccon_login_panel.trigger('slideIn');
                utils.socialConnectingPanel(this);
            }
        }*/
        
    ]
};
var config = {
    commentsCharacterCount: 160,
    messageCharacterCount: 180,
    loginMinLength: 3,
    loginMaxLength: 20,
    passwordMinLength: 6,
    passwordMaxLength: 40,
    shoppingTypes: {
        iphone:1,
        full: 2
    }
}
var templates = {
    selectList: function(arr){
        /*
    * 0 - arr
    * 1 - selected
    * 2 - name
    * 3 - class
    * 4 - id
    */
        var str = '<select' + (arguments[2] ? ' name="' + arguments[2] + '"' : '') + (arguments[3] ? ' class="' + arguments[3] + '"' : '') + (arguments[4] ? ' id="' + arguments[4] + '"' : '') + '>';
        for(var i = 0, c = arr.length; i < c; ++i){
            str += '<option value="' + arr[i] + '"' + (arguments[1] == i ? 'selected="selected"' : '') + '>' + arr[i] + '</option>';
        }
        str += '</select>';
        return str;
    },
    linksList: function(obj){
        /*
    * 0 - link obj
    * 1 - class
    * 2 - id
    * 3 - icon type number
    * 4 - link prefix, default - #
    *///
        arguments[4] = arguments[4] || "#";
        var h = arguments[4].toString();
        var str = '<ul' + (arguments[1] ? ' class="' + arguments[1] + '"' : '') + (arguments[2] ? ' id="' + arguments[2] + '"' : '') + '>';
        for(var i in obj){
            str += '<li><a' + (arguments[3] ? ' class="icon' + arguments[3] + ' icon' + arguments[3] + '-' + i + '" title="' + obj[i] + '"' : '') + ' href="' + h + i + '">' + obj[i] + '</a></li>\r';
        }
        return str + '</ul>';
    },
    searchPanelContent: function(){
        return '<input type="hidden" id="search_href" value="' + (arguments[0] ? '/' + arguments[0] : '/films') + '"/><input type="text" class="text" id="search_tag" maxlength="200" /><input type="button" class="button" value="' + i18n.m77 + '" id="search_button" />';
            
    },
    commentsForm: function(){
        var o = arguments[0];
        return '<form action="' + (o.action ? o.action : '') + '" method="post" class="' + (o.styleClass ? o.styleClass : '') + '"><textarea class="textareaComment noCorners" name="comment" cols="25" rows="4"></textarea><div class="error"></div><button type="submit" class="button">' + (o.buttonTitle ? o.buttonTitle : '') + '</button><span class="label characterCountLabel">Remaining character count: <span class="characterCount">' + config.commentsCharacterCount + '</span></span></form>';
    },
    sendMessageForm: function(){
        var o = arguments[0];
        return '<form action="' + (o.action ? o.action : '') + '" method="post" class="' + (o.styleClass ? o.styleClass : '') + '"><fieldset><label for="send_message_form_subject">' + i18n.m181 + ':</label><br/><div class="error"></div><input type="text" id="send_message_form_subject" name="subject" value="" /><br/><label for="send_message_form_message">' + i18n.m180 + ':</label><br/><div class="error"></div><textarea id="send_message_form_message" class="textareaMessage" name="message" cols="25" rows="3"></textarea></fieldset><fieldset class="buttons"><button type="submit" class="button">' + (o.buttonTitle ? o.buttonTitle : '') + '</button><a class="actionTextLink" href="#form_reset">' + i18n.m66  + '</a><span class="label characterCountLabel">Remaining character count: <span class="characterCount">' + config.messageCharacterCount + '</span></span></fieldset></form>';
    },
    loginForm: function(){
        var o = arguments[0];
        return '<form action="/" method="post" class="formLogin formVertical labelsAuto"><fieldset><label for="login_form_login">' + i18n.m255 + ':</label><br/><div class="error"></div><input maxlength="' + config.loginMaxLength + '" type="text" id="login_form_login" name="login" value="" /><br/><label for="login_form_password">' + i18n.m257 + ':</label><br/><div class="error"></div><input maxlength="' + config.passwordMaxLength + '" type="password" id="login_form_password" name="password" value="" /><div class="notice"><a class="actionTextLink buttonForgot" href="/recovery-password/">' + i18n.m293 + '</a></div></fieldset><fieldset class="buttons"><button type="submit" class="button">' + i18n.m10 + '</button><a class="actionTextLink" href="#form_reset">' + i18n.m66  + '</a></fieldset></form>';
    },
    socconLoginForm: function(){
        var o = arguments[0],
        str = '<form action="' + (o.action ? o.action : '') + '" method="post" class="' + (o.styleClass ? o.styleClass : '') + '">';
        str += '<fieldset>';
        if(o.type){
            str += '<input type="hidden" value="' + o.type + '"/>';
        }
        if(o.labelBefore){
            str += '<label for="soccon_login_form_login">' + o.labelBefore + '</label>';
        }
        str += '<input type="text" id="soccon_login_form_login" name="login" value="" />';
        if(o.labelAfter){
            str += '<label class="after">' + o.labelAfter + '</label>';
        }
        str += '</fieldset><fieldset class="buttons">';
        str += '<button type="submit" class="button">' + i18n.m10 + '</button>';
        str += '</fieldset></form>';
        return str;
    },
    passwordRecoveryForm: function(){
        return '<form action="/" method="post" class="formPasswordRecovery formGray"><div class="info">' + i18n.m296 + '</div><fieldset><label for="password_recovery_form_login">' + i18n.m295 + ':</label>\n<input type="text" id="password_recovery_form_login" name="login" value="" /><div class="error"></div><div class="notice"><a class="actionTextLink buttonLogin" href="#login">' + i18n.m299 + '</a></div></fieldset><fieldset class="buttons"><button type="submit" class="button">' + i18n.m298  + '</button><a class="actionTextLink" href="#form_reset">' + i18n.m66  + '</a></fieldset></form>';
    },
    socconLinkList: function(){
        var o = arguments[0],
        data = links.social_connecting,
        _ul = $('<ul class="socconLinkList"></ul>');
        if(o.styleClass){
            _ul.addClass(o.styleClass)
        }
        for( var i=0, c = data.length; i<c; ++i){
            $('<li><a href="' + data[i].href + '">' + data[i].title + '</a></li>')
            .bind('click', data[i].action).appendTo(_ul);
        }
        return _ul;
    },
    captchaForm: function(){
        return '<form action="/" method="post" class="formCaptcha formDark">'
        + '<fieldset class="captchaBox">'
        + '<div class="captcha"><img id="captcha_string" src="/design/images/1px_t.gif" alt="" width="120" height="60"/></div>'
        + '<label for="captcha_field">' + i18n.m273 + '</label><br/>'
        + '<a class="actionTextLink" href="#captcha_reload">' + i18n.m274 + '</a>'
        + '<input type="hidden" id="captcha_id" name="captcha_id" />'
        + '<input type="text" id="captcha_field" name="captcha_input" maxlength="10" />'
        + '<div class="error"></div>'
        + '</fieldset>'
        + '<fieldset class="buttons"><button class="button" type="submit">' + i18n.m356 + '</button><button class="button buttonClose" type="button">' + i18n.m344 + '</button></fieldset></form>';
    },
    searchHeaderBox: function(type){
        var link = links.search_menu;
        return '<div id="content_search"><div id="content_promo"><div id="content_search_box">'
        + '<h1 id="title">' + i18n.m77 + ' /</h1>'
        + '<ul id="title_info"><li>' + link[type] + '</li></ul>'
        + templates.linksList(links.search_menu, 'tabMenu', 'search_menu', false,'/')
        + templates.searchPanelContent(type)
        + '<div id="search_result">' + i18n.m467.supplant({
            query: '<em>' + search.query + '</em>',
            count: '<span id="search_result_count">' + search.count + '</span>'
        }) + '</div>'
        + '</div></div></div>';
    },
    openfilmFeedback: function(){
        var o = {
            action: '/feedbacks/create/',
            styleClass: 'formGray required',
            buttonTitle: i18n.m216
        };
        var str = '';
        str += '<div class="form_wrapper"><p class="description">'+i18n.m950 +'<p><p class="noteform">' + i18n.m276 + '</p>' +
        '<form action="'+ (o.action ? o.action : '') +'" method="post" id="openfilm_feedback_form" class="'+ o.styleClass +'">' +
        '<fieldset><label for="openfilm_feedback_name">'+ i18n.m169 +': </label>' +
        '<input type="text" id="openfilm_feedback_name" value="" name="user_name"/>' +
        '<label for="openfilm_feedback_email">'+ i18n.m952 +' :</label>' +
        '<input type="text" id="openfilm_feedback_email" name="email" value=""/>' +
        '<div class="error"></div><label for="openfilm_feedback_message"><sup>*</sup>'+ i18n.m180+' :</label>' +
        '<textarea id="openfilm_feedback_message" name="feedback" cols="25" rows="10">' +
        '</textarea><div class="error"></div></fieldset><fieldset class="buttons">' +
        '<input type="hidden" name="feedback_type" value="1"><input type="hidden" name="flash_version" value="'+swfobject.ua.pv+'"><input type="hidden" name="url" value="'+document.location+'"><button type="submit" class="button">' + (o.buttonTitle ? o.buttonTitle : '') + '</button>' +
        '<a class="actionTextLink" href="#form_reset">'+ i18n.m66 +'</a></fieldset></form></div>';
                
        return str;
    },
    ffSendEmail: function(){
        var o = {
            action: '',
            styleClass: 'formGray required',
            buttonTitle: i18n.m216
        };
        var str = '';
        str += '<div class="form_wrapper"><p class="description"><p><p class="noteform">' + i18n.m276 + '</p>' +
        '<form action="'+ (o.action ? o.action : '') +'" method="post" id="ff_email_form" class="'+ o.styleClass +'">' +
        '<fieldset>'+
        '<label for="openfilm_name"><sup>*</sup>'+ i18n.m169 +': </label>' +
        '<input type="text" id="openfilm_name" value="" name="user_name"/><div class="error"></div>' +
        '<label for="openfilm_title"><sup>*</sup>'+ i18n.m360 +': </label>' +
        '<input type="text" id="openfilm_title" name="title" value=""/>' +
        '<div class="error"></div>'+
        '<label for="openfilm_message"><sup>*</sup>'+ i18n.m180+': </label>' +
        '<textarea id="openfilm_message" name="body" cols="25" rows="10"></textarea>'+
        '<div class="error"></div>'+
        '</fieldset>'+
        '<fieldset class="buttons">' +
        '<input type="hidden" name="id_filmfestival" id="id_filmfestival" value="'+ arguments[0].ff_id +'"><button type="submit" class="button">' + (o.buttonTitle ? o.buttonTitle : '') + '</button>' +
        '<a class="actionTextLink" href="#form_reset">'+ i18n.m66 +'</a></fieldset></form></div>';
        
        return str;
    }
}


$.fn.ears = function(){
    var idPage = {
        'home' : 'header_promo_box',
        'videos_browse': 'header_promo',
        'video_details': 'header_promo',
        'users_browse': 'header_promo',
        'user_details': 'header_promo',
        'channels_browse': 'content',
        'channel_details': 'header_promo',
        'chats_index': 'content_box',
        'chats_detail': 'content',
        'browse_video_reviews': 'content',
        'browse_channel_reviews': 'content',
        'channel_review_detail': 'content',
        'video_reviews_detail': 'content',
        'blogs_posts_browse': 'content_box',
        'blogs_browse': 'content_box',
        'blog_posts_browse' : 'content_box',
        'blog_post': 'content_box',
        'film_festivals_index': 'content',
        'film_festivals_browse': 'content',
        'film_festivals_detail': 'header_promo',
        'boxee': 'content',
        'tivo': 'content',
        'hcc_tv': 'content',
        'miniweb': 'content',
        'contests_browse': 'content',
        'gim_detail': 'header_promo_box',
        'gim_detail_form': 'header_promo_box',
        'dashboard': 'header_promo'
    },

    place = idPage[ $(document.body).attr('id') ] ? $('#'+idPage[$(document.body).attr('id')]) : 
    $(document.body).is('.dashboard') ? $('#'+idPage['dashboard']) : false;

    if(place){
        var w = $(window),
        earsMini = '<div id="ears"><div id="ears_mini"></div></div>',
        earsMiniCss = {
            'background-image' : 'url(/design/images/pages/ears/ears_mini.jpg)',
            'background-repeat' : 'no-repeat',
            'width' : 980,
            'height' : 50,
            'position' : 'relative',
            'margin' : '0 auto',
            'cursor' : 'pointer',
            'padding-bottom' : 10
        },
        //http://ad.doubleclick.net/clk;225288219;48891938;c
        earsContent = '<div id="ears_content"><div id="ears_player"></div><a href="/lt/?tid=american-express&lnk=http%3A%2F%2Fad.doubleclick.net%2Fclk%3B225288219%3B48891938%3Bc" id="ears_img"></a></div>',
        earsContentCss = {
            'background-image' : 'url(/design/images/pages/ears/ears_content.jpg)',
            'width' : 980,
            'height' : 592,
            'position' : 'absolute',
            'z-index' : '9999',
            'cursor' : 'default'
        },
        earsPlayerCss = {
            'float' : 'left',
            'margin-left' : 18,
            'margin-top' : 60
        },
        earsImgCss = {
            'display' : 'block',
            'width' : 376,
            'height' : 322,
            'float' : 'left',
            'background-image' : 'url(/design/images/pages/ears/ears_img.jpg)',
            'margin-top' : 60
        },
        earsClose = '<div id="ears_close"></div>',
        earsCloseCss = {
            'background-image' : 'url(/design/images/icons/icon16.png)',
            'background-position' : '0 -320px',
            'display' : 'block',
            'height' : 16,
            'position' : 'absolute',
            'right' : 10,
            'text-indent' : '-9999',
            'top': 10,
            'width': 16,
            'cursor' : 'pointer'
        };
        var backlight = $('<div id="ears_backLight" class="ajaxIndicatorBacklight"></div>');
        backlightCss = {
            'opacity': 0.8,
            'display': 'block',
            'z-index': '9990',
            'position': 'absolute',
            'top' : 0,
            'left' : 0
        };
            
        place.prepend(earsMini).find('#ears').css(earsMiniCss).find('#ears_mini').css({
            'width':980, 
            'height':50
        }).bind('click', function(){
            var _this = $('#ears');
            //_this
                
            $(document.body).append(backlight).find('#ears_backLight').css(backlightCss).css({
                'height':$('#root').height(),
                'width': w.width()
            }).fadeIn('fast', function(){
                $(this).bind('click', function(){
                    $('#ears_content').remove();
                    $('#ears_backLight').remove();
                });
            });
                
            $(document.body).append(earsContent)
            $('#ears_content').css(earsContentCss).append(earsClose);
            $('#ears_content').css({
                'top' : (w.height()-592)/2+w.scrollTop(),
                'left' : (w.width()-980)/2+w.scrollLeft()
            });
                
            $('#ears_close').css(earsCloseCss).hover(function(){
                $(this).css({
                    'background-position' : '0 -336px'
                });
            }, function(){
                $(this).css({
                    'background-position' : '0 -320px'
                });
            }).bind('click', function(){
                $('#ears_content').remove();
                $('#ears_backLight').remove();
            });
                
            flashvars = {
                file: '/videos/a/load/26625',
                timebar : false,
                menu : false,
                hd : false,
                captions : false,
                displaymenu : false,
                related : false
            };
                
            swfobject.embedSWF("/design/flash/player.swf", "ears_player", "569", "322", "9.0.0","/design/flash/expressInstall.swf", flashvars, global.flashParams);
                
            $('#ears_img').css(earsImgCss);
            $('#ears_player').css(earsPlayerCss);
                
            if($('#video_player_content').length && document.getElementById('video_player_content')){
                document.getElementById('video_player_content').sendEvent('stop');
            }
            if($('#home_video').length && document.getElementById('home_video')){
                document.getElementById('home_video').childNodes[1].pause()
            }
        });
    }
};



function insertAds (places) {
    var i = 0,
    ids = [],
    vids = [];
    if ( !(i = places.length)) {
        return;
    }
    while (i) {
        places[--i] = $(places[i]);
        ids[i] = places[i].attr('id').replace(/.*_/,'');
        vids[i] = places[i].attr('class').replace(/^ap vid_/,'');
    }
    function renderPanel(place){
        var panel = place.parents('.panelLeft, .panelCenter, .panelRight');
        if(panel.length){
            height =  panel.height();
            panel.height(height).height('auto');
        }
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        cache: false,
        data : 'id[]=' + ids.join('&id[]=') + '&vid[]=' + vids.join('&vid[]='),
        url: '/get_media_info/',
        success: function(data){
            if (data.error){
                return;
            }
            var i = places.length,
            res,
            t = new Date();
            t = t.getTime();
            
            while (i) {
                --i;
                res = null;
                if (!!data[ids[i]].type) {
                    res = data[ids[i]];
                } else {
                    continue;
                }

                if (res.type == 'iframe') {
                    var _iframe = $('<iframe src="' + res.link.supplant({
                        timestamp: "_" + t
                    }) + '" width="' + res.width + '" height="' + res.height + '" frameborder="0" />');                        
                    _iframe.bind('load', {
                        id: ids[i],
                        vid: vids[i]
                    },
                    function(event){
                        setTimeout(function(data){
                            $.ajax({
                                type:"POST",
                                cache: false,
                                data : data,
                                url: '/set_media_info/'
                            });
                        }, 5000, event.data);
                    }
                    );
                    places[i].html(_iframe);
                    if($.browser.msie && parseInt($.browser.version) == 8){
                        renderPanel(places[i]);
                    }
                } else if (data.type == 'swf') {
                /*
                var flashvars = {
                    clickTag: data.link,
                    clickTAG: data.link
                };
                var attributes = {
                    id: player_id + "_player"
                };
                swfobject.embedSWF(data.title, divId+'_del', width, height, "9.0.0", "/design/flash/expressInstall.swf", flashvars, global.flashParams, attributes);
                  */
                } else {
                    var img = '<img width="'+res.width+'" height="'+res.height+'" src="'+res.src+'" alt="'+res.title+'"/>';
                    if (res.link) {
                        img = '<a href="'+res.link.supplant({
                                timestamp: "_" + t
                            })+'">' + img + '</a>'
                    }
                    img = $(img);
                    img.bind('click', function(){
                        $.ajax({
                            type:"POST",
                            cache: false,
                            data : {
                                id: ids[i],
                                vid: vids[i]
                            },
                            url: '/set_media_click_info/'
                        });
                    });
                    if (res.ad_view_tracker) {
                        places[i].html(img);
                        img = $('<img src="' + res.ad_view_tracker.supplant({
                            timestamp: "_" + t
                        }) + ' width="1" height="1" "/>');
                    }
                    img.ready(function(){
                        $.ajax({
                            type:"POST",
                            cache: false,
                            data : {
                                id: ids[i],
                                vid: vids[i]
                            },
                            url: '/set_media_info/'
                        });
                    });
                    places[i].append(img);
                    
                }
            }
        }
    });
    
}



var layoutInit = function(){
    store = new Persist.Store('ofs', {
        swf_path: '/design/flash/persist/persist.swf'
    });
    userStatusBar = {};
    global.search_status = false;
    if(typeof search == 'object' && (search.query != '' || search.force)){
        global.search_status = true;
    }
    var search_index = 0;
    for(var i in links.search_menu){
        if(i == search.type){
            break;
        }
        search_index++;
    }
    $.validator.setDefaults({ 
        errorElement: 'em'
    });
    $.datepicker.setDefaults({
        /*showOtherMonths: true,*/
        showAnim: 'slideDown',
        prevText: i18n.m311,
        nextText: i18n.m310,
        monthNames: [i18n.m312, i18n.m313, i18n.m314, i18n.m315, i18n.m316, i18n.m317, i18n.m318, i18n.m319, i18n.m320, i18n.m321, i18n.m322, i18n.m323],
        hideIfNoPrevNext: true,
        gotoCurrent: true,
        dayNamesMin: [i18n.m324, i18n.m325, i18n.m326, i18n.m327, i18n.m328, i18n.m329, i18n.m330]
    });
        
    $('body').addClass($.client.os + 'OS').addClass($.client.browser + 'UA');
    $('body').ajaxIndikator({
        orientation:'scroll center',
        title:i18n.m158
    });
    $('#header_main_menu').dropDownMenu();
    $('#header_service_menu').dropDownMenu({});
        

    if(!ie(6)){
        var header_main_menu_end = $('#header_main_menu').offset().left + $('#header_main_menu').width();
        var _header_options_menu = $('#header_options_menu');
        _header_options_menu.empty();

        if(global.search_status){           
            $('#content').prepend(templates.searchHeaderBox(search.type));
            var content_search_box = $('#content_search_box');
            $('#search_menu', content_search_box).clickMenu({
                current:search_index,
                action:function(){
                    var href = arguments[0];
                    $('#search_href').val(href);
                    $('#search_tag').focus();
                    $('#search_button').trigger('click');
                }
            });
            $('#search_button', content_search_box).click(function(){
                location.href = $('#search_href', content_search_box).val() + '/?q=' + $('#search_tag', content_search_box).val();
            }).removeClass('button').addClass('icon24 icon24-search').val('');
            $('#search_tag', content_search_box).val(search.query).focus().keydown(function(event) {
                if (event.keyCode == '13' && $(this).val() != '') {
                    $('#search_button', content_search_box).trigger('click');
                }
            });
        }
        
        _header_options_menu.append('<li><span title="' + i18n.m77 + '" class="icon16 icon16-search buttonSearchPanel" /></li>');
        global.search_panel = $.slidePanel({
            title: '<span class="icon16 icon16-search" />',
            titleHidden: true,
            styleClass: 'panelName-search forIcon16-service titleHiddenBg formGray panelBgGray',
            content: templates.searchPanelContent(search.type),
            contentFixed: true,
            orientation:'top',
            position: 'left',
            offset: 0,
            height: 120,
            width: 470,
            topBar: templates.linksList(links.search_menu, 'tabMenu', 'search_menu', false,'/')
        });
        //global.search_panel.trigger('show')
            
        global.search_panel.css('left', header_main_menu_end - global.search_panel.width() + 40);
        $('.buttonSearchPanel').bind('click',function(){
            global.search_panel.trigger('toggle');
            $('#search_tag', global.search_panel).val('').focus();
            return false;
        });
            
        $('#search_menu', global.search_panel).clickMenu({
            current: search_index,
            action:function(){
                var href = arguments[0];
                $('#search_href', global.search_panel).val(href);
                $('#search_tag', global.search_panel).focus();
            }
        }).lastLIWidthCorrect();
        $('#search_button', global.search_panel).click(function(){
            var stag = $('#search_tag', global.search_panel).val();
            if(stag != ''){
                location.href = $('#search_href', global.search_panel).val() + '/?q=' + stag;
            }
        });
        $('#search_tag', global.search_panel).keydown(function(event) {
            if (event.keyCode == '13' && $(this).val() != '') {
                $('#search_button', global.search_panel).trigger('click');
            }
        });

        _header_options_menu.append('<li><span title="' + i18n.m217 + '" class="icon16 icon16-upload buttonUploadVideo" /></li>');
        $('.buttonUploadVideo').bind('click', function(event){
            if(mustLogin('video-upload')){
                buttons.mustLogin(event);
                return;
            }
            window.location = '/dashboard/videos/upload/';
        });        
        
        if(user.role == global.user.role.guest){
            
            var loginForm = $(templates.loginForm());
            
            var validatorLoginForm = loginForm.validate(formActions.loginPanelForm);
            $('a[href="#form_reset"]',loginForm).bind('click',function(event){
                event.preventDefault();
                validatorLoginForm.resetForm();
            });
                
            global.login_panel = $.slidePanel({
                title: false /*i18n.m10*/,
                titleHidden: true,
                styleClass: 'panelName-login formGray panelBgGray',
                content: loginForm,
                orientation:'top',
                position: 'right',
                offset: $('#header_top').offset().left,
                heightAuto: true,
                width: 250,
                contentFixed: true,
                topBar: '<h3>' + i18n.m196 + '</h3>'
            });
            loginForm.submitAjaxIndikator();

            

            
            var socconm_current = 0;
            store.get('sbmsoccon' ,function(ok, val) {
                socconm_current = val || 1;
            });
            $('#sbmsoccon').rotateIconSubMenu({
                title: i18n.m309 + ' ',
                items: links.social_connecting,
                current: socconm_current,
                styleClass: 'iconServ',
                rotate: true,
                store: true
            });
            
            global.soccon_login_panel = $.slidePanel({
                title: false,
                titleHidden: true,
                styleClass: 'panelName-socconLogin formGray panelBgGray',
                content: templates.socconLoginForm({
                    styleClass: 'socconFormLogin labelsSmall labelsAuto',
                    buttonTitle: i18n.m10
                }),
                orientation:'top',
                position: 'center',
                offset: 0,
                heightAuto: true,
                width: 460,
                contentFixed: true,
                /*closeAll: false,*/
                topBar: '<h3 class="icon"><span class="iconServ" /><span class="name">' + i18n.m290.supplant({
                    name:''
                }) + '</span></h3>'
            });
            //global.soccon_login_panel.trigger('show');

            /*var pRForm = $(templates.passwordRecoveryForm());
            
            var validatorPRForm = pRForm.validate(formActions.passwordRecoveryPanelForm);
            $('a[href="#form_reset"]',pRForm).bind('click',function(event){
                event.preventDefault();
                validatorPRForm.resetForm();
            });
            pRForm.submitAjaxIndikator();

            global.password_recovery = $.slidePanel({
                title: false,
                titleHidden: true,
                styleClass: 'panelName-passwordRecovery formGray panelBgGray',
                content: pRForm,
                orientation:'top',
                position: 'right',
                offset: $('#header_top').offset().left,
                width: 480,
                contentFixed: true,
                heightAuto: true,
                topBar: '<h3>' + i18n.m294 + '</h3>'
            });*/
            
            $('.buttonLogin').bind('click',function(event){
                event.preventDefault();
                global.login_panel.trigger('toggle');
            });            
        /*$('.buttonForgot').bind('click',function(event){
                event.preventDefault();
                //global.password_recovery.trigger('slideIn');
                // temporary turn off
                document.location.href = '/recovery-password/'
            });*/

        }else{
            var _header_service_menu = $('#header_service_menu'),
            _user_status_bar = $('#user_status_bar');

            var UPDATE_USER_STATUS_INTERVAL = 300000;
            $('.microThumbUser', _header_service_menu).thumbLoadControl();

            userStatusBar.all = $('<span id="user_status_bar_box" />');
            userStatusBar.messages = $('<span class="icon16 icon16-inmails" />').iconStatus({
                count: 'user.messages',
                title: i18n.m716,
                href: '/dashboard/inmails/inbox/'
            });
            userStatusBar.friendInvites = $('<span class="icon16 icon16-friends" />').iconStatus({
                count: 'user.friendInvites',
                title: i18n.m715,
                href: '/dashboard/contacts/invites/'
            });
            userStatusBar.shoppingCart = $('<span class="icon16 icon16-shoppingCart" />').iconStatus({
                count: 'user.shoppingCart',
                title: i18n.m717,
                href: '/dashboard/shopping/'
            });
            userStatusBar.all.prepend(userStatusBar.messages, userStatusBar.friendInvites, userStatusBar.shoppingCart)
            _user_status_bar.prepend(userStatusBar.all);
            userStatusBar.all.bind('updateAllStatus', function(){
                userStatusBar.messages.trigger('updateStatus');
                userStatusBar.friendInvites.trigger('updateStatus');
                userStatusBar.shoppingCart.trigger('updateStatus');
            });
            setInterval(updateAllStatus, UPDATE_USER_STATUS_INTERVAL);
            
        }
        $(window).resize(function(){
            var header_main_menu_end = $('#header_main_menu').offset().left + $('#header_main_menu').width();
            global.search_panel.css('left', header_main_menu_end - global.search_panel.width() + 40);
                
            if(user.role == global.user.role.guest){
                global.login_panel.css('right',$('#header_top').offset().left);
            //global.password_recovery.css('right',$('#header_top').offset().left);
            }
        });
    }
    $('a._target').live('click', function(){
        $(this).attr('target', '_blank');
    });
    
    if(swfobject.ua.pv[0] == 0) {
        $('.installFlash').css('display', 'block');
    }
    /*
    if(user.premiumType < 2 || !user.premiumType) {
        $(document).ears();
    }
    */
    /*
    $(window).resize(function(){
            $('.ears').each(function(index){
                if(!index){
                    $(this).css({
                        'left': $('#header_top').offset().left - 141 - 5
                    });
                } else {
                    $(this).css({
                        'left': $('#header_top').offset().left + $('#header_top').width() + 5
                    });
                }
            });
            
            $('#ears_center').css({
                'left' : $('#header_top').offset().left - 5
            });
        });
    */
    //TODO: need to find another solution
    if($.browser.msie && parseInt($.browser.version) == 8){
        var panel_center = $('.panelCenter'),
        panel_left = $('.panelLeft'),
        panel_right = $('.panelRight');
        function renderThis(){
            var _this = $(this);
            height =  _this.height();
            _this.height(height).height('auto');
        }            
        if(panel_center.length){
            panel_center.bind('resize', renderThis);        
        }
        if(panel_left.length){
            panel_left.bind('resize', renderThis);        
        }
        if(panel_right.length){
            panel_right.bind('resize', renderThis);        
        }
    }

    
    var options_feedback = {
        width: 500,
        height: 'auto',
        content: templates.openfilmFeedback,
        onComplete: false,
        onCleanup: false,
        title: i18n.m951,
        onComplete: function () {
        
            var _form = $('#openfilm_feedback_form'),
            validator  = _form.validate(formActions.openfilmFeedbackForm);
			
            $('a[href="#form_reset"]', _form).bind('click', function(event){
                event.preventDefault();
                validator.resetForm();
            });
        
        }
    };
    
    $('#openfilm_feedback').bind('click', function(event) {
        event.preventDefault();
        $.modalDialog(options_feedback);
    });


    // ads
    //setTimeout(function(){
    insertAds ($("div.ap"));
    //}, 1000);
    
// console.log
}


var updateAllStatus = function(){
    $.ajax({
        url: '/a/user-status/update/',
        success: function(data) {
            user.messages = data.messages;
            user.friendInvites = data.friend_invites;
            user.shoppingCart  = data.shopping_cart;
            userStatusBar.all.trigger('updateAllStatus');
        }
    });

}

function mustLogin(type)
{
    switch(type){
        case 'comment-add':
            return user.role == global.user.role.guest;
            break;
        case 'comment-vote':
            return user.role == global.user.role.guest;
            break;
        case 'comment-answer':
            return user.role == global.user.role.guest;
            break;
        case 'comment-report-spam':
            return user.role == global.user.role.guest;
            break;
        case 'user-add-as-friend':
            return user.role == global.user.role.guest;
            break;
        case 'user-block-user':
            return user.role == global.user.role.guest;
            break;
        case 'user-send-message':
            return user.role == global.user.role.guest;
            break;
        case 'video-rating':
            return user.role == global.user.role.guest;
            break;
        case 'video-quicklist':
            return user.role == global.user.role.guest;
            break;
        case 'channel-subscribe':
            return user.role == global.user.role.guest;
            break;
        case 'filmfestival-subscribe':
            return user.role == global.user.role.guest;
            break;
        case 'filmfestival-favorite':
            return user.role == global.user.role.guest;
            break;
        case 'chat-vote':
            return user.role == global.user.role.guest;
            break;
        case 'ask-questions':
            return user.role == global.user.role.guest;
            break;
        case 'video-upload':
            return user.role == global.user.role.guest;
            break;
        default:
            return true;
    }
    return false;
}

function mustConfirm(type)
{
    switch(type){
        case 'video-rating':
            return user.role == global.user.role.viewer;
            break;
        case 'user-add-as-friend':
            return user.role == global.user.role.viewer;
            break;
        case 'user-send-message':
            return user.role == global.user.role.viewer;
            break;
        case 'channel-subscribe':
            return user.role == global.user.role.viewer;
            break;
        case 'filmfestival-subscribe':
            return user.role == global.user.role.viewer;
            break;
        case 'filmfestival-favorite':
            return user.role == global.user.role.viewer;
            break;
        case 'comment-add':
            return user.role == global.user.role.viewer;
            break;
        case 'comment-vote':
            return user.role == global.user.role.viewer;
            break;
        case 'comment-answer':
            return user.role == global.user.role.viewer;
            break;
        case 'comment-report-spam':
            return user.role == global.user.role.viewer;
            break;
        default:
            return true;
    }
    return false;
}

BrowserDetect.init();
	
window.$.client = {
    os : BrowserDetect.OS,
    browser : BrowserDetect.browser
}; 
