
var OwUtils = function(){
    var langs = {};
    var messageTime = 3000;
    var $messageCont = $('<div class="ow_message_cont"></div>');
    var events = {};

    this.registry = {};

    $(function(){
    	$messageCont.appendTo(document.body);
    });

    this.message = function( message, type, paramTime ){
        var $messageNode = $('<div class="ow_message_node '+type+'" style="display:none;"><div><div><a class="close_button" href="javascript://" onclick="$(this).closest(\'.ow_message_node\').slideUp(200, function(){$(this).remove();})"></a>'+message+'</div></div></div>').appendTo($messageCont);
        if( paramTime == undefined ){
            paramTime = messageTime;
        }

        $messageNode.fadeIn(1000,
            function(){
                window.setTimeout(
                    function(){
                        $messageNode.fadeOut(1000,
                            function() {
                                $messageNode.remove();
                            }
                    );
                    }, paramTime
                );
            }
        );
    }

    this.error = function( message ){
    	this.message(message, 'error');
    };

    this.warning = function( message ){
    	this.message(message, 'warning');
    };

    this.info = function( message ){
    	this.message(message, 'info');
    };

    this.flagContent = function( entity, id, title, href, lang )
    {
        OW.registry['flag-panel-fb'] = OW.ajaxFloatBox("BASE_CMP_Flag", [entity, id, title, href, lang], {
            width: 315,
            title: OW.getLanguageText('base', 'flag_as')
        });
    };


    var loadedScriptFiles = {};
    this.loadScriptFiles = function( urlList, callback, options ){
        
        if ( $.isPlainObject(callback) ) {
            options = callback;
            callback = null;
        }
        
        var addScript = function(url) {
            return jQuery.ajax($.extend({
                dataType: "script",
                cache: true,
                url: url
            }, options || {})).done(function() {
                loadedScriptFiles[url] = true;
            });
        };
        
        if( urlList && urlList.length > 0 ) {
            var recursiveInclude = function(urlList, i) {
                if( (i+1) === urlList.length )
                {
                    addScript(urlList[i]).done(callback);
                    return;
                }

                addScript(urlList[i]).done(function() {
                    recursiveInclude(urlList, ++i);
                });
            };
            recursiveInclude(urlList, 0);
        } else {
            callback.apply(this);
        }
    };
    
    this.addScriptFiles = function( urlList, callback, once ) {
        if ( once === false ) {
            this.loadScriptFiles(urlList, callback);
            return;
        }
        
        $("script").each(function() {
            loadedScriptFiles[this.src] = true;
        });
        
        var requiredScripts = $.grep(urlList, function(url) {
            return !loadedScriptFiles[url];
        });

        this.loadScriptFiles(requiredScripts, callback);
    };

    this.addScript = function( script, scope, context )
    {
    	if (!script)
    	{
            return;
    	}

        context = context || window;
        scope = scope || window;

        Function('_scope', script).call(context, scope);
    },

    this.addCssFile = function( url )
    {
        if ( $('link[href="'+ $.trim(url) +'"]').length ) {
            return;
        }
        
        $('head').append($('<link type="text/css" rel="stylesheet" href="'+$.trim(url)+'" />'));
    },

    this.addCss = function( css ){
        $('head').append($('<style type="text/css">'+css+'</style>'));
    };

    this.getLanguageText = function(prefix, key, assignedVars)
    {
        if ( langs[prefix] === undefined ) {
                return prefix + '+' + key;
        }

        if ( langs[prefix][key] === undefined ) {
                return prefix + '+' + key;
        }

        var langValue = langs[prefix][key];

        if ( assignedVars ) {
                for( varName in assignedVars ) {
                        langValue = langValue.replace('{$'+varName+'}', assignedVars[varName]);
                }
        }

        return langValue;
    };

    this.registerLanguageKey = function(prefix, key, value)
    {
            if ( langs[prefix] === undefined ) {
                    langs[prefix] = {};
            }

            langs[prefix][key] = value;
    };

    this.inProgressNode = function(node)
    {
    	return $(node).inprogress();
    };

    this.activateNode = function(node)
    {
    	return $(node).activate();
    };

    this.showUsers = function(userIds, title)
    {
    	OW.Users.showUsers(userIds, title);
    },

    this.getActiveFloatBox = function getFloatBox()
    {
    	if ( typeof window.OWActiveFloatBox === 'undefined' )
    	{
    		return false;
    	}

    	return window.OWActiveFloatBox;
    },

    /**
     * Loads a component
     *
     * Examples:
     * 1:
     * OW.loadComponent(cmpClass, '.place_to_node');
     *
     * 2:
     * OW.loadComponent(cmpClass, function(){
     *     //onReady event
     *     //Add the html somewhere
     * });
     *
     * 3:
     * OW.loadComponent(cmpClass, [ p1, p2, ... ], '.place_to_node');
     *
     * 4:
     * OW.loadComponent(cmpClass, [ p1, p2, ... ], function(html){
     *     //onReady event
     *     //Add the html somewhere
     * });
     *
     * 5:
     * OW.loadComponent(cmpClass, [ p1, p2, ... ],
     * {
     *     onLoad: function(){},
     *     onError: function(){},
     *     onComplete: function(){},
     *     onReady: function( html )
     *     {
     *        //Add the html somewhere
     *     }
     * });
     *
     * @param string cmpClass
     *
     * Cmp class params or targetNode selector or targetNod HtmlElement or ready callback
     * @param array|string|HTMLElement|jQuery|function p1
     *
     * Options or targetNode selector or targetNod HtmlElement or ready callback
     * @param object|string|HTMLElement|jQuery|function p2
     */
    this.loadComponent = function( cmpClass, p1, p2 )
    {
        function isNode( node )
        {
            return typeof node === 'string' || node.jquery || node.nodeType
        }

        var params = [], options = {};

        if ( isNode(p2) )
        {
            options.place = $(p2);
        }
        else if ( $.isPlainObject(p2) )
        {
            options = p2;
        }
        else if ( $.isFunction(p2) )
        {
            options.onReady = p2;
        }

        if ( isNode(p1) )
        {
            options.place = $(p1);
        }
        else if ( $.isArray(p1) || $.isPlainObject(p1) )
        {
            params = p1;
        }
        else if ( $.isFunction(p1) )
        {
            options.onReady = p1;
        }

    	options = $.extend({}, {
            place: false,
            scope: window,
            context: window,
            addClass: '',
            onLoad: function() {},
            onReady: function( r ) {},
            onError: function( r ) {},
            onComplete: function( r ) {}
    	}, options);

        var rsp = this.ajaxComponentLoaderRsp,
            jsonParams = JSON.stringify(params),
            $preloader = false;

        if ( options.place )
        {
            $preloader = $('<div class="ow_ajaxloader_preloader ow_preloader_content ' + options.addClass + '"></div>');
            $(options.place).html($preloader);
        }

        var ajaxOptions = {
            url: rsp + '?cmpClass=' + cmpClass + '&r=' + Math.random(),
            dataType: 'json',
            type: 'POST',
            data: {params: jsonParams},
            error: function(r)
            {
                options.onError(r);
            },
            complete: function(r)
            {
                options.onComplete(r);
            },
            success: function(markup)
            {
                var contentHtml = markup.content, $contentHtml = $(contentHtml);

                if ( !$contentHtml.length )
                {
                    contentHtml = '<span>' + contentHtml + '</span>';
                    $contentHtml = $(contentHtml)
                }

                if ( $preloader )
                {
                    $preloader.replaceWith($contentHtml);
                }

                options.onReady($contentHtml);

                OW.bindAutoClicks($contentHtml);
                OW.bindTips($contentHtml);

                if (markup.styleSheets)
                {
                    $.each(markup.styleSheets, function(i, o)
                    {
                        OW.addCssFile(o);
                    });
                }

                if (markup.styleDeclarations)
                {
                    OW.addCss(markup.styleDeclarations);
                }

                if (markup.beforeIncludes)
                {
                    OW.addScript(markup.beforeIncludes, options.scope, options.context);
                }

                if (markup.scriptFiles)
                {

                    OW.addScriptFiles(markup.scriptFiles, function()
                    {
                        if (markup.onloadScript)
                        {
                            OW.addScript(markup.onloadScript, options.scope, options.context);
                            options.onLoad();
                        }
                    });
                }
                else
                {
                    if (markup.onloadScript)
                    {
                        OW.addScript(markup.onloadScript, options.scope, options.context);
                    }
                    options.onLoad();
                }
            }
	};

    	$.ajax(ajaxOptions);
    },

    this.ajaxFloatBox = function(cmpClass, params, options)
    {
    	params = params || [];

    	options = options || {};
    	options = $.extend({}, {
            title: '',
            width: false,
            height: false,
            top: false,
            left: false,
            iconClass: false,
            addClass: false,
            layout: 'default',
            $preloader: null,
            scope: {},
            context: null,
            onLoad: function(){},
            onReady: function(){},
            onError: function(){},
            onComplete: function(){}
    	}, options);

    	var floatBox = new OW_FloatBox({
            $title: options.title,
            width: options.width,
            height: options.height,
            top: options.top,
            left: options.left,
            icon_class: options.iconClass,
            addClass: options.addClass,
            layout: options.layout,
            $preloader: options.$preloader
        });

        options.scope = $.extend({floatBox: floatBox}, options.scope);
        options.context = options.context || floatBox;

        this.loadComponent(cmpClass, params,
        {
            scope: options.scope,
            context: options.context,
            onLoad: options.onLoad,
            onError: options.onError,
            onComplete: options.onComplete,
            onReady: function( r )
            {
                floatBox.setContent(r);

                if ( $.isFunction(options.onReady) )
            	{
                    options.onReady.call(this, r);
            	}
            }
        })

    	return floatBox;
    };

    this.bind = function(type, func)
	{
		if (events[type] == undefined)
		{
			events[type] = [];
		}

		events[type].push(func);

	};

	this.trigger = function(type, params, applyObject)
	{
		if (events[type] == undefined) {
			return false;
		}

		applyObject = applyObject || this;
		params = params || [];

		if ( !$.isArray(params) )
		{
			params = [params];
		}

		for (var i = 0, func; func = events[type][i]; i++)
		{
			if (func.apply(applyObject, params) === false)
			{
				return false;
			}
		}

		return true;
	};

	this.unbind = function( type )
	{
		if (events[type] == undefined) {
			return false;
		}

		events[type] = [];
	};

	this.editLanguageKey = function( prefix, key, success )
	{
        var fb = OW.ajaxFloatBox("BASE_CMP_LanguageValueEdit", [prefix, key, true], {width: 520, title: this.getLanguageText('admin', 'edit_language')});

        OW.bind("admin.language_key_edit_success", function( e ) {
            fb.close();
            OW.unbind("admin.language_key_edit_success");
            success(e);
        });
	};

    this.authorizationLimitedFloatbox = function( message )
    {
        OW.ajaxFloatBox(
            "BASE_CMP_AuthorizationLimited",
            {message: message},
            {width: 500, title: this.getLanguageText('base', 'authorization_limited_permissions')}
        );
    };

    this.bindAutoClicks = function(context){
    	var autoClicks;

    	if ( context )
    	{
    		autoClicks = $('.form_auto_click', context);
    	}
    	else
    	{
    		autoClicks = $('.form_auto_click');
    	}

        $.each(autoClicks, function(i,o){
            var context = $(o);
            $('textarea.invitation', context)
            .bind('focus.auto_click', {context:context},
                function(e){
                    $('.ow_submit_auto_click', e.data.context).show();
                    $(this).unbind('focus.auto_click')
                }
            );/*
            .bind('keyup.auto_click',
                function(){
                    if( $(this).val() != '' ){
                        $(this).unbind('focus.auto_click').unbind('keyup.auto_click').unbind('mouseup.auto_click').unbind('blur.auto_click');
                    }
                }
            )
            .bind('mouseup.auto_click',
                function(){
                    if( $(this).val() != '' ){
                        $(this).unbind('focus.auto_click').unbind('keyup.auto_click').unbind('mouseup.auto_click').unbind('blur.auto_click');
                    }
                }
            )
            .bind('blur.auto_click', {context:context},
                function(e){
                    if( $(this).hasClass('invitation') ){
                        $('.ow_submit_auto_click', e.data.context).hide();
                    }
                }
            );*/
        });
    };

    this.initWidgetMenu = function( items ){
        var $toolbarCont = null;
        var $contex = null;
        var condIds = [];
        var linkIds = [];
        $.each( items, function(key, value){
                if( $toolbarCont === null ){
                    $contex = $('#'+value['contId']).closest('.ow_box, .ow_box_empty');
                    $toolbarCont = $('.ow_box_toolbar_cont', $contex);
                }
                condIds.push('#'+value['contId']);
                linkIds.push('#'+value['id']);
            }
        );

        var contIdSelector = $(condIds.join(','));
        var linkIdSelector = $(linkIds.join(','));

        $.each( items, function(key, value){
                $('#'+value['id']).bind('click', {value:value},
                    function(e){
                        contIdSelector.hide();
                        $('#'+e.data.value.contId).show();
                        linkIdSelector.removeClass('active');
                        $(this).addClass('active');

                        if( e.data.value.toolbarId != undefined ){
                            if( e.data.value.toolbarId ){
                                if( $toolbarCont.length === 0 ){
                                    $toolbarCont = $('<div class="ow_box_toolbar_cont"></div>');
                                    $contex.append($toolbarCont);
                                }
                                $toolbarCont.html($('#'+e.data.value.toolbarId).html());
                            }
                            else{
                                if( $toolbarCont.length !== 0 ){
                                    $toolbarCont.remove();
                                    $toolbarCont = [];
                                }
                            }
                        }
                    }
                );
            }
        );
    };

    this.showTip = function( $el, params ){
        params = params || {};
        params = $.extend({side:'top', show:null, width:null, timeout:0, offset:5, hideEvent: null}, params);

        var showTipN = function(){

            var $rootEl = $el.data('owTip');
            var coords = $el.offset();

            switch( params.side )
            {
                case 'top':
                    var left = coords.left + $el.outerWidth()/2 - $rootEl.outerWidth()/2;
                    var top = coords.top - $rootEl.outerHeight() - params.offset;
                    break;

                case 'bot':
                    var left = coords.left + $el.outerWidth()/2 - $rootEl.outerWidth()/2;
                    var top = coords.top + $el.outerHeight() + params.offset;
                    break;

                case 'right':
                    var left = coords.left + $el.outerWidth() + params.offset;
                    var top = coords.top + $el.outerHeight()/2 - $rootEl.outerHeight()/2;
                    break;

                case 'left':
                    var left = coords.left - $rootEl.outerWidth() - params.offset;
                    var top = coords.top + $el.outerHeight()/2 - $rootEl.outerHeight()/2;
                    break;

                 default:
                     return;
            }

            $rootEl.css({left:left, top:top});

            var tod = setTimeout( function(){
                $el.data('owTip').show( 1,
                    function(){
                        if( params.hideEvent ){
                            $el.bind(params.hideEvent, function(){OW.hideTip($el)});
                        }
                        $el.data('owTipStatus', true);
                        if( $el.data('owTipHide') == true ){
                            OW.hideTip($el);
                        }
                    }
                );
            }, params.timeout);
            $el.data('tod', tod)
        }

        if( $el.data('owTip') ){
            if( $el.data('owTipStatus') == true ){
                return;
            }
            showTipN();
            return;
        }

        var showContent;

        if( params.show != null ){
            showContent = ( typeof(params.show) == 'string' ? params.show : params.show.html() );
        }
        else{
            if( !$el.attr('title') ){
                return;
            }

            showContent = '<span class="ow_tip_title">'+$el.attr('title')+'</span>';
        }

        var $rootEl = $('<div class="ow_tip ow_tip_'+params.side+'"></div>').css({display:'none'}).append($('<div class="ow_tip_arrow"><span></span></div><div class="ow_tip_box">'+ showContent +'</div>'));
        if( params.width != null ){
            $rootEl.css({width:params.width});
        }
        $('body').append($rootEl);

        $el.removeAttr('title');
        $el.data('owTip', $rootEl);
        showTipN();
    };

    this.hideTip = function( $el ){
        if( $el.data('tod') ){
            clearTimeout($el.data('tod'));
        }

        if( $el.data('owTip') && $el.data('owTipStatus') == true ){
            $el.data('owTip').hide();
            $el.data('owTipStatus', false);
            $el.data('owTipHide', false);
        }
    };

    this.bindTips = function( $context ){
      //$('*[title]', $context).each( function(i, o){$(o).hover(function(){OW.showTip($(this), {timeout:200})}, function(){OW.hideTip($(this))})});
      $('*[title]', $context).each( function(i, o){
          $(o).on('mouseenter', function(){ OW.showTip($(this), {timeout:200}); });
          $(o).on('mouseleave', function(){ OW.hideTip($(this)); });
      });
    };

    this.resizeImg = function($context, params){
        if( !params.width ){
            return;
        }

        $( 'img', $context ).each(function(){
            $(this).load(
                function(){
                    if( $(this).data('imgResized') != true){
                        var $fakeImg = $(this).clone();
                        $fakeImg.css({width:'auto',height:'auto',visibility:'hidden',position:'absolute',left:'-9999px'}).removeAttr('width').removeAttr('height');
                        $(document.body).append ($fakeImg);
                        var self = this;
                        $fakeImg.load(function(){
                            var width = $(this).width();
                            if( width < params.width  ){
                                $(self).css({width:'auto', height:'auto'});
                            }
                            else if( $(self).width() >= params.width ){
                                $(self).css({width:params.width, height:'auto'});
                            }
                            $(self).data('imgResized', true);
                            $(this).remove();
                        });
                    }
                }
            );
        });
    };

    this.showImageInFloatBox = function( src )
    {
        var floatBox = new OW_FloatBox({layout: 'empty'});
        var $fakeImageC = $('<div></div>');
        var $fakeImg = $('<img src="'+src+'" />');
        $fakeImageC.append($fakeImg);
        $fakeImageC.css({visibility:'hidden',position:'absolute',left:'-9999px'});
        $(document.body).append ($fakeImageC);

        $fakeImg.load(function(){
            var width = $fakeImg.width();
            var height = $fakeImg.height();

            if( width > 340 || height > 220 ){

                if( width > 800 )
                {
                    $fakeImg.css({width:'800px', height:'auto'});
                    width = 800;
                }
                else if( $fakeImg.height > 600 )
                {
                    height = 600;
                    $fakeImg.css({height:'600px', width:'auto'});
                }

                floatBox.setContent($fakeImg);
            }
            else{
                floatBox.setContent($fakeImg);
            }

            floatBox.fitWindow({
                "width": width,
                "height": height
            });

            floatBox.bind('close', function(){
                $fakeImageC.remove();
            });
        });
    }
}


//Enable / Disable node
jQuery.fn.extend({
	inprogress: function() {
		this.each(function()
		{
			var $this = jQuery(this).addClass('ow_inprogress');
			this.disabled = true;

			if ( this.tagName != 'INPUT' && this.tagName != 'TEXTAREA' && this.tagName != 'SELECT' )
			{
				this.jQuery_disabled_clone = $this.clone().removeAttr('id').removeAttr('onclick').get(0);

				$this.hide()
					.bind('unload', function(){
						$this.activate();
					})
					.after(this.jQuery_disabled_clone);
			}
		});

		return this;
	},

	activate: function() {
		this.each(function()
		{
			var $this = jQuery(this).removeClass('ow_inprogress');
			this.disabled = false;

			if ( this.jQuery_disabled_clone )
			{
				jQuery(this.jQuery_disabled_clone).remove();
				this.jQuery_disabled_clone = null;

				jQuery(this)
					.unbind('unload', function(){
						$this.activate();
					})
					.show();
			}
		});

		return this;
	}
});

window.OW = new OwUtils();

function lg(o){
	console.log(o);
}

$( //8aa: resize fullsize images to fit to it's parendt width
	function (){
		if(typeof($) == 'undefined') return;

		$('.fullsize-image').hide();
		var node = $('.fullsize-image')[0];

		while( node = $(node).parent()[0]){

			if( node.tagName != 'DIV'){
				continue;
			}

			if($('.fullsize-image').width() > parseInt($(node).innerWidth()))
				$('.fullsize-image').width( (parseInt($(node).innerWidth()) - 10) + 'px' );

			$('.fullsize-image').show();
			break;
		}

	}
);


/**
 * Float box constructor.
 *
 * @param string|jQuery $title
 * @param string|jQuery $contents
 * @param jQuery $controls
 * @param object position {top, left} = center
 * @param integer width = auto
 * @param integer height = auto
 */
function OW_FloatBox(options)
{
    var fl_box = this;
    var fb_class;
    this.parentBox = OW.getActiveFloatBox();
    this.options = options;
    this.verion = 2;

    this.events = {close: [], show: []};

    if (typeof document.body.style.maxHeight === 'undefined') { //if IE 6
            jQuery('body').css({height: '100%', width: '100%'});
            jQuery('html').css('overflow', 'hidden');
            if (document.getElementById('floatbox_HideSelect') === null)
            { //iframe to hide select elements in ie6
                jQuery('body').append('<iframe id="floatbox_HideSelect"></iframe><div id="floatbox_overlay"></div>');
                fb_class = OW_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
                jQuery('#floatbox_overlay').addClass(fb_class);
            }
    }
    else { //all others
        if (document.getElementById('floatbox_overlay') === null)
        {
            jQuery('body').append('<div id="floatbox_overlay"></div>');
            fb_class = OW_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
            jQuery('#floatbox_overlay').addClass(fb_class).click(function()
            {
                fl_box.close();
            });
        }
    }

    options.layout = options.layout || 'default';

    jQuery('body').addClass('floatbox_nooverflow');

    var activeCanvas = jQuery('.floatbox_canvas_active');
    var fbContext = jQuery('#floatbox_prototype').find('.' + options.layout);

    this.$canvas = jQuery('.floatbox_canvas', fbContext).clone().appendTo(document.body);
    this.$preloader = jQuery('.floatbox_preloader_container', this.$canvas);

    if ( options.addClass )
    {
        this.$canvas.addClass(options.addClass);
    }

    activeCanvas.removeClass('floatbox_canvas_active');
    this.$canvas.addClass('floatbox_canvas_active');

    if (this.parentBox)
    {
        this.$canvas.addClass('floatbox_canvas_sub');
        this.parentBox.bind('close', function()
        {
            fl_box.close();
        });
    }

    this.$canvas.click(function(e)
    {
        if ( $(e.target).is(this) )
        {
            fl_box.close();
        }
    });

    this.$container = jQuery('.floatbox_container', this.$canvas);

    if ( options.$title )
    {
        if (typeof options.$title == 'string')
        {
            options.$title = jQuery('<span>'+options.$title+'</span>');
        }
        else
        {
            this.$title_parent = options.$title.parent();
        }

        this.$header = jQuery('.floatbox_header', this.$container);

        var $fbTitle = jQuery('.floatbox_cap', this.$header)
            .find('.floatbox_title')
                .append(options.$title);
    }

    /*if (typeof options.icon_class == 'string')
    {
    	$fbTitle.addClass(options.icon_class);
    }*/

    this.$body = jQuery('.floatbox_body', this.$container);
    this.$bottom = jQuery('.floatbox_bottom', this.$container);

    this.showPreloader(options.$preloader || null);

    if (options.$controls)
    {
        if (typeof options.$controls == 'string')
        {
            options.$controls = jQuery('<span>'+options.$controls+'</span>');
        }
        else
        {
            this.$controls_parent = options.$controls.parent();
        }

        this.$bottom.append(options.$controls);
    }


    if (options.width)
            this.$container.css("width", options.width);
    if (options.height)
            this.$body.css("height", options.height);

    jQuery('.close', this.$header)
        .one('click', function()
        {
            fl_box.close();
            return false;
        });

    this.esc_listener =
    function(event) {
            if (event.keyCode == 27) {
                    fl_box.close();
                    return false;
            }
            return true;
    }

    jQuery(document).bind('keydown', this.esc_listener);

    if (options.left)
    {
        this.$container.css('margin-left', options.left);
    }

    if (options.top)
    {
        this.$container.css('margin-top', options.top);
    }

    if ( options.$contents )
    {
        this.setContent(options.$contents);
    }

    window.OWActiveFloatBox = this;
}

OW_FloatBox.version = 3;
OW_FloatBox.detectMacXFF = function()
{
    var userAgent = navigator.userAgent.toLowerCase();
    return (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1);
}

OW_FloatBox.prototype = {

    fitWindow: function( params )
    {
        params = params || {};
        params = $.extend({
            "width": null,
            "height": null,
            "top": null,
            "left": null
        }, params);

        var css = {};

        if ( params.width )
        {
            this.options.width = params.width;
            css.width = params.width;
        }

        if ( params.height )
        {
            this.options.height = params.height;
            css.height = params.height;
        }

        if ( params.top )
        {
            this.options.top = params.top;
            css.marginTop = params.top;
        }

        if ( params.left )
        {
            this.options.left = params.left;
            css.marginLeft = params.left;
        }

        this.$container.css(css);
    },

    setContent: function( $contents )
    {
        var self = this;

        if (typeof $contents == 'string')
        {
            var $contentsNode = jQuery($contents);

            if ( !$contentsNode.length )
            {
                $contentsNode = jQuery('<span>' + $contents + '</span>');
            }

            $contents = jQuery($contentsNode);
        }
        else
        {
            this.$contents_parent = $contents.parent();
        }

        var width, fakeNode;

        if ( !this.options.width )
        {
            fakeNode = $('<div></div>').insertAfter(this.$body);
            fakeNode.attr('class', this.$body.attr('class'));
            fakeNode.css({position: 'absolute',top: -2000, visibility: 'hidden'});
            fakeNode.append($contents);
            width = fakeNode.outerWidth();
        }
        else
        {
            width = this.options.width;
        }

        this.$body.empty().append($contents);

        if ( fakeNode )
        {
            fakeNode.remove();
        }

        this.hidePreloader();

        this.fitWindow({width: width});

        window.setTimeout(function(){
            self.trigger('show');
        });
    },

    // OLD
    /*showPreloader: function( preloaderContent )
    {
        var css = {};

        if ( preloaderContent )
        {
            if ( typeof preloaderContent == 'string' )
            {
                preloaderContent = jQuery('<div class="floatbox_string_preloader"><span>' + preloaderContent + '</span></div>');
            }

            this.$preloader.html(preloaderContent);
        }

        this.$canvas.addClass('ow_floatbox_loading');


        this.$preloader.css('visibility', 'hidden');

        css.marginTop = ( jQuery(window).height() / 2 ) - ( this.$preloader.height() / 2 + 100);
        css.visibility = 'visible';

        this.$preloader.css(css);
    },*/

    showPreloader: function( preloaderContent )
    {
        if ( preloaderContent )
        {
            if ( typeof preloaderContent == 'string' )
            {
                preloaderContent = jQuery('<div class="floatbox_string_preloader"><span>' + preloaderContent + '</span></div>');
            }

            this.$preloader.html(preloaderContent);
        }

        this.$canvas.addClass('ow_floatbox_loading');
    },

    hidePreloader: function()
    {
        this.$canvas.removeClass('ow_floatbox_loading');
    },

    close: function()
    {
        if (this.trigger('close') === false) {
                return false;
        }

        jQuery(document).unbind('keydown', this.esc_listener);

        if (this.$title_parent && this.$title_parent.length)
        {
            this.$title_parent.append(
                jQuery('.floatbox_title', this.$header).children()
            );
        }

        if (this.$contents_parent && this.$contents_parent.length)
        {
            this.$contents_parent.append(this.$body.children());
        }

        if (this.$controls_parent && this.$controls_parent.length)
        {
            this.$controls_parent.append(this.$bottom.children());
        }

        this.$canvas.remove();

        if (jQuery('.floatbox_canvas:visible').length === 0)
        {
            jQuery('html, body').removeClass('floatbox_nooverflow');
            jQuery('#floatbox_overlay, #floatbox_HideSelect').remove();
        }

        window.OWActiveFloatBox = this.parentBox;

        return true;
    },

    bind: function(type, func)
    {
            if (this.events[type] == undefined) {
                    throw 'form error: unknown event type "'+type+'"';
            }

            this.events[type].push(func);

    },

    trigger: function(type, params)
    {
            if (this.events[type] == undefined) {
                    throw 'form error: unknown event type "'+type+'"';
            }

            params = params || [];

            for (var i = 0, func; func = this.events[type][i]; i++) {
                    if (func.apply(this, params) === false) {
                            return false;
                    }
            }

            return true;
    }
}


/* OW Forms */

var OwFormElement = function( id, name ){
    this.id = id;
    this.name = name;
    this.input = document.getElementById(id);
    this.validators = [];
}

OwFormElement.prototype = {

    validate: function(){

        var error = false;
        var errorMessage = '';

        try{
            for( var i = 0; i < this.validators.length; i++ ){
                this.validators[i].validate(this.getValue());
            }
        }catch (e) {
            error = true;
            this.showError(e);
            errorMessage = e;
        }

        if( error ){
            throw errorMessage;
        }
    },

    addValidator: function( validator ){
        this.validators.push(validator);
    },

    getValue: function(){
        return $(this.input).val();
    },

    setValue: function( value ){
        $(this.input).val(value);
    },

    resetValue: function(){
        $(this.input).val('');
    },

    showError: function( errorMessage ){
        $('#'+this.id+'_error').append(errorMessage).fadeIn(50);
    },

    removeErrors: function(){
        $('#'+this.id+'_error').empty().fadeOut(50);
    }
}

var OwForm = function( params ){
    $.extend(this, params);
    this.form = document.getElementById(this.id);
    this.elements = {};
    var actionUrl = $(this.form).attr('action');
    this.actionUrl = ( !actionUrl ? location.href : actionUrl );
    this.showErrors = true;
    this.events = {
        submit:[],
        success:[]
    }
};

OwForm.prototype = {

    addElement: function( element ){
        this.elements[element.name] = element;
    },

    getElement: function( name ){
        if( this.elements[name] === undefined ){
            return null;
        }

        return this.elements[name];
    },

    validate: function(){

        var error = false;
        var element = null;
        var errorMessage;

        $.each( this.elements,
            function(index, data){
                try{
                    data.validate();
                }catch (e){
                    error = true;

                    if( element == null ){
                        element = data;
                        errorMessage = e;
                    }
                }
            }
            );

        if( error ){
            element.input.focus();

            if( this.validateErrorMessage ){
                throw this.validateErrorMessage;
            }else{
                throw errorMessage;
            }
        }
    },

    bind: function( event, fnc ){
        this.events[event].push(fnc);
    },

    sucess: function( fnc ){
        this.bind('success', fnc);
    },

    submit: function( fnc ){
        this.bind('submit', fnc);
    },

    trigger: function( event, data ){
        if( this.events[event] == undefined || this.events[event].length == 0 ){
            return;
        }
        
        var result = undefined, returnVal;

        for( var i = 0; i < this.events[event].length; i++ ){
            
            returnVal = this.events[event][i].apply(this.form, [data]);
            if(returnVal === false || returnVal === true ){
                result = returnVal;
            }
        }
        
        if( result !== undefined ){
            return result;
        }
    },

    getValues: function(){

        var values = {};

        $.each(this.elements,
            function( index, data ){
                values[data.name] = data.getValue();
            }
            );

        return values;
    },

    setValues: function( values ){

        var self = this;

        $.each( values,
            function( index, data ){
                if(self.elements[index]){
                    self.elements[index].setValue(data);
                }
            }
            );
    },

    resetForm: function(){
        $.each( this.elements,
            function( index, data ){
                data.resetValue();
            }
            );
    },

    removeErrors: function(){

        $.each( this.elements,
            function( index, data ){
                data.removeErrors();
            }
            );
    },

    submitForm: function(){

        var self = this;

        this.removeErrors();

        try{
            this.validate();
        }catch(e){
            if( this.showErrors ){
                OW.error(e);
            }
            return false;
        }

        var dataToSend = this.getValues();
        if( self.trigger('submit', dataToSend) === false ){
            return false;
        }

        var buttons = $('input[type=button], input[type=submit], button', '#' + this.id).addClass('ow_inprogress');

        if( this.ajax ){
            OW.inProgressNode(buttons);
            var postString = '';

            $.each( dataToSend, function( index, data ){
                if ( $.isArray(data) || $.isPlainObject(data) ) {
                    $.each(data, function (key, value){
                        postString += index + '[' + key + ']=' + encodeURIComponent(value) + '&';
                    });
                }
                else{
                    postString += index + '=' + encodeURIComponent(data) + '&';
                }
            } );

            $.ajax({
                type: 'post',
                url: this.actionUrl,
                data: postString,
                dataType: self.ajaxDataType,
                success: function(data){
                    if(self.reset){
                        self.resetForm();
                    }
                    self.trigger('success', data);
                },
                error: function( XMLHttpRequest, textStatus, errorThrown ){
                    OW.error(textStatus);
                    throw textStatus;
                },
                complete: function(){
                    OW.activateNode(buttons);
                }
            });

            return false;
        }

        $.each(this.elements,
            function( i, o ){
                if( $(o.input).hasClass('invitation') ){
                    $(o.input).attr('disabled', 'disabled');
                }
            }
            );

        return true;
    }
}

owForms = {};

// custom fields
var addInvitationBeh = function( formElement, invitationString ){
    formElement.invitationString = invitationString;

    formElement.getValue = function(){
        var val = $(this.input).val();
        if( val != '' && val != this.invitationString ){
            $(this.input).removeClass('invitation');
            return val;
        }
        else{
            return '';
        }
    };

    var parentResetValue = formElement.resetValue;

    formElement.resetValue = function(){
        parentResetValue.call(this);

        $(this.input).addClass('invitation');
        $(this.input).val(invitationString);
    };

    $(formElement.input
        ).bind('focus.invitation', {formElement:formElement},
            function(e){
                el = $(this);
                el.removeClass('invitation');
                if( el.val() == '' || el.val() == e.data.formElement.invitationString){
                    el.val('');
                    //hotfix for media panel
                    if( 'htmlarea' in el.get(0) ){
                        el.unbind('focus.invitation').unbind('blur.invitation');
                        el.get(0).htmlarea();
                        el.get(0).htmlareaFocus();
                    }
                }
                else{
                    el.unbind('focus.invitation').unbind('blur.invitation');
                }
            }
        )/*.bind('blur.invitation', {formElement:formElement},
            function(e){
                el = $(this);
                if( el.val() == '' || el.val() == e.data.formElement.invitationString){
                    el.addClass('invitation');
                    el.val(e.data.formElement.invitationString);
                }
                else{
                    el.unbind('focus.invitation').unbind('blur.invitation');
                }
            }
    );*/
}

var OwTextField = function( id, name, invitationString ){
    var formElement = new OwFormElement(id, name);
    if( invitationString ){
        addInvitationBeh(formElement, invitationString);
    }
    return formElement;
}

var OwTextArea = function( id, name, invitationString ){
    var formElement = new OwFormElement(id, name);
    if( invitationString ){
        addInvitationBeh(formElement, invitationString);
    }
    return formElement;
}

var OwWysiwyg = function( id, name, invitationString ){
    var formElement = new OwFormElement(id, name);
    formElement.input.focus = function(){this.htmlareaFocus();};
    addInvitationBeh(formElement, invitationString);
    formElement.resetValue = function(){$(this.input).val('');$(this.input).keyup();};
    formElement.getValue = function(){
                var val = $(this.input).val();
                if( val != '' && val != '<br>' && val != '<div><br></div>' && val != this.invitationString ){
                    $(this.input).removeClass('invitation');
                    return val;
                }
                else{
                    return '';
                }
            };

    return formElement;
}

var OwRadioField = function( id, name ){
    var formElement = new OwFormElement(id, name);

    formElement.getValue = function(){
        var value = $("input[name='"+this.name +"']:checked", $(this.input.form)).val();
        return ( value == undefined ? '' : value );
    };

    formElement.resetValue = function(){
        $("input[name='"+this.name +"']:checked", $(this.input.form)).removeAttr('checked');
    };

    formElement.setValue = function(value){
        $("input[name='"+ this.name +"'][value='"+value+"']", $(this.input.form)).attr('checked', 'checked');
    };

    return formElement;
}

var OwCheckboxGroup = function( id, name ){
    var formElement = new OwFormElement(id, name);

    formElement.getValue = function(){
        var $inputs = $("input[name='"+ this.name +"[]']:checked", $(this.input.form));
        var values = [];

        $.each( $inputs, function(index, data){
                if( this.checked == true ){
                    values.push($(this).val());
                }
            }
        );

        return values;
    };

    formElement.resetValue = function(){
        var $inputs = $("input[name='"+ this.name +"[]']:checked", $(this.input.form));

        $.each( $inputs, function(index, data){
                $(this).removeAttr('checked');
            }
        );
    };

    formElement.setValue = function(value){
        for( var i = 0; i < value.length; i++ ){
            $("input[name='"+ this.name +"[]'][value='"+value[i]+"']", $(this.input.form)).attr('checked', 'checked');
        }
    };

    return formElement;
}

var OwCheckboxField = function( id, name ){
    var formElement = new OwFormElement(id, name);

    formElement.getValue = function(){
        var $input = $("input[name='"+this.name+"']:checked", $(this.input.form));
        if( $input.length == 0 ){
            return '';
        }
        return 'on';
    };

    formElement.setValue = function(value){
        var $input = $("input[name='"+this.name+"']:checked", $(this.input.form));
        if( value ){
            $input.attr('checked', 'checked');
        }
        else{
            $input.removeAttr('checked');
        }
    };
    formElement.resetValue = function(){
        var $input = $("input[name='"+this.name+"']:checked", $(this.input.form));
        $input.removeAttr('checked');
    };

    return formElement;
}

var OwRange = function( id, name ){
    var formElement = new OwFormElement(id, name);

    formElement.getValue = function(){
        var $inputFrom = $("select[name='"+ this.name +"[from]']");
        var $inputTo = $("select[name='"+ this.name +"[to]']");
        var values = [];

        values.push($inputFrom.val());
        values.push($inputTo.val());

        return values;
    };

    formElement.setValue = function(value){
        var $inputFrom = $("select[name='"+ this.name +"[from]']");
        var $inputTo = $("select[name='"+ this.name +"[to]']");

        if( value[1] ){
            $("option[value='"+ value[1] +"']", $inputFrom).attr('selected', 'selected');
        }

        if( value[2] ){
            $("option[value='"+ value[2] +"']", $inputTo).attr('selected', 'selected');
        }

    };

    return formElement;
}


/* end of forms */


/* Drag and drop fix */

DND_InterfaceFix = new (function(){

	var embed = function(context){
		var $context = $(context);
		var cWidth = $context.innerWidth();

		var configureEmbed = function($embed) {
			var embed = $embed.get(0);
			if ( embed.default_width === undefined || embed.default_width === null ) {
				embed.default_width = $embed.width();
			}

			if ( cWidth < embed.default_width )
			{
				$embed.css('width', '100%');
			}
			else
			{
				$embed.css('width', embed.default_width + 'px');
			}

                        $embed.attr('wmode', 'transparent');
    	};

    	var configureObject = function($object) {
    		$object.css('width', '100%');
    	};

    	$('embed', context).each(function(){
    		var $node = $(this).hide();
    		configureEmbed($node);
    		$node.show();
    	});

    	$('object', context).each(function() {
    		var $node = $(this).hide(), $embeds = $('embed', this);

    		configureObject($node);
		if ( $embeds.length )
		{
		    configureEmbed($embeds);
		}
    		$node.show();
    	});
	};

	var image = function(context) {

		var $context = $(context), cWidth;
		var cWidth = $context.innerWidth();

		if ( !cWidth )
		{
		    return;
		}

		var resize = function(img) {
			var $img = $(img);

			if ( img.default_width ) {
				img.default_width = $img.width();
			}

			if ( img.default_width > cWidth ) {
				$img.css('width', '100%');
			} else {
				$img.css('width', img.default_width);
			}
		};

		$context.find('img').each(function(){
                    $(this).css('max-width', '100%');
                    if (this.naturalWidth == 0) {
                        $(this).load(function(){
                            resize(this);
                        });
                    } else {
                        resize(this);
                    }
		});
	};


	var iframe = function(context)
        {
            var $iframe = $('iframe', context);
            var cWidth = $(context).innerWidth();
            $iframe.each(function(i, o)
            {
                var $o = $(o), url, wmode;

                if ( $o.width() > cWidth )
                {
                    $o.css('width', '100%');
                }

                url = $(this).attr("src");

                if ( !url ) return;

                wmode = "wmode=transparent";
                if ( url.indexOf("?") != -1)
                {
                    $o.attr("src", url + "&" + wmode);
                }
                else
                {
                    $o.attr("src", url + "?" + wmode);
                }
            });
	};

	this.fix = function(context) {
		this.embed(context);
		this.image(context);
		this.iframe(context);
	};

	this.embed = function(context) {
		$(context).each(function(){
			embed(this);
		})
	};

	this.image = function(context) {
		$(context).each(function(){
			image(this);
		});
	};

	this.iframe = function(context) {
		$(context).each(function(){
			iframe(this);
		});
	};

})();

/* Comments */
var OwComments = function( params ){
    $.extend(this, params);
    this.$cmpContext = $('#' + this.contextId);
    var self = this;
    var sleeping = false;
    this.eventParams = {entityType:self.entityType, entityId:self.entityId, customId:self.customId};
    this.submitHandler = function(){OW.error('FORM IS NOT INITIALIZED!');};
    this.attachmentInProgressHandler = function(){OW.error(params.labels.attachmentLoading);};
    
    var checkAddress = function( data ){
        if( data.customId && data.customId != self.customId  ){
            return false;
        }
        
        return ( data.entityType == self.entityType && data.entityId == self.entityId );
    };
    
    OW.bind('base.comments_sleep', 
        function(data){
            if( checkAddress(data) ){
                sleeping = true;
                if( this.userAuthorized ){
                    self.moveForm();
                }
                self.$cmpContext.hide();
            }
        }
    );
    
    OW.bind('base.comments_wakeup', 
        function(data){
            if( checkAddress(data) ){
                sleeping = false;
                self.$cmpContext.show();
            }
        }
    );
    
    OW.bind('base.comments_destroy', 
        function(data){
            if( checkAddress(data) ){
                self.$cmpContext.remove();
            }
        }
    );
    
    if( !this.userAuthorized ){
        return;
    }
    
    this.$textarea = $('#'+this.textAreaId);
    this.$attchCont = $('#'+this.attchId);
    this.$formWrapper = $('.ow_comments_form_wrap', this.$cmpContext);
    this.$formWrapperPre = $('.ow_comments_form_wrap_pre', this.$cmpContext);
    this.$hiddenBtnCont = $('.comments_hidden_btn', this.$cmpContext);
    this.$commentsInputCont = $('.ow_comments_item_info', this.$formWrapper);
    this.initTextarea();
    this.attachmentInfo = false;
    this.oembedInfo = false;

    OW.bind('base.comments_list_init',
        function(data){
            if( sleeping ) return;
            if( checkAddress(data) ){
                self.initialCount = this.initialCount;
            }
        }
    );

    OW.bind('base.add_photo_attachment_submit',
        function(data){
            if( sleeping ) return;            
            if( data.uid == self.attchUid ){
                self.oembedInfo = false;
                self.$attchCont.empty();
                self.submitHandler = self.attachmentInProgressHandler;
                self.$hiddenBtnCont.show();
                OW.trigger('base.comment_button_show', self.eventParams);
            }
        }
    );

    OW.bind('base.attachment_added',
        function(data){
            if( sleeping ) return;            
            if( data.uid == self.attchUid ){                
                self.attachmentInfo = data;
                self.$textarea.focus();
                self.submitHandler = self.realSubmitHandler;
                OW.trigger('base.comment_attachment_added', self.eventParams);
            }
        }
    );

    OW.bind('base.attachment_deleted',
        function(data){
            if( sleeping ) return;
            if( data.uid == self.attchUid ){
                self.attachmentInfo = false;
                self.$hiddenBtnCont.hide();
                OW.trigger('base.comment_attachment_deleted', self.eventParams);
            }
        }
    );

    OW.bind('base.move_comments_form',
        function(data){
            if( sleeping ) return;
            if( !data.entityType || !data.entityId ){
                return;
            }

            if( checkAddress(data) ){
                if( data.appendTo ){
                    self.moveForm(data.appendTo);
                }else{
                    self.moveForm();
                }
            }
        }
    );
}

OwComments.prototype = {
    repaintCommentsList: function(data){
        if(data.error){
            OW.error(data.error);
            return;
        }
        //OW.trigger('base.comments_list_update', {entityType: data.entityType, entityId: data.entityId, id:this.uid});
        $('.comments_list_cont', this.$cmpContext).empty().append($(data.commentList));        
        OW.addScript(data.onloadScript);
    },

    sendMessage: function( message ){
        var self = this;
        var dataToSend = {
            entityType: self.entityType,
            entityId: self.entityId,
            displayType: self.displayType,
            pluginKey: self.pluginKey,
            ownerId: self.ownerId,
            cid: self.uid,
            attchUid: self.attchUid,
            commentCountOnPage: self.commentCountOnPage,
            commentText: message,
            initialCount: self.initialCount
        };

        if( self.attachmentInfo ){
            dataToSend.attachmentInfo = JSON.stringify(self.attachmentInfo);
        }
        else if( self.oembedInfo ){
            dataToSend.oembedInfo = JSON.stringify(self.oembedInfo);
        }

        $.ajax({
            type: 'post',
            url: self.addUrl,
            data: dataToSend,
            dataType: 'JSON',
            success: function(data){
                self.repaintCommentsList(data);
                OW.trigger('base.photo_attachment_uid_update', {uid:self.attchUid, newUid:data.newAttachUid});
                self.eventParams.commentCount = data.commentCount;
                OW.trigger('base.comment_added', self.eventParams);
                self.attchUid = data.newAttachUid;
                
                self.$formWrapper.removeClass('ow_preloader');
                self.$commentsInputCont.show();
            },
            error: function( XMLHttpRequest, textStatus, errorThrown ){
                OW.error(textStatus);
            },
            complete: function(){
                
            }
        });
        
        this.$textarea.val('').keyup().trigger('input.autosize');
    },

    initTextarea: function(){
        var self = this;
        this.realSubmitHandler = function(){
            self.initialCount++;                         
            self.sendMessage(self.$textarea.val());
            self.attachmentInfo = false;
            self.oembedInfo = false;
            self.$hiddenBtnCont.hide();
            if( this.mediaAllowed ){
                OWLinkObserver.getObserver(self.textAreaId).resetObserver();
            }
            self.$attchCont.empty();
            OW.trigger('base.photo_attachment_reset', {pluginKey:self.pluginKey, uid:self.attchUid});
            OW.trigger('base.comment_add', self.eventParams);
            
            self.$formWrapper.addClass('ow_preloader');
            self.$commentsInputCont.hide();
            
        };
        
        this.submitHandler = this.realSubmitHandler;
        
        this.$textarea
            .bind('keypress',
                function(e){
                    if( e.which === 13 && !e.shiftKey ){
                        var textBody = $(this).val();

                         if ( $.trim(textBody) == '' && !self.attachmentInfo && !self.oembedInfo ){
                             OW.error(self.labels.emptyCommentMsg);
                            return false;
                         }
                        
                        self.submitHandler();
                        return false;
                    }
                }
            )
            .one('focus', function(){$(this).removeClass('invitation').val('').autosize({callback:function(data){OW.trigger('base.comment_textarea_resize', self.eventParams);}});});

       this.$hiddenBtnCont.unbind('click').click(function(){self.submitHandler();});

       if( this.mediaAllowed ){
           OWLinkObserver.observeInput(this.textAreaId, function( link ){
            if( !self.attachmentInfo ){
                 self.$attchCont.html('<div class="ow_preloader" style="height: 30px;"></div>');
                 this.requestResult( function( r ){
                     self.$attchCont.html(r);
                     self.$hiddenBtnCont.show();

                     OW.trigger('base.comment_attach_media', {})
                 });
                 this.onResult = function( r ){ 
                     self.oembedInfo = r; 
                     if( $.isEmptyObject(r) ){
                         self.$hiddenBtnCont.hide();
                     }
                 };
            }
         });
       }
    },

    moveForm: function( $appendTo ){
        if( $appendTo ){
            $appendTo.append(this.$formWrapper);
        }
        else{
            this.$formWrapperPre.after(this.$formWrapper);
        }
    }
};

var OwCommentsList = function( params ){
	this.$context = $('#' + params.contextId);
	$.extend(this, params, owCommentListCmps.staticData);
        this.$loader = $('.ow_comment_list_loader', this.$context);
}

OwCommentsList.prototype = {
	init: function(){
	var self = this;
        $('.ow_comments_item', this.$context).hover(function(){$('.cnx_action', this).show();$('.ow_comments_date_hover', this).hide();}, function(){$('.cnx_action', this).hide();$('.ow_comments_date_hover', this).show();});
        this.$loader.one('click',
            function(){
                self.$loader.addClass('ow_preloader');
                $('a', self.$loader).hide();
                self.initialCount += self.loadMoreCount;
                self.reload();
            }
        );

//        OW.bind('base.comments_list_update',
//            function(data){
//                if( data.entityType == self.entityType && data.entityId == self.entityId && data.id != self.cid ){
//                    self.reload();
//                }
//            }
//        );

        OW.trigger('base.comments_list_init', {entityType: this.entityType, entityId: this.entityId}, this);

        OW.bind('base.comment_add', function(data){ if( data.entityType == self.entityType && data.entityId == self.entityId ) self.initialCount++ });

        if( this.pagesCount > 0 )
        {
            for( var i = 1; i <= this.pagesCount; i++ )
            {
                $('a.page-'+i, self.$context).bind( 'click', {i:i},
                    function(event){
                        self.reload(event.data.i);
                    }
                );
            }
        }

        $.each(this.actionArray.comments,
            function(i,o){
                $('#'+i).click(
                    function(){
                        if( confirm(self.delConfirmMsg) )
                        {
                           $(this).closest('div.ow_comments_item').slideUp(300, function(){$(this).remove();});

                            $.ajax({
                                type: 'POST',
                                url: self.delUrl,
                                data: {
                                    cid:self.cid,
                                    commentCountOnPage:self.commentCountOnPage,
                                    ownerId:self.ownerId,
                                    pluginKey:self.pluginKey,
                                    displayType:self.displayType,
                                    entityType:self.entityType,
                                    entityId:self.entityId,
                                    initialCount:self.initialCount,
                                    page:self.page,
                                    commentId:o
                                },
                                dataType: 'json',
                                success : function(data){
                                    if(data.error){
                                            OW.error(data.error);
                                            return;
                                    }

                                    self.$context.replaceWith(data.commentList);
                                    OW.addScript(data.onloadScript);

                                    var eventParams = {
                                        entityType: self.entityType,
                                        entityId: self.entityId,
                                        commentCount: data.commentCount
                                    };

                                    OW.trigger('base.comment_delete', eventParams, this);
                                }
                            });
                        }
                    }
             );
            }
        );

        $.each(this.actionArray.users,
            function(i,o){
                $('#'+i).click(
                    function(){
                        OW.Users.deleteUser(o);
                    }
             );
            }
        );

        for( i = 0; i < this.commentIds.length; i++ )
        {
            if( $('#att'+this.commentIds[i]).length > 0 )
             {
                 $('.attachment_delete',$('#att'+this.commentIds[i])).bind( 'click', {i:i},
                    function(e){

                        $('#att'+self.commentIds[e.data.i]).slideUp(300, function(){$(this).remove();});

                        $.ajax({
                            type: 'POST',
                            url: self.delAtchUrl,
                            data: {
                                cid:self.cid,
                                commentCountOnPage:self.commentCountOnPage,
                                ownerId:self.ownerId,
                                pluginKey:self.pluginKey,
                                displayType:self.displayType,
                                entityType:self.entityType,
                                entityId:self.entityId,
                                page:self.page,
                                initialCount:self.initialCount,
                                loadMoreCount:self.loadMoreCount,
                                commentId:self.commentIds[e.data.i]
                            },
                            dataType: 'json'
                        });
                    }
                 );
             }
        }
	},

	reload:function( page ){
		var self = this;        
		$.ajax({
            type: 'POST',
            url: self.respondUrl,
            data: {
                    cid:self.cid,
                    commentCountOnPage:self.commentCountOnPage,
                    ownerId:self.ownerId,
                    pluginKey:self.pluginKey,
                    displayType:self.displayType,
                    entityType:self.entityType,
                    entityId:self.entityId,
                    initialCount:self.initialCount,
                    loadMoreCount:self.loadMoreCount,
                    page:page
            },
            dataType: 'json',
            success : function(data){
               if(data.error){
                        OW.error(data.error);
                        return;
                }
                self.$loader.removeClass('ow_preloader');
                $('a', self.$loader).hide();
                self.$context.replaceWith(data.commentList);
                OW.addScript(data.onloadScript);
            },
            error : function( XMLHttpRequest, textStatus, errorThrown ){
                OW.error('Ajax Error: '+textStatus+'!');
                throw textStatus;
            }
        });
	}
}

owCommentCmps = {};
owCommentListCmps = {items:{},staticData:{}};

var OwRate = function( params ){
    this.cmpId = params.cmpId;
    this.userRate = params.userRate;
    this.entityId = params.entityId;
    this.entityType = params.entityType;
    this.itemsCount = params.itemsCount;
    this.respondUrl = params.respondUrl;
    this.ownerId = params.ownerId;
    this.$context = $('#rate_'+params.cmpId);
}

OwRate.prototype = {
    init: function(){
        var self = this;
        this.setRate(this.userRate);
        for( var i = 1; i <= this.itemsCount; i++ ){
            $('#' + this.cmpId + '_rate_item_' + i).bind( 'mouseover', {i:i},
                function(e){
                    self.setRate(e.data.i);
                }
            ).bind( 'mouseout',
                function(){
                    self.setRate(self.userRate);
                }
            ).bind( 'click', {i:i},
                function(e){
                    self.updateRate(e.data.i);
                }
            );
        }
    },

    setRate: function( rate ){
        for( var i = 1; i <= this.itemsCount; i++ ){
            var $el = $('#' + this.cmpId + '_rate_item_' + i);
            $el.removeClass('active');
            if( !rate ){
                continue;
            }
            if( i <= rate ){
                $el.addClass('active');
            }
        }
    },

    updateRate: function( rate ){
        var self = this;
        if( rate == this.userRate ){
            return;
        }
        this.userRateBackup = this.userRate;
        this.userRate = rate;
        $.ajax({
            type: 'POST',
            url: self.respondUrl,
            data: 'entityType='+encodeURIComponent(self.entityType)+'&entityId='+encodeURIComponent(self.entityId)+'&rate='+encodeURIComponent(rate)+'&ownerId='+encodeURIComponent(self.ownerId),
            dataType: 'json',
            success : function(data){

                if( data.errorMessage ){
                    OW.error(data.errorMessage);
                    self.userRate = self.userRateBackup;
                    self.setRate(self.userRateBackup);
                    return;
                }

                if( data.message ){
                    OW.info(data.message);
                }

                $('.total_score', self.$context).empty().append(data.totalScoreCmp);
                OW.trigger('base.rate_update', {entityType: self.entityType, entityId: self.entityId, rate: rate, ownerId: self.ownerId}, this);
            },
            error : function( XMLHttpRequest, textStatus, errorThrown ){
                alert('Ajax Error: '+textStatus+'!');
                throw textStatus;
            }
        });
    }
}

OWLinkObserver =
{
    observers: {},

    observeInput: function( inputId, callBack )
    {
        this.observers[inputId] = new OWLinkObserver.handler(inputId, callBack);
    },

    getObserver: function( inputId )
    {
        return this.observers[inputId] || null;
    }
};

OWLinkObserver.handler = function( inputId, callBack )
{
    this.callback = callBack;
    this.input = $('#' + inputId);
    this.inputId = inputId;
    this.detectedUrl = null;

    this.onResult = function(){};

    this.startObserve();
};

OWLinkObserver.handler.prototype =
{
    startObserve: function()
    {
        var self = this;

        var detect = function()
        {
            var val = self.input.val();

            if ( $.trim(val) )
            {
                self.detectLink();
            }
        };

        this.input.bind('paste', function(){
            setTimeout(function() {
                detect();
            }, 100);
        });

        this.input.bind('blur', detect);

        this.input.keyup(function(e)
        {
            if (e.keyCode == 32 || e.keyCode == 13) {
                detect();
            }
        });
    },

    detectLink: function( text )
    {
        var text, rgxp, result;

        text = this.input.val();
        rgxp = /(http(s)?:\/\/|www\.)((\d+\.\d+\.\d+\.\d+)|(([\w-]+\.)+([a-z,A-Z][\w-]*)))(:[1-9][0-9]*)?(\/?([?\w\-.\,\/:%+@&*=~]+[\w\-\,.\/?\':%+@&=*|]*)?)?/;
        result = text.match(rgxp);

        if ( !result )
        {
            return false;
        }

        if ( this.detectedUrl == result[0] )
        {
            return false;
        }

        this.detectedUrl = result[0];

        this.callback.call(this, this.detectedUrl);
    },

    requestResult: function( callback, link )
    {
        var self = this;

        link = link || this.detectedUrl;

        $.ajax({
            type: 'POST',
            url: OW.ajaxAttachmentLinkRsp,
            data: {"url": link},
            dataType: 'json',
            success: function( r )
            {
                if ( r.content )
                {
                    if ( r.content.css )
                    {
                        OW.addCss(r.content.css);
                    }

                    if ( $.isFunction(callback) )
                    {
                        callback.call(self, r.content.html, r.result);
                    }

                    if ( $.isFunction(self.onResult) )
                    {
                        self.onResult(r.result);
                    }

                    if ( r.content.js )
                    {
                        OW.addScript(r.content.js);
                    }
                }

                if ( r.attachment && OW_AttachmentItemColletction[r.attachment] )
                {
                    OW_AttachmentItemColletction[r.attachment].onChange = function(oembed){
                        self.onResult(oembed);
                    };
                }
            }
        });
    },

    resetObserver: function()
    {
        this.detectedUrl = null;
    }
};

OW_AttachmentItemColletction = {};

OW_Attachment = function(uniqId, data)
{
    var self = this;

    this.data = data;
    this.uniqId = uniqId;
    this.node = document.getElementById(this.uniqId);
    this.onChange = function(){};

    //OW.resizeImg(this.$('.EQ_AttachmentImageC'),{width:'150'});

    this.$('.OW_AttachmentSelectPicture').click(function()
    {
        self.showImageSelector();
    });

    this.$('.OW_AttachmentDelete').click(function()
    {
        $(self.node).remove();

        if ( $.isFunction(self.onChange) )
        {
            self.data = [];
            self.onChange.call(self, self.data);
        }
        
        return false;
    });
};

OW_AttachmentProto = function()
{
    this.$ = function (sel)
    {
        return $(sel, this.node);
    };

    this.showImageSelector = function()
    {
        var fb, $contents, self = this;

        $contents = this.$('.OW_AttachmentPicturesFbContent')

        fb = new OW_FloatBox({
            $title: this.$('.OW_AttachmentPicturesFbTitle'),
            $contents: $contents,
            width: 520
        });

        $contents.find('.OW_AttachmentPictureItem').unbind().click(function()
        {
            var img = $('img', this);
            self.changeImage(img.attr('src'));

            fb.close();
        });
    };

    this.changeImage = function( url )
    {
        var clone, original;

        original = this.$('.OW_AttachmentImage');
        clone = original.clone();
        clone.attr('src', url);
        original.replaceWith(clone);

        if ( $.isFunction(this.onChange) )
        {
            this.data["thumbnail_url"] = url;

            this.onChange.call(this, this.data);
        }
    };

};
OW_Attachment.prototype = new OW_AttachmentProto();

// Additional jQuery plugins

jQuery.fn.onImageLoad = function(fn)
{
    this.load(fn);
    this.each( function() {
        if ( this.complete && this.naturalWidth !== 0 ) {
            $(this).trigger('load');
        }
    });
};


/* PING */

OW_PingCommand = function( commandName, commandObject, stack )
{
    $.extend(this, commandObject);

    this.commandName = commandName;
    this.repeatTime = false;
    this.minRepeatTime = null;

    this.stack = stack;
    this.commandTimeout = null;
    this.stopped = true;
    this.skipped = false;
    this.inProcess = false;
    this.isRootCommand = false;

    this._lastRunTime = null;
};

OW_PingCommand.PROTO = function()
{
    this._updateLastRunTime = function()
    {
        this._lastRunTime = $.now();
    };

    this._received = function( r )
    {
        this.after(r);
    },

    this._delayCommand = function()
    {
        var self = this;

        if ( this.commandTimeout )
        {
            window.clearTimeout(this.commandTimeout);
        }

        this.commandTimeout = window.setTimeout(function()
        {
            self._run();
            self.skipped = false;
        }, this.repeatTime);
    },

    this._completed = function()
    {
        this.inProcess = false;
        this._updateLastRunTime();

        if ( this.skipped || this.stopped || this.repeatTime === false )
        {
            return;
        }

        this._delayCommand();
    },

    this._getStackCommand = function()
    {
        return {
            "command": this.commandName,
            "params": this.params
        };
    };

    this._beforeStackSend = function()
    {
        if ( this.minRepeatTime === null || this.stopped || this.inProcess || this.isRootCommand )
        {
            return;
        }

        if ( $.now() - this._lastRunTime < this.minRepeatTime )
        {
            return;
        }

        this._run();
    };

    this._run = function()
    {
        if ( !this.stopped )
        {
            this.inProcess = true;
            this.stack.push(this);
        }

        if ( this.onRun )
        {
            this.onRun(this);
        }
    };

    this.params = {};
    this.before = function(){};
    this.after = function(){};

    this.start = function( repeatTime )
    {
        if ( $.isNumeric(repeatTime) )
        {
            this.repeatTime = repeatTime;
        }
        else if ( $.isPlainObject(repeatTime) )
        {
            if ( repeatTime.max )
            {
                this.repeatTime = repeatTime.max;
            }

            if ( repeatTime.min )
            {
                this.minRepeatTime = repeatTime.min == 'each' ? 0 : repeatTime.min;
            }
        }

        this.stop();
        this.stopped = false;

        if ( !this.inProcess )
        {
            this._run();
        }
    };

    this.skip = function()
    {
        this.skipped = true;
        this._delayCommand();
    };

    this.stop = function()
    {
        this.stopped = true;
    };
};

OW_PingCommand.prototype = new OW_PingCommand.PROTO();


OW_Ping = function()
{
    var _stack = [], _commands = {};

    var rspUrl;
    var _rootCommand = null;

    var beforeStackSend, sendStack, refreshRootCommand, rootOnCommandRun, genericOnCommandRun, setRootCommand;

    rootOnCommandRun = function( command )
    {
        window.setTimeout(function(){
            sendStack();
        }, 10);
    };

    genericOnCommandRun = function( command )
    {
        if ( !_rootCommand )
        {
            setRootCommand(command);
            rootOnCommandRun(command);

            return;
        }

        if ( command.repeatTime === false )
        {
            return;
        }

        if ( _rootCommand.repeatTime === false || _rootCommand.repeatTime > command.repeatTime )
        {
            setRootCommand(command);
            rootOnCommandRun(command);
        }
    };

    refreshRootCommand = function()
    {
        var rootCommand = null;

        for ( var c in _commands )
        {
            if ( _commands[c].repeatTime === false || _commands[c].stopped  )
            {
                continue;
            }

            if ( !rootCommand || _commands[c].repeatTime < rootCommand.repeatTime )
            {
                rootCommand = _commands[c];
            }
        }

        if ( rootCommand )
        {
           setRootCommand(rootCommand);
        }
    };

    setRootCommand = function( command )
    {
        if ( _rootCommand )
        {
            _rootCommand.onRun = genericOnCommandRun;
            _rootCommand.isRootCommand = false;
        }

        command.isRootCommand = true;
        _rootCommand = command;
        _rootCommand.onRun = rootOnCommandRun;
    };

    beforeStackSend = function()
    {
        for ( var c in _commands )
        {
            _commands[c]._beforeStackSend();
        }
    };

    sendStack = function()
    {
        beforeStackSend();

        if ( !_stack.length )
        {
            return;
        }

        var stack = [], commands = [];

        while ( _stack.length )
        {
            var c = _stack.pop();
            commands.push(c);

            if ( c.before() === false )
            {
                c.skip();
                continue;
            }

            stack.push(c._getStackCommand());
        }

        if ( !stack.length )
        {
            return;
        }

        var request = {
            "stack": stack
        };

        var jsonRequest = JSON.stringify(request);

        var ajaxOptions =
        {
            url: rspUrl,
            dataType: 'json',
            type: 'POST',
            data: {request: jsonRequest},
            success: function(result)
            {
                if ( !result || !result.stack )
                {
                    return;
                }

                $.each(result.stack, function(i, command)
                {
                    if ( _commands[command.command] )
                    {
                        _commands[command.command]._received(command.result);
                    }
                });
            },

            complete: function()
            {
                $(commands).each(function(i, command)
                {
                    command._completed();
                });

                refreshRootCommand();
            }
        };

        $.ajax(ajaxOptions);
    };

    this.addCommand = function( commandName, commandObject )
    {
        if ( _commands[commandName] )
        {
            return _commands[commandName];
        }

        commandObject = commandObject || {};

        _commands[commandName] = new OW_PingCommand(commandName, commandObject, _stack);
        _commands[commandName].onRun = genericOnCommandRun;

        return _commands[commandName]
    };

    this.getCommand = function( commandName )
    {
        return _commands[commandName] || null;
    };

    this.setRspUrl = function( url )
    {
        rspUrl = url;
    };

};


OW_Ping.getInstance = function()
{
    if ( !OW_Ping.pingInstance )
    {
        OW_Ping.pingInstance = new OW_Ping();
    }

    return OW_Ping.pingInstance;
}



OW.getPing = function()
{
    return OW_Ping.getInstance();
};

/* Add command example
OW.getPing().addCommand('ajaxim', {
    params: {
        p1: 1,
        p2: 3
    },
    before: function()
    {
        this.params.p1 = 4;
    },
    after: function( res )
    {

    }
}).start(5000); // repeatTime ( Number or Object {max: maxRepeatTime, min: minRepeatTime} )
*/




/* Scroll */

OW.Scroll = {};

OW.Scroll.settings =
{
    verticalGutter: 0,
    horizontalGutter: 0,
    showArrows: false
};

OW.addScroll = function( node, settings )
{
    settings = settings || {};
    settings = $.extend({}, OW.Scroll.settings, settings);

    var $node = $(node);

    $node.unbind('jsp-initialised').bind('jsp-initialised', function()
    {
        var track = $node.find('.jspTrack');

        $node.hover(function()
        {
            track.fadeIn('fast');
        }, function()
        {
            track.fadeOut(200);
        });
    });

    if ( !$node.hasClass('ow_scrollable') )
    {
        $node.addClass('ow_scrollable');
    }

    $node.jScrollPane(settings);

    return $node.data().jsp;
};

OW.removeScroll = function( node )
{
    var $node = $(node);
    var jsp = $node.data('jsp');

    if ( jsp )
    {
        jsp.destroy();
    }
    //$node.jScrollPaneRemove();
    $node.removeClass('ow_scrollable');
};

OW.updateScroll = function( node, settings )
{
    var jsp = $(node).data('jsp');

    settings = settings || {};
    settings = $.extend({}, OW.Scroll.settings, settings);

    if ( jsp )
    {
        jsp.reinitialise(settings);
    }
};

OW.addScrolls = function( context )
{
    context = context || null;

    $('.ow_scrollable', context).each(function()
    {
        OW.addScroll(this);
    });
};

OW.removeScrolls = function( context )
{
    context = context || null;

    $('.ow_scrollable', context).each(function()
    {
        OW.removeScroll(this);
    });
};

OW.updateScrolls = function( context )
{
    context = context || null;

    $('.ow_scrollable', context).each(function()
    {
        OW.updateScroll(this);
    });
};

OW.Utils = (function() {

    return {
        toggleText: function( node, value, alternateValue ) {
            var $node = $(node), text = $node.text();

            if ( !$node.data("toggle-text") )
                $node.data("toggle-text", text);

            alternateValue = alternateValue || $node.data("toggle-text");
            $node.text(text == alternateValue ? value : alternateValue);
        },

        toggleAttr: function( node, attributeName, value, alternateValue ) {
            var $node = $(node), attributeValue = $node.attr(attributeName);

            if ( !$node.data("toggle-" + attributeName) )
                $node.data("toggle-" + attributeName, attributeValue);

            alternateValue = alternateValue || $node.data("toggle-" + attributeName);
            $node.attr(attributeName, attributeValue == alternateValue ? value : alternateValue);
        }
    };
})();


OW.Users = null;
OW_UsersApi = function( _settings )
{
    var _usersApi = this;

    var _query = function(command, params, callback) {
        callback = callback || function( r ) {
            if ( !r ) return;
            if (r.info) OW.info(r.info);
            if (r.error) OW.error(r.error);
        };

        return $.getJSON(_settings.rsp, {"command": command, "params": JSON.stringify(params)}, callback);
    };

    OW.Users = this;

    //Public methods

    this.deleteUser = function(userId, callBack, showMessage)
    {
        showMessage = showMessage === false ? false : true;

        var redirectUrl = null;

        if ( typeof callBack == 'string' )
        {
            redirectUrl = callBack;
        }

        var floatBox;

        floatBox = OW.ajaxFloatBox('BASE_CMP_DeleteUser', [{userId: userId, showMessage : showMessage && redirectUrl}],
        {
            title: OW.getLanguageText('base', 'delete_user_confirmation_label'),
            iconClass: 'ow_ic_add',
            scope: {
                deleteCallback: function( r )
                {
                    if ( r.result == 'error' )
                    {
                        if ( r.message )
                        {
                            OW.error(r.message);
                        }

                        return;
                    }

                    if ( redirectUrl )
                    {
                        window.location.href = redirectUrl;

                        return;
                    }

                    if ( showMessage )
                    {
                        OW.info(r.message);
                    }

                    if ( callBack )
                    {
                        callBack.call(floatBox, r);

                        return;
                    }
                }
            }
        });
    },

    this.showUsers = function(userIds, title)
    {
    	title = title || OW.getLanguageText('base', 'ajax_floatbox_users_title');

    	OW.ajaxFloatBox('BASE_CMP_FloatboxUserList', [userIds], {iconClass: "ow_ic_user", title: title, width: 470});
    },

    this.suspendUser = function( userId, callback ) {
        return _query("suspend", {"userId": userId}, callback);
    };

    this.unSuspendUser = function( userId, callback ) {
        return _query("unsuspend", {"userId": userId}, callback);
    };

    this.blockUserWithConfirmation = function( userId, confirmationCallback, callback ) {
        var floatBox = OW.ajaxFloatBox("BASE_CMP_BlockUser", [userId], {
            scope: {
                "confirmCallback": function() {
                    _usersApi.blockUser(userId, callback);
                    if ( $.isFunction(confirmationCallback) ) {
                        confirmationCallback.call(null, userId);

                        floatBox.close();
                    }
                }
            }
        });
    };

    this.blockUser = function( userId, callback ) {
        return _query("block", {"userId": userId}, callback);
    };

    this.unBlockUser = function( userId, callback ) {
        return _query("unblock", {"userId": userId}, callback);
    };

    this.featureUser = function( userId, callback ) {
        return _query("feature", {"userId": userId}, callback);
    };

    this.unFeatureUser = function( userId, callback ) {
        return _query("unfeature", {"userId": userId}, callback);
    };
};;


/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.6
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

if ($.event.fixHooks) {
    for ( var i=types.length; i; ) {
        $.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
    }
}

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    
    // Old school scrollwheel delta
    if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
    if ( orgEvent.detail     ) { delta = -orgEvent.detail/3; }
    
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    
    return ($.event.dispatch || $.event.handle).apply(this, args);
}

})(jQuery);
;


/*
 * jScrollPane - v2.0.0beta12 - 2012-09-27
 * http://jscrollpane.kelvinluck.com/
 *
 * Copyright (c) 2010 Kelvin Luck
 * Dual licensed under the MIT or GPL licenses.
 */
(function(b,a,c){b.fn.jScrollPane=function(e){function d(D,O){var ay,Q=this,Y,aj,v,al,T,Z,y,q,az,aE,au,i,I,h,j,aa,U,ap,X,t,A,aq,af,am,G,l,at,ax,x,av,aH,f,L,ai=true,P=true,aG=false,k=false,ao=D.clone(false,false).empty(),ac=b.fn.mwheelIntent?"mwheelIntent.jsp":"mousewheel.jsp";aH=D.css("paddingTop")+" "+D.css("paddingRight")+" "+D.css("paddingBottom")+" "+D.css("paddingLeft");f=(parseInt(D.css("paddingLeft"),10)||0)+(parseInt(D.css("paddingRight"),10)||0);function ar(aQ){var aL,aN,aM,aJ,aI,aP,aO=false,aK=false;ay=aQ;if(Y===c){aI=D.scrollTop();aP=D.scrollLeft();D.css({overflow:"hidden",padding:0});aj=D.innerWidth()+f;v=D.innerHeight();D.width(aj);Y=b('<div class="jspPane" />').css("padding",aH).append(D.children());al=b('<div class="jspContainer" />').css({width:aj+"px",height:v+"px"}).append(Y).appendTo(D)}else{D.css("width","");aO=ay.stickToBottom&&K();aK=ay.stickToRight&&B();aJ=D.innerWidth()+f!=aj||D.outerHeight()!=v;if(aJ){aj=D.innerWidth()+f;v=D.innerHeight();al.css({width:aj+"px",height:v+"px"})}if(!aJ&&L==T&&Y.outerHeight()==Z){D.width(aj);return}L=T;Y.css("width","");D.width(aj);al.find(">.jspVerticalBar,>.jspHorizontalBar").remove().end()}Y.css("overflow","auto");if(aQ.contentWidth){T=aQ.contentWidth}else{T=Y[0].scrollWidth}Z=Y[0].scrollHeight;Y.css("overflow","");y=T/aj;q=Z/v;az=q>1;aE=y>1;if(!(aE||az)){D.removeClass("jspScrollable");Y.css({top:0,width:al.width()-f});n();E();R();w()}else{D.addClass("jspScrollable");aL=ay.maintainPosition&&(I||aa);if(aL){aN=aC();aM=aA()}aF();z();F();if(aL){N(aK?(T-aj):aN,false);M(aO?(Z-v):aM,false)}J();ag();an();if(ay.enableKeyboardNavigation){S()}if(ay.clickOnTrack){p()}C();if(ay.hijackInternalLinks){m()}}if(ay.autoReinitialise&&!av){av=setInterval(function(){ar(ay)},ay.autoReinitialiseDelay)}else{if(!ay.autoReinitialise&&av){clearInterval(av)}}aI&&D.scrollTop(0)&&M(aI,false);aP&&D.scrollLeft(0)&&N(aP,false);D.trigger("jsp-initialised",[aE||az])}function aF(){if(az){al.append(b('<div class="jspVerticalBar" />').append(b('<div class="jspCap jspCapTop" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragTop" />'),b('<div class="jspDragBottom" />'))),b('<div class="jspCap jspCapBottom" />')));U=al.find(">.jspVerticalBar");ap=U.find(">.jspTrack");au=ap.find(">.jspDrag");if(ay.showArrows){aq=b('<a class="jspArrow jspArrowUp" />').bind("mousedown.jsp",aD(0,-1)).bind("click.jsp",aB);af=b('<a class="jspArrow jspArrowDown" />').bind("mousedown.jsp",aD(0,1)).bind("click.jsp",aB);if(ay.arrowScrollOnHover){aq.bind("mouseover.jsp",aD(0,-1,aq));af.bind("mouseover.jsp",aD(0,1,af))}ak(ap,ay.verticalArrowPositions,aq,af)}t=v;al.find(">.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow").each(function(){t-=b(this).outerHeight()});au.hover(function(){au.addClass("jspHover")},function(){au.removeClass("jspHover")}).bind("mousedown.jsp",function(aI){b("html").bind("dragstart.jsp selectstart.jsp",aB);au.addClass("jspActive");var s=aI.pageY-au.position().top;b("html").bind("mousemove.jsp",function(aJ){V(aJ.pageY-s,false)}).bind("mouseup.jsp mouseleave.jsp",aw);return false});o()}}function o(){ap.height(t+"px");I=0;X=ay.verticalGutter+ap.outerWidth();Y.width(aj-X-f);try{if(U.position().left===0){Y.css("margin-left",X+"px")}}catch(s){}}function z(){if(aE){al.append(b('<div class="jspHorizontalBar" />').append(b('<div class="jspCap jspCapLeft" />'),b('<div class="jspTrack" />').append(b('<div class="jspDrag" />').append(b('<div class="jspDragLeft" />'),b('<div class="jspDragRight" />'))),b('<div class="jspCap jspCapRight" />')));am=al.find(">.jspHorizontalBar");G=am.find(">.jspTrack");h=G.find(">.jspDrag");if(ay.showArrows){ax=b('<a class="jspArrow jspArrowLeft" />').bind("mousedown.jsp",aD(-1,0)).bind("click.jsp",aB);x=b('<a class="jspArrow jspArrowRight" />').bind("mousedown.jsp",aD(1,0)).bind("click.jsp",aB);
if(ay.arrowScrollOnHover){ax.bind("mouseover.jsp",aD(-1,0,ax));x.bind("mouseover.jsp",aD(1,0,x))}ak(G,ay.horizontalArrowPositions,ax,x)}h.hover(function(){h.addClass("jspHover")},function(){h.removeClass("jspHover")}).bind("mousedown.jsp",function(aI){b("html").bind("dragstart.jsp selectstart.jsp",aB);h.addClass("jspActive");var s=aI.pageX-h.position().left;b("html").bind("mousemove.jsp",function(aJ){W(aJ.pageX-s,false)}).bind("mouseup.jsp mouseleave.jsp",aw);return false});l=al.innerWidth();ah()}}function ah(){al.find(">.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow").each(function(){l-=b(this).outerWidth()});G.width(l+"px");aa=0}function F(){if(aE&&az){var aI=G.outerHeight(),s=ap.outerWidth();t-=aI;b(am).find(">.jspCap:visible,>.jspArrow").each(function(){l+=b(this).outerWidth()});l-=s;v-=s;aj-=aI;G.parent().append(b('<div class="jspCorner" />').css("width",aI+"px"));o();ah()}if(aE){Y.width((al.outerWidth()-f)+"px")}Z=Y.outerHeight();q=Z/v;if(aE){at=Math.ceil(1/y*l);if(at>ay.horizontalDragMaxWidth){at=ay.horizontalDragMaxWidth}else{if(at<ay.horizontalDragMinWidth){at=ay.horizontalDragMinWidth}}h.width(at+"px");j=l-at;ae(aa)}if(az){A=Math.ceil(1/q*t);if(A>ay.verticalDragMaxHeight){A=ay.verticalDragMaxHeight}else{if(A<ay.verticalDragMinHeight){A=ay.verticalDragMinHeight}}au.height(A+"px");i=t-A;ad(I)}}function ak(aJ,aL,aI,s){var aN="before",aK="after",aM;if(aL=="os"){aL=/Mac/.test(navigator.platform)?"after":"split"}if(aL==aN){aK=aL}else{if(aL==aK){aN=aL;aM=aI;aI=s;s=aM}}aJ[aN](aI)[aK](s)}function aD(aI,s,aJ){return function(){H(aI,s,this,aJ);this.blur();return false}}function H(aL,aK,aO,aN){aO=b(aO).addClass("jspActive");var aM,aJ,aI=true,s=function(){if(aL!==0){Q.scrollByX(aL*ay.arrowButtonSpeed)}if(aK!==0){Q.scrollByY(aK*ay.arrowButtonSpeed)}aJ=setTimeout(s,aI?ay.initialDelay:ay.arrowRepeatFreq);aI=false};s();aM=aN?"mouseout.jsp":"mouseup.jsp";aN=aN||b("html");aN.bind(aM,function(){aO.removeClass("jspActive");aJ&&clearTimeout(aJ);aJ=null;aN.unbind(aM)})}function p(){w();if(az){ap.bind("mousedown.jsp",function(aN){if(aN.originalTarget===c||aN.originalTarget==aN.currentTarget){var aL=b(this),aO=aL.offset(),aM=aN.pageY-aO.top-I,aJ,aI=true,s=function(){var aR=aL.offset(),aS=aN.pageY-aR.top-A/2,aP=v*ay.scrollPagePercent,aQ=i*aP/(Z-v);if(aM<0){if(I-aQ>aS){Q.scrollByY(-aP)}else{V(aS)}}else{if(aM>0){if(I+aQ<aS){Q.scrollByY(aP)}else{V(aS)}}else{aK();return}}aJ=setTimeout(s,aI?ay.initialDelay:ay.trackClickRepeatFreq);aI=false},aK=function(){aJ&&clearTimeout(aJ);aJ=null;b(document).unbind("mouseup.jsp",aK)};s();b(document).bind("mouseup.jsp",aK);return false}})}if(aE){G.bind("mousedown.jsp",function(aN){if(aN.originalTarget===c||aN.originalTarget==aN.currentTarget){var aL=b(this),aO=aL.offset(),aM=aN.pageX-aO.left-aa,aJ,aI=true,s=function(){var aR=aL.offset(),aS=aN.pageX-aR.left-at/2,aP=aj*ay.scrollPagePercent,aQ=j*aP/(T-aj);if(aM<0){if(aa-aQ>aS){Q.scrollByX(-aP)}else{W(aS)}}else{if(aM>0){if(aa+aQ<aS){Q.scrollByX(aP)}else{W(aS)}}else{aK();return}}aJ=setTimeout(s,aI?ay.initialDelay:ay.trackClickRepeatFreq);aI=false},aK=function(){aJ&&clearTimeout(aJ);aJ=null;b(document).unbind("mouseup.jsp",aK)};s();b(document).bind("mouseup.jsp",aK);return false}})}}function w(){if(G){G.unbind("mousedown.jsp")}if(ap){ap.unbind("mousedown.jsp")}}function aw(){b("html").unbind("dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp");if(au){au.removeClass("jspActive")}if(h){h.removeClass("jspActive")}}function V(s,aI){if(!az){return}if(s<0){s=0}else{if(s>i){s=i}}if(aI===c){aI=ay.animateScroll}if(aI){Q.animate(au,"top",s,ad)}else{au.css("top",s);ad(s)}}function ad(aI){if(aI===c){aI=au.position().top}al.scrollTop(0);I=aI;var aL=I===0,aJ=I==i,aK=aI/i,s=-aK*(Z-v);if(ai!=aL||aG!=aJ){ai=aL;aG=aJ;D.trigger("jsp-arrow-change",[ai,aG,P,k])}u(aL,aJ);Y.css("top",s);D.trigger("jsp-scroll-y",[-s,aL,aJ]).trigger("scroll")}function W(aI,s){if(!aE){return}if(aI<0){aI=0}else{if(aI>j){aI=j}}if(s===c){s=ay.animateScroll}if(s){Q.animate(h,"left",aI,ae)
}else{h.css("left",aI);ae(aI)}}function ae(aI){if(aI===c){aI=h.position().left}al.scrollTop(0);aa=aI;var aL=aa===0,aK=aa==j,aJ=aI/j,s=-aJ*(T-aj);if(P!=aL||k!=aK){P=aL;k=aK;D.trigger("jsp-arrow-change",[ai,aG,P,k])}r(aL,aK);Y.css("left",s);D.trigger("jsp-scroll-x",[-s,aL,aK]).trigger("scroll")}function u(aI,s){if(ay.showArrows){aq[aI?"addClass":"removeClass"]("jspDisabled");af[s?"addClass":"removeClass"]("jspDisabled")}}function r(aI,s){if(ay.showArrows){ax[aI?"addClass":"removeClass"]("jspDisabled");x[s?"addClass":"removeClass"]("jspDisabled")}}function M(s,aI){var aJ=s/(Z-v);V(aJ*i,aI)}function N(aI,s){var aJ=aI/(T-aj);W(aJ*j,s)}function ab(aV,aQ,aJ){var aN,aK,aL,s=0,aU=0,aI,aP,aO,aS,aR,aT;try{aN=b(aV)}catch(aM){return}aK=aN.outerHeight();aL=aN.outerWidth();al.scrollTop(0);al.scrollLeft(0);while(!aN.is(".jspPane")){s+=aN.position().top;aU+=aN.position().left;aN=aN.offsetParent();if(/^body|html$/i.test(aN[0].nodeName)){return}}aI=aA();aO=aI+v;if(s<aI||aQ){aR=s-ay.verticalGutter}else{if(s+aK>aO){aR=s-v+aK+ay.verticalGutter}}if(aR){M(aR,aJ)}aP=aC();aS=aP+aj;if(aU<aP||aQ){aT=aU-ay.horizontalGutter}else{if(aU+aL>aS){aT=aU-aj+aL+ay.horizontalGutter}}if(aT){N(aT,aJ)}}function aC(){return -Y.position().left}function aA(){return -Y.position().top}function K(){var s=Z-v;return(s>20)&&(s-aA()<10)}function B(){var s=T-aj;return(s>20)&&(s-aC()<10)}function ag(){al.unbind(ac).bind(ac,function(aL,aM,aK,aI){var aJ=aa,s=I;Q.scrollBy(aK*ay.mouseWheelSpeed,-aI*ay.mouseWheelSpeed,false);return aJ==aa&&s==I})}function n(){al.unbind(ac)}function aB(){return false}function J(){Y.find(":input,a").unbind("focus.jsp").bind("focus.jsp",function(s){ab(s.target,false)})}function E(){Y.find(":input,a").unbind("focus.jsp")}function S(){var s,aI,aK=[];aE&&aK.push(am[0]);az&&aK.push(U[0]);Y.focus(function(){D.focus()});D.attr("tabindex",0).unbind("keydown.jsp keypress.jsp").bind("keydown.jsp",function(aN){if(aN.target!==this&&!(aK.length&&b(aN.target).closest(aK).length)){return}var aM=aa,aL=I;switch(aN.keyCode){case 40:case 38:case 34:case 32:case 33:case 39:case 37:s=aN.keyCode;aJ();break;case 35:M(Z-v);s=null;break;case 36:M(0);s=null;break}aI=aN.keyCode==s&&aM!=aa||aL!=I;return !aI}).bind("keypress.jsp",function(aL){if(aL.keyCode==s){aJ()}return !aI});if(ay.hideFocus){D.css("outline","none");if("hideFocus" in al[0]){D.attr("hideFocus",true)}}else{D.css("outline","");if("hideFocus" in al[0]){D.attr("hideFocus",false)}}function aJ(){var aM=aa,aL=I;switch(s){case 40:Q.scrollByY(ay.keyboardSpeed,false);break;case 38:Q.scrollByY(-ay.keyboardSpeed,false);break;case 34:case 32:Q.scrollByY(v*ay.scrollPagePercent,false);break;case 33:Q.scrollByY(-v*ay.scrollPagePercent,false);break;case 39:Q.scrollByX(ay.keyboardSpeed,false);break;case 37:Q.scrollByX(-ay.keyboardSpeed,false);break}aI=aM!=aa||aL!=I;return aI}}function R(){D.attr("tabindex","-1").removeAttr("tabindex").unbind("keydown.jsp keypress.jsp")}function C(){if(location.hash&&location.hash.length>1){var aK,aI,aJ=escape(location.hash.substr(1));try{aK=b("#"+aJ+', a[name="'+aJ+'"]')}catch(s){return}if(aK.length&&Y.find(aJ)){if(al.scrollTop()===0){aI=setInterval(function(){if(al.scrollTop()>0){ab(aK,true);b(document).scrollTop(al.position().top);clearInterval(aI)}},50)}else{ab(aK,true);b(document).scrollTop(al.position().top)}}}}function m(){if(b(document.body).data("jspHijack")){return}b(document.body).data("jspHijack",true);b(document.body).delegate("a[href*=#]","click",function(s){var aI=this.href.substr(0,this.href.indexOf("#")),aK=location.href,aO,aP,aJ,aM,aL,aN;if(location.href.indexOf("#")!==-1){aK=location.href.substr(0,location.href.indexOf("#"))}if(aI!==aK){return}aO=escape(this.href.substr(this.href.indexOf("#")+1));aP;try{aP=b("#"+aO+', a[name="'+aO+'"]')}catch(aQ){return}if(!aP.length){return}aJ=aP.closest(".jspScrollable");aM=aJ.data("jsp");aM.scrollToElement(aP,true);if(aJ[0].scrollIntoView){aL=b(a).scrollTop();aN=aP.offset().top;if(aN<aL||aN>aL+b(a).height()){aJ[0].scrollIntoView()}}s.preventDefault()
})}function an(){var aJ,aI,aL,aK,aM,s=false;al.unbind("touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick").bind("touchstart.jsp",function(aN){var aO=aN.originalEvent.touches[0];aJ=aC();aI=aA();aL=aO.pageX;aK=aO.pageY;aM=false;s=true}).bind("touchmove.jsp",function(aQ){if(!s){return}var aP=aQ.originalEvent.touches[0],aO=aa,aN=I;Q.scrollTo(aJ+aL-aP.pageX,aI+aK-aP.pageY);aM=aM||Math.abs(aL-aP.pageX)>5||Math.abs(aK-aP.pageY)>5;return aO==aa&&aN==I}).bind("touchend.jsp",function(aN){s=false}).bind("click.jsp-touchclick",function(aN){if(aM){aM=false;return false}})}function g(){var s=aA(),aI=aC();D.removeClass("jspScrollable").unbind(".jsp");D.replaceWith(ao.append(Y.children()));ao.scrollTop(s);ao.scrollLeft(aI);if(av){clearInterval(av)}}b.extend(Q,{reinitialise:function(aI){aI=b.extend({},ay,aI);ar(aI)},scrollToElement:function(aJ,aI,s){ab(aJ,aI,s)},scrollTo:function(aJ,s,aI){N(aJ,aI);M(s,aI)},scrollToX:function(aI,s){N(aI,s)},scrollToY:function(s,aI){M(s,aI)},scrollToPercentX:function(aI,s){N(aI*(T-aj),s)},scrollToPercentY:function(aI,s){M(aI*(Z-v),s)},scrollBy:function(aI,s,aJ){Q.scrollByX(aI,aJ);Q.scrollByY(s,aJ)},scrollByX:function(s,aJ){var aI=aC()+Math[s<0?"floor":"ceil"](s),aK=aI/(T-aj);W(aK*j,aJ)},scrollByY:function(s,aJ){var aI=aA()+Math[s<0?"floor":"ceil"](s),aK=aI/(Z-v);V(aK*i,aJ)},positionDragX:function(s,aI){W(s,aI)},positionDragY:function(aI,s){V(aI,s)},animate:function(aI,aL,s,aK){var aJ={};aJ[aL]=s;aI.animate(aJ,{duration:ay.animateDuration,easing:ay.animateEase,queue:false,step:aK})},getContentPositionX:function(){return aC()},getContentPositionY:function(){return aA()},getContentWidth:function(){return T},getContentHeight:function(){return Z},getPercentScrolledX:function(){return aC()/(T-aj)},getPercentScrolledY:function(){return aA()/(Z-v)},getIsScrollableH:function(){return aE},getIsScrollableV:function(){return az},getContentPane:function(){return Y},scrollToBottom:function(s){V(i,s)},hijackInternalLinks:b.noop,destroy:function(){g()}});ar(O)}e=b.extend({},b.fn.jScrollPane.defaults,e);b.each(["mouseWheelSpeed","arrowButtonSpeed","trackClickSpeed","keyboardSpeed"],function(){e[this]=e[this]||e.speed});return this.each(function(){var f=b(this),g=f.data("jsp");if(g){g.reinitialise(e)}else{b("script",f).filter('[type="text/javascript"],:not([type])').remove();g=new d(f,e);f.data("jsp",g)}})};b.fn.jScrollPane.defaults={showArrows:false,maintainPosition:true,stickToBottom:false,stickToRight:false,clickOnTrack:true,autoReinitialise:false,autoReinitialiseDelay:500,verticalDragMinHeight:0,verticalDragMaxHeight:99999,horizontalDragMinWidth:0,horizontalDragMaxWidth:99999,contentWidth:c,animateScroll:false,animateDuration:300,animateEase:"linear",hijackInternalLinks:false,verticalGutter:4,horizontalGutter:4,mouseWheelSpeed:0,arrowButtonSpeed:0,arrowRepeatFreq:50,arrowScrollOnHover:false,trackClickSpeed:0,trackClickRepeatFreq:70,verticalArrowPositions:"split",horizontalArrowPositions:"split",enableKeyboardNavigation:true,hideFocus:false,keyboardSpeed:0,initialDelay:300,speed:30,scrollPagePercent:0.8}})(jQuery,this);;


/*
|--------------------------------------------------------------------------
| UItoTop jQuery Plugin 1.2 by Matt Varone
| http://www.mattvarone.com/web-design/uitotop-jquery-plugin/
|--------------------------------------------------------------------------
*/
(function($){
	$.fn.UItoTop = function(options) {

 		var defaults = {
    			text: 'To Top',
    			min: 200,
    			inDelay:600,
    			outDelay:400,
      			containerID: 'toTop',
    			containerHoverID: 'toTopHover',
    			scrollSpeed: 1200,
    			easingType: 'linear'
 		    },
            settings = $.extend(defaults, options),
            containerIDhash = '#' + settings.containerID,
            containerHoverIDHash = '#'+settings.containerHoverID;
		
		$('body').append('<a href="#" id="'+settings.containerID+'">'+settings.text+'</a>');
		$(containerIDhash).hide().on('click.UItoTop',function(){
			$('html, body').animate({scrollTop:0}, settings.scrollSpeed, settings.easingType);
			$('#'+settings.containerHoverID, this).stop().animate({'opacity': 0 }, settings.inDelay, settings.easingType);
			return false;
		})
		.prepend('<span id="'+settings.containerHoverID+'"></span>')
		.hover(function() {
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 1
				}, 600, 'linear');
			}, function() { 
				$(containerHoverIDHash, this).stop().animate({
					'opacity': 0
				}, 700, 'linear');
			});
					
		$(window).scroll(function() {
			var sd = $(window).scrollTop();
			if(typeof document.body.style.maxHeight === "undefined") {
				$(containerIDhash).css({
					'position': 'absolute',
					'top': sd + $(window).height() - 50
				});
			}
			if ( sd > settings.min ) 
				$(containerIDhash).fadeIn(settings.inDelay);
			else 
				$(containerIDhash).fadeOut(settings.Outdelay);
		});
};
})(jQuery);;


/*
 * 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
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

// 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;
    }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
;


/* UItoTop jQuery Plugin 1.2 | Matt Varone | http://www.mattvarone.com/web-design/uitotop-jquery-plugin */
(function($){$.fn.UItoTop=function(options){var defaults={text:'To Top',min:200,inDelay:600,outDelay:400,containerID:'toTop',containerHoverID:'toTopHover',scrollSpeed:1200,easingType:'linear'},settings=$.extend(defaults,options),containerIDhash='#'+settings.containerID,containerHoverIDHash='#'+settings.containerHoverID;$('body').append('<a href="#" id="'+settings.containerID+'">'+settings.text+'</a>');$(containerIDhash).hide().on('click.UItoTop',function(){$('html, body').animate({scrollTop:0},settings.scrollSpeed,settings.easingType);$('#'+settings.containerHoverID,this).stop().animate({'opacity':0},settings.inDelay,settings.easingType);return false;}).prepend('<span id="'+settings.containerHoverID+'"></span>').hover(function(){$(containerHoverIDHash,this).stop().animate({'opacity':1},600,'linear');},function(){$(containerHoverIDHash,this).stop().animate({'opacity':0},700,'linear');});$(window).scroll(function(){var sd=$(window).scrollTop();if(typeof document.body.style.maxHeight==="undefined"){$(containerIDhash).css({'position':'absolute','top':sd+$(window).height()-50});}
if(sd>settings.min)
$(containerIDhash).fadeIn(settings.inDelay);else
$(containerIDhash).fadeOut(settings.Outdelay);});};})(jQuery);;


OW_DataModel = function( data )
{
    this.data = data || {};
    this.observers = [];
};

OW_DataModel.PROTO = function()
{
    var isEqual = function( x, y )
    {
        if ( x === y ) return true;
        if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
        if ( x.constructor !== y.constructor ) return false;

        for ( var p in x )
        {
            if ( ! x.hasOwnProperty( p ) ) continue;
            if ( ! y.hasOwnProperty( p ) ) return false;
            if ( x[ p ] === y[ p ] ) continue;
            if ( typeof( x[ p ] ) !== "object" ) return false;
            if ( !isEqual( x[ p ],  y[ p ] ) ) return false;
        }

        for ( p in y )
        {
            if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false;
        }

        return true;
    };

    this.get = function( key )
    {
        if ( !key )
        {
            return this.data;
        }

        var dataBranch = this.data, dataPath, out = null;

        dataPath = key.split('.');

        for ( var i = 0; i < dataPath.length; i++ )
        {
            if ( dataPath[i] in dataBranch )
            {
                out = dataBranch[dataPath[i]];
                dataBranch = dataBranch[dataPath[i]];
            }
        }

        return out;
    };

    this.set = function( key, value, notifyObservers )
    {
        var self = this;
        var notify = notifyObservers || true;
        var changed = false;

        if ( value === undefined && key )
        {
            changed = changed || !isEqual(this.data, key);
            this.data = key;
        }
        else
        {
            var i = 0, dataBranch = this.data, dataPath;

            dataPath = key ? key.split('.') : [];

            for ( i = 0; i < dataPath.length - 1; i++ )
            {
                if ( !$.isPlainObject(dataBranch[dataPath[i]]) )
                {
                    dataBranch[dataPath[i]] = {};
                }

                dataBranch = dataBranch[dataPath[i]];
            }

            changed = changed || !isEqual(dataBranch[dataPath[i]], value);
            dataBranch[dataPath[i]] = value;
        }

        if ( notify && changed )
        {
            window.setTimeout(function()
            {
                self.notifyObservers();
            });
        }
    };

    this.addObserver = function( observer, method )
    {
        method = method || 'onDataChange';

        var _observer, self = this;

        if ( $.isFunction(observer) )
        {
            _observer = function() {
                observer.call(self, self);
            };
        }
        else
        {
            _observer = function() {
                observer[method].call(observer, self);
            };
        }

        this.observers.push(_observer);
    };

    this.onChange = function(){};

    this.notifyObservers = function()
    {
        this.onChange(this);

        $.each(this.observers, function(i, obs)
        {
            obs.call();
        });
    };
};

OW_DataModel.prototype = new OW_DataModel.PROTO();


OW_Console = function( params, modelsData )
{
    modelsData = modelsData || {};
    params = params || {};

    var self = this;
    var _models = {};

    this.items = {};

    this.addItem = function( item, key )
    {
        key = key || item.uniqId;
        this.items[key] = item;
    };

    this.getItem = function( key )
    {
        return this.items[key];
    };

    this.getData = function( key )
    {
        _models[key] = _models[key] || new OW_DataModel();

        return _models[key];
    };

    this.hideOtherContents = function( item )
    {
        $.each(this.items, function(i, o)
        {
            if ( item != o )
            {
                o.hideContent();
            }
        });
    };

    this.hideAllContents = function()
    {
        $.each(this.items, function(i, o)
        {
            o.hideContent();
        });
    };

    $.each( modelsData, function (key, data)
    {
        self.getData(key).set(data);
    });

    var command = OW.getPing().addCommand('consoleUpdate',
    {
        before: function()
        {
            var c = this;

            $.each( _models, function (key, model)
            {
                c.params[key] = model.get();
            });
        },
        after: function( dataList )
        {
            $.each( dataList, function (key, data)
            {
                self.getData(key).set(data);
            });

        }
    });

    window.setTimeout(function()
    {
        command.start(params.pingInterval);
    }, params.pingInterval);
};










OW_ConsoleItem =
{
    animate: false,
    opened: false,

    init: function( uniqId, contentUniqId )
    {
        var self = this;

        this.uniqId = uniqId;
        this.contentUniqId = contentUniqId;

        this.$node = $('#' + this.uniqId);
        this.$contentNode = $('#' + this.contentUniqId);
        this._$tooltip = this.$contentNode.find('.console_tooltip');

        this.observers = [];
        this.observers.notify = function(method)
        {
            for ( var i = 0; i < this.length; i++ )
            {
                if ( this[i][method] )
                {
                    this[i][method].call(this[i], self);
                }
            }
        };
    },

    getKey: function()
    {
        return this.uniqId;
    },

    showItem: function()
    {
        this.$node.show();
    },

    hideItem: function()
    {
        if ( this.opened )
        {
            this.hideContent();
        }

        this.$node.hide();
    },

    showContent: function()
    {
        var self = this;

        OW.Console.hideOtherContents(this);

        if ( this.opened )
        {
            return;
        }

        this.$contentNode.show();

        this.animate = true;
        this._$tooltip.css({opacity: 0, top: this.$node.height() - 12}).stop(true, true).animate({top: this.$node.height(), opacity: 1}, 'fast', function()
        {
            self.animate = false;
            OW.addScrolls(self.$contentNode);
            self.observers.notify('afterShow');
        });

        this.opened = true;
        this.observers.notify('beforeShow');


        this.onShow();
        this._onShow();
    },

    hideContent: function()
    {
        var self = this;

        if ( !this.opened )
        {
            return;
        }

        this.animate = true;

        this.observers.notify('beforeHide');
        this._$tooltip.stop(true, true).animate({top: this.$node.height() - 12, opacity: 0}, 'fast', function()
        {
            self.animate = false;
            self.observers.notify('afterHide');

            self.onHide();
            self._onHide();

            self.$contentNode.hide();
        });

        this.opened = false;
    },

    //TODO replace this with bind
    onShow: function() {},
    _onShow: function() {},
    onHide: function() {},
    _onHide: function() {},

    addObserver: function( observer )
    {
        this.observers.push(observer);
    }
};




OW_ConsoleDropdownHover = function( uniqId, contentUniqId )
{
    this.init( uniqId, contentUniqId );

    var self = this;
    var hideTimeout;

    this.$node.hover(function()
    {
        if (self.animate)
        {
            return false;
        }

        if ( hideTimeout )
        {
            window.clearTimeout(hideTimeout);
        }

        self.showContent();
    },
    function()
    {
        hideTimeout = window.setTimeout(function()
        {
            self.hideContent();
        }, 300);
    });
}
OW_ConsoleDropdownHover.prototype = OW_ConsoleItem;


OW_ConsoleDropdownClick = function( uniqId, contentUniqId )
{
    this.init( uniqId, contentUniqId );

    this.initDropdown();
}
$.extend(OW_ConsoleDropdownClick.prototype, OW_ConsoleItem,
{
    initDropdown: function()
    {
        var self = this;

        this.addObserver({
           beforeShow: function()
           {
               self.$node.addClass('ow_console_dropdown_pressed');
           },

           beforeHide: function()
           {
               self.$node.removeClass('ow_console_dropdown_pressed');
           }
        });

        $(document).click(function( e )
        {
            if ( !$(e.target).is(':visible') )
            {
                return;
            }

            var isContent = self.$contentNode.find(e.target).length;
            var isTarget = self.$node.is(e.target) || self.$node.find(e.target).length;

            if ( isTarget && !isContent )
            {
                if ( self.opened )
                {
                    self.hideContent();

                }
                else
                {
                    self.showContent();

                }
            }
            else if ( !isContent )
            {
                self.hideContent();
            }
        });
    }
});




OW_ConsoleDropdownList = function( uniqId, contentUniqId )
{
    this.init( uniqId, contentUniqId );
    this.initDropdown();

    var $counter = $('.OW_ConsoleItemCounter', this.$node),
        $number = $counter.find('.OW_ConsoleItemCounterNumber'),
        $place = $counter.find('.OW_ConsoleItemCounterPlace');

    var shown = false,
        currentNumber = null;

    var numberSetActive = function( active )
    {
        active = active === false ? false : true;
        $place[ active ? 'addClass' : 'removeClass' ]('ow_count_active');
    }

    var numberShow = function( number, animate )
    {
        animate = animate === false ? false : true;

        var placeWidth = $place.width();

        $number.text(number);
        $number.css({visibility: "visible"});
        currentNumber = number;

        var numberWidth = $number.outerWidth();
        $place.animate({width: numberWidth}, 'fast');

        if ( animate )
        {
            $number.css({right: -placeWidth}).animate({right: 0}, 'fast');
        }
    };

    var numberHide = function( callBack )
    {
        var placeWidth = $place.width();

        $number.animate({right: placeWidth}, 'fast', callBack);
    };

    var counterShow = function( callBack )
    {
        var placeWidth;

        $counter.show();
        placeWidth = $place.width();
        $place.css({width: 2}).animate({width: placeWidth}, 'fast', callBack);

        shown = true;
    };

    var counterHide = function( callBack )
    {
        numberHide(function()
        {
            $place.animate({width: 0}, 'fast', function()
            {
                $number.text(0);
                $place.css({width: 'auto'});
                $counter.hide();
                if ( $.isFunction(callBack) ) callBack.apply($counter.get(0));
            });
        });

        shown = false;
    };

    // Public Methods

    this.setCounter = function( number, active )
    {
        var intNumber = parseInt(number);
        intNumber = isNaN(intNumber) ? 0 : intNumber;

        if ( intNumber <= 0 )
        {
            counterHide();

            return;
        }

        if ( !shown )
        {
            counterShow(function()
            {
                numberShow(number);
                numberSetActive(active);
            });
        }
        else if ( number == currentNumber )
        {
            numberSetActive(active);
        }
        else
        {
            numberHide(function()
            {
                numberShow(number);
                numberSetActive(active);
            });
        }
    };
}
OW_ConsoleDropdownList.prototype = OW_ConsoleDropdownClick.prototype;



OW_ConsoleList =
{
    construct: function( params )
    {
        var self = this;

        this.rsp = params.rsp;
        this.key = params.key;
        this.data = OW.Console.getData(this.key);
        this.item = OW.Console.getItem(this.key);

        this.$container = function() {
            return $('.OW_ConsoleListContainer', self.$contentNode);
        };

        this.$list = function() {
            return $('.OW_ConsoleList', self.$container());
        };

        this.$preloader = function() {
            return $('.OW_ConsoleListPreloader', self.$container());
        };

        this.$noContent = function() {
            return $('.OW_ConsoleListNoContent', self.$container());
        };

        this.isListFull = false;
        this.isListLoading = false;
        this.isListLoaded = false;

        this.item.onShow = function()
        {
            this.loadList();
        };

        this.item._onShow = function()
        {
            if ( this.isListLoaded )
            {
                this.updateScroll(true);
            }
        };

        this.item._onHide = function()
        {
            OW.removeScroll(this.$container().get(0));
        };
    },

    clearList: function()
    {
        OW.removeScroll(this.$container().get(0));

        this.$list().empty();
        this.setIsListFull(false);
    },

    loadList: function()
    {
        this.clearList();
        this.showPreloader();

        this.isListLoaded = false;

        this._loadList();
    },

    _loadList: function()
    {
        if ( this.isListLoading )
        {
            return;
        }

        var target = this.key;
        var request = JSON.stringify({
            console: OW.Console.getData('console').get(),
            data: this.data.get(),
            target: target,
            offset: this.getItemsCount(),
            ids: this._getItemIds()
        });

        this._ajaxStart();

        $.ajax({
            type: 'post',
            url: this.rsp,
            context: this,
            dataType: 'json',
            data: {
                request: request
            },
            success: this._ajaxSuccess,
            complete: this._ajaxComplete
        });
    },

    getItemsCount: function()
    {
        return this.getItems().length;
    },

    _getItemIds: function()
    {
        var ids = [];

        this.getItems().each(function()
        {
            var id = $(this).data('id');
            if ( id )
            {
                ids.push(id);
            }
        });

        return ids;
    },

    getItems: function()
    {
        return this.$list().children();
    },

    getItem: function( itemId )
    {
        return $('#' + itemId, this.$list());
    },

    removeItem: function( item )
    {
        var itemObject = $.type(item) == 'object' ? item : this.getItem(item);
        itemObject.remove();

        if ( this.getItemsCount() == 0 )
        {
            this.showNoContent();
        }

        this.updateScroll();
    },

    addItems: function( items, updateScrooll )
    {
        var self = this;

        $.each(items, function(i, item)
        {
            var $item = $(item.html).data('id', item.id);

            $item.find('.console_item_with_url').click(function( e )
            {
                if ( !$(e.target).is('a') )
                {
                    //window.open($(this).data('url'));
                    window.location.href = $(this).data('url');
                }
            });

            self.$list().append($item);
        });

        if ( updateScrooll !== false )
        {
            this.updateScroll();
        }

    },

    showPreloader: function()
    {
        this.$preloader().css({'visibility': 'visible'});
        this.$noContent().hide();
    },

    hidePreloader: function()
    {
        this.$preloader().css({'visibility': 'hidden'});
    },

    showNoContent: function()
    {
        this.$list().hide();
        this.$preloader().hide();
        this.$noContent().show();
    },

    hideNoContent: function()
    {
        this.$noContent().hide();
        this.$list().show();
    },

    updateScroll: function( toTop )
    {
        var self = this;

        toTop = toTop || false;

        if ( this.opened )
        {
            var hasScroll = false;
            if ( this.$container().data().jsp )
            {
                hasScroll = this.$container().data().jsp.getIsScrollableV();
            }
            else
            {
                hasScroll = this.$container().innerHeight() < this.$container().get(0).scrollHeight
            }

            OW.removeScroll(this.$container().get(0));

            if ( !hasScroll )
            {
                this.setIsListFull(true);

                return;
            }

            var jsp = OW.addScroll(this.$container().get(0));

            if ( toTop )
            {
                jsp.scrollToY(0, false);
            }

            this.$container().on('jsp-arrow-change', function( event, isAtTop, isAtBottom, isAtLeft, isAtRight )
            {
                if ( self.isListFull )
                {
                    return;
                }

                if ( isAtBottom )
                {
                    self.showPreloader();
                    self._loadList();
                }
            });
        }
    },

    setIsListFull: function( full )
    {
        this.isListFull = full;
        if ( full )
        {
            this.$preloader().hide();
        }
        else
        {
            this.$preloader().show();
        }
    },

    _ajaxStart: function()
    {
        this.isListLoading = true;
    },

    _ajaxComplete: function()
    {
        this.isListLoading = false;
        this.hidePreloader();
    },

    _ajaxSuccess: function( resp )
    {
        var self = this;

        if ( resp.data )
        {
            this.data.set(resp.data);
        }

        if ( resp.items.length )
        {
            this.addItems(resp.items, false);
        }
        else
        {
            this.setIsListFull(true);
        }

        if( this.getItemsCount() == 0 )
        {
            this.showNoContent();
        }
        else
        {
            this.hideNoContent();
        }

        if ( resp.markup )
        {
            if (resp.markup.styleSheets)
            {
                $.each(resp.markup.styleSheets, function(i, o)
                {
                    OW.addCssFile(o);
                });
            }

            if (resp.markup.styleDeclarations)
            {
                OW.addCss(resp.markup.styleDeclarations);
            }

            if (resp.markup.beforeIncludes)
            {
                OW.addScript(resp.markup.beforeIncludes);
            }

            if (resp.markup.scriptFiles)
            {
                OW.addScriptFiles(resp.markup.scriptFiles, function()
                {
                    if (resp.markup.onloadScript)
                    {
                        OW.addScript(resp.markup.onloadScript);
                    }
                });
            }
            else
            {
                if (resp.markup.onloadScript)
                {
                    OW.addScript(markup.onloadScript);
                }
            }
        }

        var scrollToTop = !this.isListLoaded;

        window.setTimeout(function() {
            self.updateScroll(scrollToTop);
        });


        this.isListLoaded = true;
    }
};



OW_Invitation = function( itemKey, params )
{
    var listLoaded = false;

    var listLoaded = false;
    var model, list, counter;

    //public methods

    this.removeItem = function( invitationKey )
    {
        var item = list.getItem(invitationKey);
        var c = {};

        if ( item.hasClass('ow_console_new_message') )
        {
            c["new"] = counter.get("new") - 1;
        }
        c["all"] = counter.get("all") - 1;
        counter.set(c);

        list.removeItem(item);

        return this;
    };

    this.send = function( command, data )
    {
        var request = $.ajax({
            url: params.rsp,
            type: "POST",
            data: {
                "command": command,
                "data": JSON.stringify(data)
            },
            dataType: "json"
        });

        request.done(function( res )
        {
            if ( res && res.script )
            {
                OW.addScript(res.script);
            }
        });

        return this;
    };

    //code

    model = OW.Console.getData(itemKey);
    list = OW.Console.getItem(itemKey);
    counter = new OW_DataModel();

    counter.addObserver(function()
    {
        var counterNumber = 0,
        newCount = counter.get('new');
        counterNumber = newCount > 0 ? newCount : counter.get('all');

        list.setCounter(counterNumber, newCount > 0);

        if ( counterNumber > 0 )
        {
            list.showItem();
        }
    });

    model.addObserver(function()
    {
        if ( !list.opened )
        {
            counter.set(model.get('counter'));
        }

        if ( model.get('listFull') )
        {
            list.setIsListFull(true);
        }
    });

    list.onHide = function()
    {
        list.getItems().removeClass('ow_console_new_message');
        counter.set('new', 0);
        model.set('counter', counter.get());
    };

    list.onShow = function()
    {
        if ( counter.get('all') <= 0 )
        {
            this.showNoContent();

            return;
        }

        if ( counter.get('new') > 0 || !listLoaded )
        {
            this.loadList();
            listLoaded = true;
        }
    };
}

OW.Invitation = null;;

