var Cornerstone = {};
Cornerstone.system = {};
Cornerstone.system.Event = {
    isInProcess: false,
    startTime: 0,
    performInProcessAnimation: function(cursorStatus) {
        var backgrounds = ["url('/_static/system/images/cursor-1.gif')", "url('/_static/system/images/cursor-2.gif')",
            "url('/_static/system/images/cursor-3.gif')"];
        var i = 0;
        for (; i < backgrounds.length; ++i) {
            if (cursorStatus.style.backgroundImage.indexOf(i + 1) != -1) {
                ++i;
                break;
            }
        }
        if (Cornerstone.system.Event.isInProcess) {
            if (i >= 3) i = 0;
            cursorStatus.style.backgroundImage = backgrounds[i];
            if (((new Date()).getTime() - this.startTime) >= 5000) {
                this.isTimeout = true;
                Cornerstone.system.Event.switchInProcessOff();
            } else {
                setTimeout(function() {Cornerstone.system.Event.performInProcessAnimation(cursorStatus)}, 333);
            }
        }
    },
    isTimeout: false,
    cursorX: -1,
    cursorY: -1,
    isActiveElementCursor: false,
    setCursorPosition: function(event) {
        this.cursorX = event.clientX;
        this.cursorY = event.clientY;
    },
    getCursorStatusElement: function() {
        this.startTime = (new Date()).getTime();
        var cursorStatus = window.top.document.getElementById('cursor_status_');
        if (cursorStatus == null) {
            cursorStatus = window.top.document.createElement('div');
            cursorStatus.id = 'cursor_status_';
            cursorStatus.innerHTML = ' ';
            cursorStatus.style.width = '20px';
            cursorStatus.style.height = '6px';
            cursorStatus.style.position = 'fixed';
            cursorStatus.style.zIndex = 9010;
            window.top.document.body.appendChild(cursorStatus);
            $(document).mousemove(function (event) {
                Cornerstone.system.Event.setCursorPosition(event);
                if (Cornerstone.system.Event.isInProcess || cursorStatus.style.display == 'block') {

                    if (Cornerstone.system.Event.isInProcess) cursorStatus.style.display = 'block';
                    cursorStatus.style.left = Cornerstone.system.Event.cursorX + 15 + 'px';
                    cursorStatus.style.top = Cornerstone.system.Event.cursorY + 23 + 'px';
                    this.isActiveElementCursor = false;
                }
            });
            $(document).mouseout(function (event) {
                this.cursorX = -1;
                this.cursorY = -1;
                cursorStatus.style.display = 'none';
            });
        }
        return cursorStatus;
    },
    switchInProcessOn: function() {
        Cornerstone.system.Event.isInProcess = true;
        this.startTime = (new Date()).getTime();
        var cursorStatus = this.getCursorStatusElement();
        if (this.cursorX == -1 || this.cursorX == -1) {
            //Cursor never been on page
            if (document.activeElement) {
                var el = $(document.activeElement);
                var offset = el.offset();
                this.cursorX = offset.left + el.width() - 12 - $(window).scrollLeft();
                this.cursorY = offset.top + el.height() - 20 - $(window).scrollTop();
                this.isActiveElementCursor = true;
            } else {
                cursorStatus.style.display = 'none';
            }
        }
        if (this.cursorX != -1 && this.cursorY != -1) {
            cursorStatus.style.display = 'block';
        }
        cursorStatus.style.left = this.cursorX + 15 + 'px';
        cursorStatus.style.top =  this.cursorY + 23 + 'px';
        cursorStatus.style.backgroundImage = "url('/_static/system/images/cursor-1.gif')";
        //cursorStatus.style.backgroundImage = "url('/_static/system/images/cursor-1.png')";
        setTimeout(function() {Cornerstone.system.Event.performInProcessAnimation(cursorStatus)}, 333);
    },
    switchInProcessOff: function() {
        window.top.systemSubmitElementsInProgress_ = 0;
        Cornerstone.system.Event.isInProcess = false;
        var cursorStatus = window.top.document.getElementById('cursor_status_');
        if (cursorStatus != null) {
            if (this.isActiveElementCursor) {
                this.cursorX = -1;
                this.cursorY = -1;
                this.isActiveElementCursor = false;
            }
            var showTime = 500;
            if (this.isTimeout) {
                showTime = 1000;
                cursorStatus.style.backgroundImage = "url('/_static/system/images/cursor-timeout.gif')";
            } else {
                cursorStatus.style.backgroundImage = "url('/_static/system/images/cursor-ok.gif')";
            }
            setTimeout(function() {cursorStatus.style.display = 'none'}, showTime);
        }
    }
};

Cornerstone.showModalDialog = function(code)
{
    var dialog = $('#modal_dialog_');
    if (dialog.size() == 0) {
        $('body').append(
            '<div class="ui-modal-dialog" id="modal_dialog_"' +
            ' style="display:none"><table cellspacing="0" cellpadding="0"' +
            ' style="width:100%;height:100%">' +
            '<tr><td style="font-size:0px;height:6px;width:6px;background:' +
            'url(&quot;/_static/website/images/template/tl.png&quot;)' +
            ' no-repeat left top transparent;">&nbsp;</td>' +
            '<td style="font-size:0px;background-color:white;height:6px;' +
            'border-top:1px solid #1183A8;">&nbsp;</td>' +
            '<td style="font-size:0px;height:6px; width:6px;background:' +
            'url(&quot;/_static/website/images/template/tr.png&quot;)' +
            ' no-repeat right top transparent;">&nbsp;</td></tr>' +
            '<tr><td style="background-color:white;width:5px;' +
            'border-left: 1px solid #1183A8;">&nbsp;</td>' +
            '<td id="modal_dialog_content_" style="background-color:white;">' +
            '</td><td style="background-color:white;width:5px;' +
            'border-right: 1px solid #1183A8;">&nbsp;</td></tr>' +
            '<tr><td style="font-size:0px;height:6px;width:6px;background:' +
            'url(&quot;/_static/website/images/template/blr.png&quot;)' +
            ' no-repeat left bottom transparent;">&nbsp;</td>' +
            '<td style="font-size:0px;background-color:white;height:6px;' +
            'border-bottom:1px solid #1183A8;">&nbsp;</td>' +
            '<td style="font-size:0px;height:6px;width:6px;background:' +
            'url(&quot;/_static/website/images/template/brr.png&quot;)' +
            ' no-repeat right bottom transparent;">&nbsp;</td></tr></table>' +
            '</div>');
        dialog = $('#modal_dialog_').dialog({modal:true, width: 466,
            zIndex: 9002});
    } else {
        $('#modal_dialog_content_').empty();
    }
    $('#modal_dialog_content_').append(code);
    dialog.dialog('open');
    $('.ui-widget-overlay').addClass('ui-modal-dialog-overlay');
}

Cornerstone.hideModalDialog = function()
{
    var dialog = $('#modal_dialog_');
    if (dialog.size() == 0) {
        return;
    }

    dialog.dialog('close');
    $('#modal_dialog_content_').empty();
    $('.ui-widget-overlay').removeClass('ui-modal-dialog-overlay');
}

Cornerstone.parseFormId = function(longId)
{
    return longId.substring(0, longId.indexOf('____'));
}

/**
 * Parse color to hex
 *
 */
Cornerstone.parseColor = function(color)
{
    if ('rgb(' == color.substring(0, 4).toLowerCase()) {
        var colors = color.substring(4, color.length-1).split(',');
        hex = '0123456789ABCDEF';
        var result = '';
        for (var i = 0; i < colors.length; i++) {
            n = parseInt(colors[i]);
            d = Math.floor(n / 16);
            c = n - d * 16;
            result += hex.charAt(d) + '' + hex.charAt(c);
        }
        return result;
    } else if ('#' == color.substring(0, 1)) {
        return color.substring(1, color.length);
    }
    return '';
}

Cornerstone.Audio = {};

Cornerstone.Audio.buildFlashVars = function(id, duration, start, autostart, file)
{
    primary = $('#' + id + '_primary');
    secondary = $('#' + id + '_secondary');
    var flashVars = {
        'type' : 'sound',
        'id' : id + '_player',
        'duration' : duration,
        'start' : start,
        'autostart' : autostart,
        'file' : file,
        'backcolor' : Cornerstone.parseColor(primary.css('background-color')),
        'frontcolor' : Cornerstone.parseColor(primary.css('color')),
        'lightcolor' : Cornerstone.parseColor(secondary.css('color')),
        'screencolor' : Cornerstone.parseColor(secondary.css('background-color'))
    };

    skinUrl = primary.css('background-image');
    if (skinUrl.substring(0, 4) == 'url(') {
        skinUrl = skinUrl.substring(4, skinUrl.length-1);
        flashVars.skin = skinUrl;
    }

    return jQuery.param(flashVars);
}

Cornerstone.Audio.createPlayer = function(id, duration, start, autostart, file)
{
    width = $('#' + id + '_primary').css('width');
    height = $('#' + id + '_primary').css('height');
    if (!width || width == 'auto') {
        width = 250;
    }
    if (!height || height == 'auto') {
        height = 20;
    }
    var player = new SWFObject('/mediaplayer/player-viral.swf', id + '_player',
        width, height, '9');
    player.addParam('allowscriptaccess', 'always');
    player.addParam('wmode', 'transparent');
    var flashVars = Cornerstone.Audio.buildFlashVars(id, duration, start,
        autostart, file);
    player.addParam('flashvars', '&' + flashVars);
    player.write(id);
    $('#' + id + '_player').css('vertical-align', 'top');
}

Cornerstone.Social = {};

Cornerstone.Social.over = function(commentRowId, isReportOver, isHideDate)
{
    var commentRow = $('#' + commentRowId);
    var baseName = commentRowId.substring(0, commentRowId.indexOf('____'));
    var commentId = commentRowId.substring(commentRowId.lastIndexOf('_')+1, commentRowId.length);
    commentRow.mouseenter(function() {
        $('#' + baseName + '____' + 'comment_edit_link_' + commentId).show();
        /*console.log($('#' + baseName + '____' + 'comment_edit_link_' + commentId));*/
        $('#' + baseName + '____' + 'comment_delete_link_' + commentId).show();
        if (isHideDate) {
            $('#' + baseName + '____' + 'comment_posted_date_' + commentId).hide();
        }
        if (isReportOver) {
            $('#' + baseName + '____' + 'comment_report_link_' + commentId).show();
        }
    });
    commentRow.mouseleave(function() {
        $('#' + baseName + '____' + 'comment_edit_link_' + commentId).hide();
        $('#' + baseName + '____' + 'comment_delete_link_' + commentId).hide();
        if (isHideDate) {
            $('#' + baseName + '____' + 'comment_posted_date_' + commentId).show();
        }
        if (isReportOver) {
            $('#' + baseName + '____' + 'comment_report_link_' + commentId).hide();
        }
        var reportPanel = $('#' + baseName + '____' + 'comment_report_panel_' + commentId);
        if (reportPanel) {
            Cornerstone.Social.hidePanel(baseName + '____' + 'comment_report_panel_' + commentId);
        }
    });
    commentRow.removeAttr('onmouseover');
    commentRow.triggerHandler('mouseenter');
}

Cornerstone.Social.showPanel = function(linkId)
{
    var baseName = linkId.substring(0, linkId.indexOf('____'));
    var commentId = linkId.substring(linkId.lastIndexOf('_')+1, linkId.length);
    var reportLink = $('#' + linkId);
    var reportPanel = $('#' + baseName + '____' + 'comment_report_panel_'
        + commentId);
    if (reportPanel.is(':visible')) {
        Cornerstone.Social.hidePanel(baseName + '____' + 'comment_report_panel_'
            + commentId);
        return;
    }
    reportLink.removeClass('website-comment-report-link')
        .addClass('website-comment-report-link-active');
//    var position = reportLink.position();
    var offset = reportLink.offset();

    // We need to set absolute positioning.
    // But absolute position may count from parent relative positioned node.
    var offsetParent = reportLink.offsetParent();
    if (offsetParent.get(0).tagName != 'BODY') {
        var parentOffset = offsetParent.offset();
        offset.top -= parentOffset.top;
        offset.left -= parentOffset.left;
    }

    /*console.log('position.top = %s, outerHeight = %s, position.left = %s', position.top,
    		reportLink.outerHeight(), position.left);*/
    /*reportPanel.css('top', position.top + reportLink.outerHeight())
        .css('left', position.left + parseInt(reportLink.css('margin-left')))
        .slideDown('fast');*/
    reportPanel.css('top', offset.top + reportLink.outerHeight())
    	.css('left', offset.left)
    	.slideDown('fast');
}

Cornerstone.Social.hidePanel = function(panelId)
{
   var reportPanel = $('#' + panelId);
   if (reportPanel) {
       var baseName = panelId.substring(0, panelId.indexOf('____'));
       var commentId = panelId.substring(panelId.lastIndexOf('_')+1,
           panelId.length);
       var reportLink = $('#' + baseName + '____' + 'comment_report_link_'
           + commentId);
       reportLink.removeClass('website-comment-report-link-active')
           .addClass('website-comment-report-link');
       reportPanel.hide();
   }
}

Cornerstone.Social.storeCommentId = function(hiddenId, cid)
{
    var baseName = hiddenId.substring(0, hiddenId.indexOf('____'));
    var commentId = hiddenId.substring(hiddenId.lastIndexOf('_')+1, hiddenId.length);
    $('#' + baseName + '____' + 'previous_comment_id').val($('#' + hiddenId).val());
   /* $('#' + hiddenId).val(cid);*/
    console.log($('#' + hiddenId).val());
}

Cornerstone.Social.statusComments = function(blockId, containerId, isHide, hideText, showText)
{
    var block = $('#' + blockId);
    var container = $('#' + containerId);
    var shadowTable = $('#' + Cornerstone.parseFormId(containerId) + '____shade_block');

    var commentLink = $('#' + Cornerstone.parseFormId(containerId) + '____comment_link');


    if (!container.is(':visible') && !isHide) {
        var position = block.position();
        var x = position.left;
        var y = position.top+block.outerHeight();
        var dx = shadowTable.children().children(':first').children(':first').children(':first');
        shadowTable.css('top', y - 4)
            .css('position', 'absolute').show().css('left', x-dx.width());
        container.width(block.innerWidth());
        /*$('#' + Cornerstone.parseFormId(containerId) + '____shadow_block_body_l')
            .height(container.height()-dx.height()-50);*/
        container.show();

        commentLink.html(showText);
    } else {
        shadowTable.hide();
        container.hide();
        commentLink.html(hideText);
    }

}

Cornerstone.Social.expandStatusCommentForm = function(formId)
{
    var postCommentRow = $('#' + formId + '____post_comment_row');
    if (!postCommentRow.is(':visible')) {
        postCommentRow.show();
        formSetTextareaParameters(formId + '____post_comment_text', 4);
        $('#' + formId + '____post_comment_text').keyup(
        function(event) {
            formExpandTextarea($('#' + formId + '____post_comment_text'), 4, 11);
        }
        );
    }
}

/**
 * Javascript processing class for Cornerstone_Ui_Form_Rating object
 *
 */
Cornerstone.Rating = function(elementId, maxRate, averageValue, classEmpty,
    classHalf, classFull)
{
    this.id = elementId;
    this.classEmpty = classEmpty;
    this.classHalf = classHalf;
    this.classFull = classFull;
    // This is needed for passing "this" object to mouseleave method
    var self = this;
    // Set classes for stars after mouse has left control block
    $('#' + elementId).mouseleave(function(){
        self.clearStars();
        var elements = $('#' + elementId + ' > *:not(:last)');
        elements.removeClass(classFull + ' ' + classHalf + ' ' + classEmpty);
        elements.each(function(i, elem) {
           if (i+1 <= Math.floor(averageValue) || i+1 == averageValue) {
                $(this).addClass(classFull);
            } else if (i+1 == Math.ceil(averageValue) && i+1 > averageValue) {
                $(this).addClass(classHalf);
            } else if (i+1 > Math.ceil(averageValue)) {
                $(this).addClass(classEmpty);
            }
        });
    });
}

Cornerstone.Rating.prototype.clearStars = function()
{
    $('#' + this.id + ' > *:not(:last)')
        .removeClass(this.classFull + ' ' + this.classHalf)
        .addClass(this.classEmpty);
    return this;
}

Cornerstone.Rating.prototype.lightStar = function(num)
{
    $('#' + this.id + ' > *:lt(' + num + ')').removeClass(this.classEmpty)
        .addClass(this.classFull);
    return this;
}

Cornerstone.Rating.prototype.setVote = function(num)
{
    $('#' + this.id+ '_vote').val(num);
}

Cornerstone.ui = {
    tips: [],
    updateHintPositions: function () {
        var self = this;

        for (var id in self.tips) {
            self.tips[id].updatePosition();
        }
    },
    destroyHint: function (id) {
        var self = this;

        var api = self.tips[id];
        if (api != null) {
        	try {
                api.destroy();
            } catch (e) {}
            delete self.tips[id];
        }
    },
    destroyChildHints: function (id) {
        var self = this;

        var newTips = [];
        for (var childId in self.tips) {
            if (childId.indexOf(id) == 0) {
            	var api = self.tips[childId];
            	if (api != null) {
                    try {
                        api.destroy();
                    } catch (e) {}
                    self.tips[childId] = null;
            	}
            	continue;
            }

            newTips[childId] = self.tips[childId];
        }
        self.tips = newTips;
    },
    hint: function (id, messages, maxWidth) {
        var self = this;

        if (maxWidth == null) maxWidth = 400;

        self.destroyHint(id);

        var el = $('#' + id).get(0);
        if (el == null) return;

        var width = el.offsetWidth;
        if (width < 98) width = 98;
        if (width > maxWidth) width = maxWidth;

        var content = '<div class="ui-hint"><div class="ui-hint-tip"></div>' +
            '<div class="ui-roundable"><div class="ui-corner ui-tr">' +
            '<div class="ui-corner ui-tl">&nbsp;</div></div>' +
            '<div class="ui-corner ui-br"><div class="ui-corner ui-bl">' +
            '<div class="ui-content">' +
            '<a class="ui-hint-close" href="#" onclick="' +
            'Cornerstone.ui.destroyHint(\'' + id + '\');return false;"> </a>';
        for (var i = 0; i < messages.length; ++i) {
            content += '<div class="ui-hint-message">' + messages[i] + '</div>';
        }
        content += '</div></div></div></div></div>';

        $('#' + id).qtip({
            content: content,
            show: { ready: true, when: { event: false } },
            hide: { when: { event: 'focus' } },
            position: {
                corner: { target: 'bottomLeft', tooltip: 'topLeft' }
            },
            style: {
                width: width,
                padding: '0px',
                overflow: 'visible',
                background: 'transparent',
                color: '#000000',
                textAlign: 'left',
                border: 0,
                tip: false
            },
            api: {
                onHide: function () {
                	self.destroyHint(id);
                }
            }
       });
       self.tips[id] = $('#' + id).qtip('api');
    },
    helpHintToggle: function (element, message) {
        element = $(element);
        // Need toggle function here but use destroy instead
        if (typeof element.data('qtip') != 'object' ||
            element.data('qtip') == null)
        {
	        var width = 232;
            var content = '<div class="ui-hint-help-message">' + message +
                '</div>';
            element.qtip({
                content: content,
                show: { ready: true, when: { event: false } },
                hide: { when: { event: 'unfocus' } },
                position: { corner: { target: 'bottomLeft', tooltip: 'topLeft' } },
                style: {
                    width: width,
                    padding: '0px',
                    overflow: 'visible',
                    background: 'transparent',
                    color: '#000000',
                    textAlign: 'left',
                    border: 0,
                    tip: false
                },
                api: {
                    onShow: function () {
                        element.data('qtip-hidden', false);
                    },
                    onHide: function () {
                    	element.data('qtip-hidden', true);
                    }
                }
            });
            return;
        }
        if (element.data('qtip-hidden')) {
            element.qtip('api').show();
        } else {
        	element.qtip('api').hide();
        }
    },
    _multiAutoTextMinWidth: 142,
    _multiAutoInProgress: false,
    _multiAutoTimeout: false,
    _multiAutoLinks: [],
    _multiAutoSelect: 0,
    multiAutoType: function (event, id, url, textEl, isCustom) {
        var self = this;
        if (self._multiAutoTimeout !== false) {
            clearTimeout(self._multiAutoTimeout);
            self._multiAutoTimeout = false;
        }

        if (isEnterKey(event) || isTabKey(event)) {
            if (isCustom) {
                if (isTabKey(event) || self._multiAutoSelect == 0) {
                    self.multiAutoAdd($('#' + id));
                } else if (self._multiAutoLinks.length > self._multiAutoSelect) {
                    self._multiAutoLinks[self._multiAutoSelect].click();
                }
            } else {
                if (isEnterKey(event) &&
                    self._multiAutoLinks.length > self._multiAutoSelect)
                {
                    self._multiAutoLinks[self._multiAutoSelect].click();
                }
                $('#' + id + ' .ui-auto-list').hide();
            }
            return true;
        }

        if (isCodeKey(event, 188) && isCustom) { // ","
            var textEl = $(textEl);
            var value = textEl.val();
            if (value.length > 1) {
                if (value[value.length - 2] != '\\') {
                    textEl.val(value.substr(0, value.length - 1));
                    self.multiAutoAdd($('#' + id));
                    return true;
                } else {
                    textEl.val(value.substr(0, value.length - 2) + ',');
                }
            }
        }

        if (self._multiAutoLinks.length > 1) {
            if (isCodeKey(event, 38)) { // UP
                self._multiAutoLinks[self._multiAutoSelect].parent().removeClass('ui-selected');
                if (self._multiAutoSelect == 0) {
                    self._multiAutoSelect = self._multiAutoLinks.length - 1; 
                } else {
                    --self._multiAutoSelect;
                }
                self._multiAutoLinks[self._multiAutoSelect].parent().addClass('ui-selected');
                return false;
            } else if (isCodeKey(event, 40)) { // DOWN
                self._multiAutoLinks[self._multiAutoSelect].parent().removeClass('ui-selected');
                if (self._multiAutoSelect == (self._multiAutoLinks.length - 1)) {
                    self._multiAutoSelect = 0; 
                } else {
                    ++self._multiAutoSelect;
                }
                self._multiAutoLinks[self._multiAutoSelect].parent().addClass('ui-selected');
                return false;
            }
        }

        self.adjustTextInputWidth(textEl, self._multiAutoTextMinWidth);
        
        var getExistingIds = function () {
            var result = {};
            $('#' + id + ' .ui-items-list .ui-remove-item[rel]').each(
                function (i, e) { result[$(e).attr('rel')] = true;});
            return result;
        };

        self._multiAutoTimeout = setTimeout(function () {
            if (self._multiAutoInProgress) {
                self.multiAutoType(event, id, url, textEl);
                return;
            }
            self._multiAutoInProgress = true;
            var value = $(textEl).val();
            
            if (jQuery.trim(value) == '') {
                $('#' + id + ' .ui-auto-list').hide();
                self._multiAutoInProgress = false;
                return;
            }

            $.ajax({
                url: url + encodeURI(value),
                type: "GET",
                dataType: 'json',
                success: function(response) {
                    var container = $('#' + id);
                    var list = $('.ui-auto-list', container).empty();
    
                    self._multiAutoLinks = [];
                    self._multiAutoSelect = 0;
                    if (jQuery.trim($(textEl).val()) == '') {
                        $('#' + id + ' .ui-auto-list').hide();
                        self._multiAutoInProgress = false;
                        return;
                    }

                    var customText = $('.ui-add-text', container).html();

                    if (isCustom) {
                        var itemDiv = $('<div class="ui-item ui-custom ui-selected"></div>');
                        var itemLink = $('<a href="" onclick="' +
                            'Cornerstone.ui.multiAutoAddClick(this);' +
                            'return false;"></a>').text(
                            customText.replace('%s', '"' + value + '"'));
                        list.append(itemDiv.append(itemLink));
                        self._multiAutoLinks[self._multiAutoLinks.length] =
                            itemLink;
                    }

                    var existingIds = getExistingIds();
                    var isFirst = true;
                    for (var itemId in response) {
                        if (existingIds[itemId] != null) continue;

                        var itemDiv = $('<div class="ui-item"></div>');
                        if (isFirst) {
                            isFirst = false;
                            if (!isCustom) { 
                                itemDiv.addClass('ui-selected');
                            }
                        }
                        var itemLink = $('<a href="" rel="' + itemId + '" onclick="' +
                            'Cornerstone.ui.multiAutoSelect(this);' +
                            'return false;"></a>').text(response[itemId]);
                        self._multiAutoLinks[self._multiAutoLinks.length] =
                            itemLink;
                        var preparedText = itemLink.html();
                        var searchTerm = $('<span></span>').text(value).html();
                        preparedText = preparedText.replace(
                            new RegExp('(' + searchTerm + ')', 'gi'),
                            '<span class="ui-search-term">$1</span>');
                        list.append(itemDiv.append(itemLink.html(preparedText)));
/*                        list.append('<div class="ui-item">' +
                            '<a href="" rel="' + itemId + '" onclick="' +
                            'Cornerstone.ui.multiAutoSelect(this);' +
                            'return false;">' + response[itemId] +
                            '</a></div>');*/
                    }
                    list.show().width($('.ui-items-list', container).innerWidth());
                    self._multiAutoInProgress = false;
                },
                error: function (request, status, error) {
                  if (status == 'timeout') {
                      alert('Request is timed out. Check your internet connection.');
                  } else if (error != null) {
                      alert(error);
                  }
                  self._multiAutoInProgress = false;
                }
            });            
        }, 300);
        return true;
    },
    _multiAutoAdd: function (container, itemId, text, idSuffix) {
        var list = $('.ui-items-list', container);
        var item = $('<div class="ui-item"></div>');
        var hidden = $('<input type="hidden" name="' + container.attr('id') +
            '[' + itemId + ']' + idSuffix + '" value="" />').val(text);
        item.append(hidden);
        var span = $('<span class="ui-item-text"></span>');
        span.text(text);
        item.append(span);
        item.append('<a class="ui-remove-item" href="" rel="' + itemId + '"' +
        ' onclick="$(this).parent().remove();return false;">&nbsp;</a>');
        $('.ui-input', list).before(item);
        $('.ui-auto-list', container).hide();
        this._multiAutoLinks = [];
        this._multiAutoSelect = 0;
    },
    multiAutoAdd: function (container) {
        var textEl = $('#' + container.attr('id') + '_text');
        var text = jQuery.trim(textEl.val());
        if (text == '') return;
        textEl.val('').width(this._multiAutoTextMinWidth);
        
        this._multiAutoAdd(container, 0, text, '[]');
        textEl.focus();
    },
    multiAutoAddClick: function (e) {
        var container = $(e).parent().parent().parent();
        
        this.multiAutoAdd(container);
    },
    multiAutoSelect: function (e) {
        e = $(e);
        var container = e.parent().parent().parent();
        var text = e.text();
        var itemId = e.attr('rel');
        var textEl = $('#' + container.attr('id') + '_text');
        textEl.val('').width(this._multiAutoTextMinWidth);

        this._multiAutoAdd(container, itemId, text, '');
        e.remove();
        textEl.focus();
    },
    textInputValueWidth: function (e) {
        e = $(e);
        var rawE = e.get(0);
        // It does not work for default style in IE! You need to specify
        // some custom style to input itself before this measurement.
        var fs = e.css("font-size");
        var ff = e.css("font-family");
        var fw = e.css("font-weight");

        var span = $('<span></span>');
        span.text(e.val() + 'MM'); // Compensate padding and new char
        span.css({"position":"absolute",
          "visibility":"hidden","height":"auto","width":"auto",
          "font-size": fs,
          "font-family": ff,
          "font-weight": fw});
        e.parent().append(span);
        width = span.width();
        span.remove();
        return width;
    },
    adjustTextInputWidth: function (e, minWidth) {
        var self = this;
        setTimeout(function(){
            if ($(e).val() == '') {
                $(e).width(minWidth);
                $(e).focus();
                return;
            }

            var width = self.textInputValueWidth(e);
            $(e).width(width < minWidth ? minWidth : width);
        }, 100);
    },
    GeoLocations: function(id) {
        var latlng = new google.maps.LatLng(40, 12);
        var myOptions = {
          zoom: 1,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var div = $("#" + id + " .map");
        var map = new google.maps.Map(div.get(0), myOptions);

        // Expand control
        var control = $('<div></div>');
        control.css({width: '16px', height: '16px',
          'background-image': "url('/_static/cs/images/maximize.png')", cursor: 'pointer',
          margin: '6px 6px 0px 0px'});
        control.click(function() {
          if (div.css('position') == 'relative') {
            control.css('background-image', "url('/_static/cs/images/minimize.png')");
            div.css({position: 'fixed', 'z-index': 2000, top: '0px', left: '0px',
                bottom: '0px', right: '0px'});
          } else {
            control.css('background-image', "url('/_static/cs/images/maximize.png')");
            div.css('position', 'relative');
          }
          google.maps.event.trigger(map, 'resize');
        });
        var el = control.get(0);
        el.index = 0;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(el);

        // Markers
        var uiControl = $("#" + id);

        var addMarker = function(hiddenInput) {
            var value = hiddenInput.val();
            var arr = value.split(';');
            if (arr.length < 3) return false;

            var lat = arr.shift();
            var lng = arr.shift();
            var text = arr.join(';');
            var location = new google.maps.LatLng(lat, lng);

            var marker = new google.maps.Marker({
                position: location,
                map: map,
                title: text
            });
            google.maps.event.addListener(marker, 'click', function(event) {
                marker.setMap(null);
                marker = null;
                hiddenInput.remove();
            });
            return location;
        };

        var addMarkerByLocation = function(location) {
            var hidden = $('<input type="hidden" name="' + id + '[0][]" />');
            hidden.val(location.lat() + ';' + location.lng() + ';' +
                input.val());
            uiControl.append(hidden);
            addMarker(hidden);
        };

        var initialBounds = null;
        var hiddenElements = $('input[type="hidden"]', uiControl);
        if (hiddenElements.size() > 1) {
            var minLat = 90;
            var maxLat = -90;
            var minLng = 180;
            var maxLng = -180;
            hiddenElements.each(function(i, el) {
                if (i == 0) return;

                var location = addMarker($(el));
                if (location != null && location != false) {
                    if (minLat > location.lat()) minLat = location.lat();
                    if (maxLat < location.lat()) maxLat = location.lat();
                    if (minLng > location.lng()) minLng = location.lng();
                    if (maxLng < location.lng()) maxLng = location.lng();
                }
            });
            if (minLat != 90 && maxLat != -90) {
                map.setZoom(15);
                if (minLat == maxLat) {
                    map.setCenter(new google.maps.LatLng(minLat, minLng));
                } else {
                    var latMargin = (maxLat - minLat)/10;
                    var lngMargin = (maxLng - minLng)/10;
                    var sw = new google.maps.LatLng(minLat - latMargin,
                        minLng - latMargin);
                    var ne = new google.maps.LatLng(maxLat + latMargin,
                        maxLng + latMargin);
                    initialBounds = new google.maps.LatLngBounds(sw, ne); 
                    map.fitBounds(initialBounds);
                }
            }
        }
        div.bind('resize', function () {
            var center = map.getCenter();
            google.maps.event.trigger(map, 'resize');
            map.setCenter(center);
            if (initialBounds != null) {
                map.setZoom(15);
                map.fitBounds(initialBounds);
            }
        });
        google.maps.event.addListener(map, 'click', function(event) {
            addMarkerByLocation(event.latLng);
        });

        // Geocoder search
        var geocoder = new google.maps.Geocoder();
        var input = $('#' + id + ' .ui-input');
        var button = $('#' + id + ' .ui-button');
        input.keyup(function() {
            if (isEnterKey(event)) button.click();
        });
        button.click(function() {
            var address = input.val();
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
/*var dump = function (val) {
    if (val.toString() == '[object Object]') {
        var str = ' {';
        for (var name in val) {
            str += name + ': ' + dump(val[name]) + "\n"; 
        }
        str += '}';
        return str;
    }
    if (typeof(val) == 'object' && val[0] != null && val.length > 0) {
        var str = '[';
        for (var i = 0; i < val.length; ++i) {
            str += dump(val[i]) + "\n"; 
        }
        str += ']';
        return str;
    }
    return val.toString();
}
for (var i = 0; i< results.length; ++i) {
    alert(i + ' :' + dump(results[i]));
}*/
                  var location = results[0].geometry.location;
                  map.setCenter(location);
                  if (map.getZoom() == 1) map.setZoom(10);
                  addMarkerByLocation(location);
                } else {
                  // do nothing
                }
          });
        });
    }
};

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function langSwitchOn(container)
{

}

function langSwitchOff(container)
{

}

function checkPasswords(passwordNames, message)
{
    for (var i = 0; i < passwordNames.length; ++i)
    {
    	var passwordName = passwordNames[i];
        var p1 = document.getElementsByName(passwordName)[0];
        var parts = passwordName.split("[", 2);
        var passwordConfirmName = (parts.length > 1 ? (parts[0] + "[confirm_" + parts[1]) : "confirm_" + passwordName);
        var p2 = document.getElementsByName(passwordConfirmName)[0];
        if (p2 == null)
        {
          alert("Cannot check password");
          return false;
        }
        if (p1.value != p2.value)
        {
            alert(message);
            p1.focus();
            return false;
        }
    }
    return true;
}

function getControlValue(element)
{
    if (element.tagName == "SELECT")
    {
        return element.options[element.selectedIndex].value;
    }
    return element.value;
}

function checkRequiredFields(fieldNames, message)
{
    for (var i = 0; i < fieldNames.length; ++i)
    {
        var field = document.getElementsByName(fieldNames[i])[0];
        if (field == null) continue;
        var value = getControlValue(field);
        if (value == "")
        {
            alert(message);
            field.focus();
            return false;
        }
    }
    return true;
}

function changeValues(values)
{
    for (var i = 0; i < values.length; ++i)
    {
        var input = document.getElementsByName(values[i][0])[0];
        if (input == null) continue;
        input.value = values[i][1];
    }
}

function submitParentForm(element)
{
    while (element != null && element.tagName != 'FORM') {
        element = element.parentNode;
    }
    if (element != null) {
        element.submit();
    }
}

function getCookieValue(name)
{
    var multiline = RegExp.multiline
    RegExp.multiline = true;
    var exp = new RegExp(name + "=([^;]*)", "g");
    var cookies = "" + document.cookie;
    exp.exec(cookies);
    var value = RegExp.$1;
    RegExp.multiline = multiline;
    return value;
}

// ---- Sorting

var csIsDescending = false;
var csColumnIndex = 0;
var csColumnType = 'string';

function getCellValue(cell, type)
{
  var value = cell.getAttribute('sort');
  if (value == null)
  {
    if (cell.firstChild && cell.firstChild.tagName == 'A')
    {
      value = cell.firstChild.innerHTML;
    }
    else
    {
      value = cell.innerHTML;
    }
  }
  if (type == 'integer')
  {
    value = parseInt(value);
    if (isNaN(value)) value = 0;
  }
  else if (type == 'float' || type == 'money')
  {
    value = parseFloat(value);
    if (isNaN(value)) value = 0;
  }
  return value;
}

function getNextCell(cell)
{
  do
  {
    cell = cell.nextSibling;
  }
  while (cell != null && cell.tagName != 'TH' && cell.tagName != 'TD' &&
    cell.tagName != 'COL');
  return cell;
}

function getFirstCell(row)
{
  var cell = row.firstChild;
  if (cell != null && cell.tagName != 'TH' && cell.tagName != 'TD' &&
    cell.tagName != 'COL')
  {
    cell = getNextCell(cell);
  }
  return cell;
}

function getPreviousCell(cell)
{
  do
  {
    cell = cell.previousSibling;
  }
  while (cell != null && cell.tagName != 'TH' && cell.tagName != 'TD' &&
    cell.tagName != 'COL');
  return cell;
}

function getCell(row, index)
{
  var cell = getFirstCell(row);
  for (var i = 0; i < index; ++i)
  {
    cell = getNextCell(cell);
  }
  return cell;
}

function compareRows(a, b)
{
    var aCell = getCell(a, csColumnIndex);
    var aValue = getCellValue(aCell, csColumnType);
    var bCell = getCell(b, csColumnIndex);
    var bValue = getCellValue(bCell, csColumnType);

    // Reversed order of collected rows is reason why logic of comparision is
    // different to normal.
    if (bValue.localeCompare)
    {
        if (csIsDescending)
        {
            return aValue.localeCompare(bValue);
        }
        else
        {
            return bValue.localeCompare(aValue);
        }
    }
    if (csIsDescending)
    {
        if (aValue < bValue) return -1;
        if (aValue > bValue) return 1;
    }
    else
    {
        if (aValue > bValue) return -1;
        if (aValue < bValue) return 1;
    }
    return 0;
}

function applyCssClass(row, cssClassNames)
{
  var cell = getFirstCell(row);
  var index = 0;
  while (cell)
  {
    cell.className = cssClassNames[index++];
    cell = getNextCell(cell);
  }
}

function getCssClassNames(row)
{
  var cell = getFirstCell(row);
  var classNames = new Array();
  while (cell)
  {
    classNames[classNames.length] = cell.className;
    cell = getNextCell(cell);
  }
  return classNames;
}

function saveSetting(name, value, isForRoot)
{
    var date = new Date();
    date.setFullYear(date.getFullYear() + 1);
    var pathPart = (isForRoot ? ";path=/" : "");
    document.cookie = name + "=" +
        escape(value) + ";expires=" + date.toGMTString() + pathPart;
}

function saveSettingExpire(name, value, isForRoot, expireHours)
{
    var date = new Date();
    date.setTime(date.getTime() + (expireHours*60*60*1000));
    var pathPart = (isForRoot ? ";path=/" : "");
    document.cookie = name + "=" +
        escape(value) + ";expires=" + date.toGMTString() + pathPart;
}

// Sorting - dealing with cell internals

function isSortableCell(cell)
{
    return (cell.className == 'website-grid-head-cell');
}

function isSortedCell(cell)
{
    return (cell.lastChild && isSortableCell(cell) && cell.lastChild.innerHTML != '');
}

function isSortedDescending(cell)
{
    var value = cell.lastChild.innerHTML;
    return (value == String.fromCharCode(9650));
}

function setSortMark(cell, isDescending)
{
    var value = cell.lastChild.innerHTML;
    if (value == String.fromCharCode(9660))
    {
        isDescending = true;
        cell.lastChild.innerHTML = String.fromCharCode(9650);
        cell.lastChild.className = "website-sorting-mark-up";
    }
    else
    {
        cell.lastChild.innerHTML = String.fromCharCode(9660);
        cell.lastChild.className = "website-sorting-mark-down";
    }
}

function removeSortMark(cell)
{
    cell.lastChild.innerHTML = "";
    cell.lastChild.className = "website-sorting-mark-no";
}

// --

function applySortMark(row, index)
{
    var previousIndex = 0;
    var oldCell = getFirstCell(row);
    while (oldCell && !isSortedCell(oldCell))
    {
        oldCell = getNextCell(oldCell);
        ++previousIndex;
    }
    var isDescending = false;
    if (oldCell)
    {
        if (previousIndex == index)
        {
            var isDescending = !isSortedDescending(oldCell);
            setSortMark(oldCell, isDescending);
            return isDescending;
        }
        else
        {
            removeSortMark(oldCell);
        }
    }
    var cell = getCell(row, index);
    setSortMark(cell, isDescending);
    return isDescending;
}

function getTableBody(table)
{
    var body = table.firstChild;
    while (body && body.tagName != 'TBODY') {
        body = body.nextSibling;
    }
    return body;
}

function getCellIndex(cell)
{
    var index = 0;
    cell = getPreviousCell(cell);
    while (cell != null)
    {
        ++index;
        cell = getPreviousCell(cell);
    }
    return index;
}

function sortTable(table, colIndex, type)
{
    var body = getTableBody(table);
    var lastRow = body.lastChild;
    var rows = [];
    csIsDescending = applySortMark(body.firstChild, colIndex);
    while (lastRow.previousSibling)
    {
        lastRow = lastRow.previousSibling;
        if (lastRow.nextSibling.tagName != 'TR') // Text nodes in FF
        {
            body.removeChild(lastRow.nextSibling);
            continue;
        }
        rows[rows.length] = body.removeChild(lastRow.nextSibling);
    }
    var cssClassOdd = new Array();
    var cssClassEven = new Array();
    if (rows.length > 0)
    {
        cssClassOdd = getCssClassNames(rows[rows.length - 1]);
        if (rows.length > 1)
        {
            cssClassEven = getCssClassNames(rows[rows.length - 2]);
        }
    }
    csColumnIndex = colIndex;
    csColumnType = type;
    rows.sort(compareRows);
    var isOdd = true;
    for (var i = rows.length - 1; i >= 0; --i)
    {
        applyCssClass(rows[i], (isOdd ? cssClassOdd : cssClassEven));
        body.appendChild(rows[i]);
        isOdd = !isOdd;
    }
}

function getSortSettings(cookieName)
{
    var result = [];
    try
    {
        var sortUrl = unescape(getCookieValue(cookieName));
        var exp = new RegExp("([^&]*)", "g");
        var nameValuePairs = exp.exec(sortUrl);
        exp = new RegExp("([^=]*)=([^&]*)", "g");
        for (var i = 1; i < nameValuePairs.length; ++i)
        {
            var pair = exp.exec(nameValuePairs[i]);
            var object = new Object();
            object.name = pair[1];
            object.value = pair[2];
            result[result.length] = object;
        }
    }
    catch (e)
    {
        return [];
    }
    return result;
}

function saveSortSetting(cookieName, fieldName, isDescending)
{
    var cookieValue = fieldName + "=" + isDescending;
    var settings = getSortSettings(cookieName);
    for (var i = 0; i < settings.length; ++i)
    {
        var pair = settings[i];
        if (pair.name == fieldName) continue;
        cookieValue += "&" + pair.name + "=" + pair.value;
    }
    saveSetting(cookieName, cookieValue, true);
}

function sortGrid(link, fieldName, type, cookieName)
{
    var cell = link.parentNode;
    var index = getCellIndex(cell);
    var table = cell.parentNode.parentNode.parentNode;
    sortTable(table, index, type);
    var isDescending = (csIsDescending ? 1 : 0);
    saveSortSetting(cookieName, fieldName, isDescending);
}

// ---- End of Sorting

// Column resizing
var csResizedLeftColumn = null;
var csResizedLastColumn = null;
var csResizeControlColumn = null;
var csResizeControlCell = null;
var csRexizeCursorXOffset = 0;
var csRexizeCursorX = 0;
var csResizedTableWidth = "";
var csSwitchLastCount = 0;
var csSwitchLeftCount = 0;
var csResizeCookieName = "";

function getCursorXCoordinate(cursor)
{
    var x = 0;
    var y = 0;
    if (cursor.pageX || cursor.pageY)
    {
        x = cursor.pageX;
        y = cursor.pageY;
    }
    else if (cursor.clientX || cursor.clientY)
    {
        x = cursor.clientX + document.body.scrollLeft;
        y = cursor.clientY + document.body.scrollTop;
    }
    return x;
}

function getElementXCoordinate(element) {
  var x = 0;
  if (element.offsetParent) {
    while (element.offsetParent) {
      x += element.offsetLeft
      element = element.offsetParent;
    }
  } else if (element.x) {
      x += element.x;
  }
  return x;
}

function getDebugElement()
{
  element = document.body.firstChild;
  while (element && !element.tagName) element = element.nextSibling;
  return element;
}

function gridColumnResizeStart(cell, cursor, cookieName)
{
    var row = cell.parentNode;
    var table = row.parentNode.parentNode;
    var colgroup = table.firstChild;
    if (colgroup.tagName != 'COLGROUP') return;

    var index = getCellIndex(cell);
    csResizeControlColumn = getCell(colgroup, index);
    csResizedLeftColumn = csResizeControlColumn.previousSibling;
    csResizedLastColumn = colgroup.lastChild;
    csResizeControlCell = cell;
    csResizeCookieName = cookieName;
    if (document.setCapture) {
        document.setCapture(); // for IE
        document.onlosecapture = gridColumnResizeStop;
    } else {
        document.body.onselectstart = function () {return false;}; // for FireFox
    }
    document.onmousemove = gridColumnResize;
    document.onmouseup = gridColumnResizeStop;
    csRexizeCursorX = getCursorXCoordinate(cursor);
    csRexizeCursorXOffset = parseInt(csResizeControlCell.offsetWidth / 2);
    csResizedTableWidth = table.style.width;
    table.style.width = "";
//    getDebugElement().innerHTML = "";
}

function updateLastWidthOnLeftMove(widthLast, realDx)
{
    if (realDx == 0) return;
    if (csResizedLastColumn != csResizeControlColumn.parentNode.lastChild)
    {
        if (csResizedLastColumn.initialWidth && csResizedLastColumn.initialWidth < (widthLast - realDx)) {
            var initialWidth = csResizedLastColumn.initialWidth;
            csResizedLastColumn.width = initialWidth + "px";
            csResizedLastColumn.initialWidth = null;
            csResizedLastColumn = csResizedLastColumn.nextSibling.nextSibling;
            return updateLastWidthOnLeftMove(csResizedLastColumn.offsetWidth,
                widthLast - realDx - initialWidth);
        }
    }
    csResizedLastColumn.width = (widthLast - realDx) + "px";
}

function updateLeftWidthOnRightMove(widthLeft, realDx)
{
    if (realDx == 0) return;
    if (csResizedLeftColumn != csResizeControlColumn.previousSibling)
    {
        if (csResizedLeftColumn.initialWidth && csResizedLeftColumn.initialWidth < (widthLeft + realDx)) {
            var initialWidth = csResizedLeftColumn.initialWidth;
            csResizedLeftColumn.width = initialWidth + "px";
            csResizedLeftColumn.initialWidth = null;
            csResizedLeftColumn = csResizedLeftColumn.nextSibling.nextSibling;
            return updateLeftWidthOnRightMove(csResizedLeftColumn.offsetWidth,
                widthLeft + realDx - initialWidth);
        }
    }
    csResizedLeftColumn.width = (widthLeft + realDx) + "px";
}

function gridColumnResize(cursor)
{
    if (!csResizedLeftColumn || !csResizedLastColumn) return;
    if (!cursor) var cursor = window.event;
    var x = getCursorXCoordinate(cursor);
    var dx = x - getElementXCoordinate(csResizeControlCell) - csRexizeCursorXOffset;
    if (dx == 0) return;
    csRexizeCursorX = x;
    var widthLeft = csResizedLeftColumn.offsetWidth;
    var widthLast = csResizedLastColumn.offsetWidth;
    var canSwitch = true;
    if (dx < 0) {
        csSwitchLastCount = 0;
        if ((widthLeft + dx) < 20) dx = 20 - widthLeft;
        csResizedLeftColumn.width = (widthLeft + dx) + "px";
        realDx = csResizedLeftColumn.offsetWidth - widthLeft;
//        getDebugElement().innerHTML += dx + " " + realDx + "<br>";
        if (realDx > 0) {
            csResizedLeftColumn.width = (widthLeft + dx - realDx) + "px";
            realDx = csResizedLeftColumn.offsetWidth - widthLeft;
            canSwitch = false;
        }
        if (realDx == 0 && canSwitch && csResizedLeftColumn.previousSibling &&
          csResizedLeftColumn.previousSibling.previousSibling)
        {
            if (-dx > 10) {
                if (csSwitchLeftCount > 0) {
                    csSwitchLeftCount = 0;
//                    getDebugElement().innerHTML += " < sw " + dx + " " + realDx + "<br>";
                    csResizedLeftColumn = csResizedLeftColumn.previousSibling.previousSibling;
                    csResizedLeftColumn.initialWidth = csResizedLeftColumn.offsetWidth;
                    gridColumnResize(cursor);
                }
                ++csSwitchLeftCount;
            }
            return;
        }
        csSwitchLeftCount = 0;
        updateLastWidthOnLeftMove(widthLast, realDx);
    } else {
        csSwitchLeftCount = 0;
        if ((widthLast - dx) < 20) dx = widthLast - 20;
        csResizedLastColumn.width = (widthLast - dx) + "px";
        realDx = widthLast - csResizedLastColumn.offsetWidth;
//        getDebugElement().innerHTML += dx + " " + realDx + "<br>";
        if (realDx < 0) {
            csResizedLastColumn.width = (widthLast - dx + realDx) + "px";
            realDx = widthLast - csResizedLastColumn.offsetWidth;
            canSwitch = false;
        }
        if (realDx == 0 && canSwitch && csResizedLastColumn.previousSibling &&
          csResizedLastColumn.previousSibling != csResizeControlColumn &&
          csResizedLastColumn.previousSibling.previousSibling)
        {
            if (dx > 10) {
                if (csSwitchLastCount > 0) {
                    csSwitchLastCount = 0;
//                    getDebugElement().innerHTML += " > sw " + dx + " " + realDx + "<br>";
                    csResizedLastColumn = csResizedLastColumn.previousSibling.previousSibling;
                    csResizedLastColumn.initialWidth = csResizedLastColumn.offsetWidth;
                    gridColumnResize(cursor);
                }
                ++csSwitchLastCount;
            }
            return;
        }
        csSwitchLastCount = 0;
        updateLeftWidthOnRightMove(widthLeft, realDx);
    }
}

function cleanColumnsAndSave(colgroup)
{
    var column = colgroup.firstChild;
    var columnWidths = "";
    var isDelimiter = false;
    var isFirst = true;
    do {
        if (column.initialWidth) column.initialWidth = null;
        if (!isDelimiter) {
            if (isFirst) {
                isFirst = false;
            } else {
                columnWidths += "&";
            }
            columnWidths += "c[]=" + column.offsetWidth;
        }
        isDelimiter = !isDelimiter;
    } while(column = column.nextSibling);
    if (csResizeCookieName) {
        saveSetting(csResizeCookieName, columnWidths, false);
    }
}

function gridColumnResizeStop()
{
    csResizedLeftColumn.parentNode.parentNode.style.width = csResizedTableWidth;
    cleanColumnsAndSave(csResizedLeftColumn.parentNode);
    csResizedLeftColumn = null;
    csResizedLastColumn = null;
    document.onmousemove = function() {};
//    document.onmouseover = function() {};
    document.onmouseup = function() {};
    if (document.releaseCapture) {
        document.onlosecapture = function() {};
        document.releaseCapture();
    } else {
        document.body.onselectstart = function () {};
    }
    csResizeControlCell = null;
}

// ---- End of Column resizing

function scriptModeSubmit(formElement) // not used as is not working for IE
{
    var targetDocument = window.parent.document;
    var iframe = targetDocument.getElementById(formElement.id + "_action");
    if (!iframe) {
        var iframe = targetDocument.createElement("iframe");
        iframe.id = formElement.id + "_action";
        iframe.name = formElement.id + "_action";
        iframe.style.display = "none";
        iframe = formElement.parentNode.appendChild(iframe);
    }
    formElement.target = iframe.name;
    return true;
}

function setTitle(id, text)
{
    var targetDocument = window.parent.document;
    var titleElement = targetDocument.getElementById(id);
    if (titleElement) {
        titleElement.innerHTML = text;
    }
    targetDocument.title = text;
}

function submitFormInReloadMode(formElement)
{
    formElement.target = "";
    if (formElement._is_script_display_mode) {
        formElement._is_script_display_mode.parentNode.removeChild(formElement._is_script_display_mode);
    }
    formElement.submit();
}

// This functionality is due to element replaced in form by replaceChild
// is not correctly reflected in form.elements array in IE.
// One dimension arrays are used because between iframe loads second dimension
// array is cleared in IE.
var csFormElements = new Array();
var csFormElementParents = new Array();

function getFormElement(form, elementName)
{
    var targetWindow = window.parent;
    var targetDocument = targetWindow.document;

    var formElement = targetWindow.csFormElements[form.id + elementName];
    if (!formElement) {
        formElement = eval("form." + elementName + ";");
//        alert('create formElement for ' + form.id + " " + elementName + " " + formElement.tagName);
        targetWindow.csFormElements[form.id + elementName] = formElement;
        targetWindow.csFormElementParents[form.id + elementName] = formElement.parentNode;
    }
    return formElement;
}

function replaceFormElement(form, elementNew, elementOld)
{
    var targetWindow = window.parent;
//    alert(targetWindow.csFormElementParents[form.id + elementOld.name]);
    targetWindow.csFormElementParents[form.id + elementOld.name].replaceChild(elementNew, elementOld);
    targetWindow.csFormElements[form.id + elementOld.name] = elementNew;
}

function newHttpRequest()
{
  if (window.XMLHttpRequest)
  {
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    return new ActiveXObject('Microsoft.XMLHTTP');
  }
  return null;
}

function checkConnection(message)
{
  var request = newHttpRequest();
  if (!request) return;

  try
  {
    request.open("GET", window.location, false);
    request.send("");
  }
  catch (e)
  {
    alert(message);
  }
}

function parseXml(text)
{
  // code for IE
  if (window.ActiveXObject) {
    var doc = new ActiveXObject("Microsoft.XMLDOM");
    doc.async = "false";
    doc.loadXML(text);
  } else { // code for Mozilla, Firefox, Opera, etc.
    var parser = new DOMParser();
    var doc = parser.parseFromString(text,"text/xml");
  }

  // documentElement always represents the root node
  return doc.documentElement;
}

/**
 * _importNode code is from http://www.alistapart.com/articles/crossbrowserscripting
 * See http://www.alistapart.com/copyright/
 */
function prepareDocument(document)
{
  if (!document.ELEMENT_NODE) {
    document.ELEMENT_NODE = 1;
    document.ATTRIBUTE_NODE = 2;
    document.TEXT_NODE = 3;
    document.CDATA_SECTION_NODE = 4;
    document.ENTITY_REFERENCE_NODE = 5;
    document.ENTITY_NODE = 6;
    document.PROCESSING_INSTRUCTION_NODE = 7;
    document.COMMENT_NODE = 8;
    document.DOCUMENT_NODE = 9;
    document.DOCUMENT_TYPE_NODE = 10;
    document.DOCUMENT_FRAGMENT_NODE = 11;
    document.NOTATION_NODE = 12;
  }

  document._importNode = function(node, allChildren) {
    switch (node.nodeType) {
      case document.ELEMENT_NODE:
        var newNode = document.createElement(node.nodeName);
        /* does the node have any attributes to add? */
        if (node.attributes && node.attributes.length > 0)
          for (var i = 0, il = node.attributes.length; i < il;)
            newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
        /* are we going after children too, and does the node have any? */
        if (allChildren && node.childNodes && node.childNodes.length > 0)
          for (var i = 0, il = node.childNodes.length; i < il;)
            newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
        return newNode;
        break;
      case document.TEXT_NODE:
      case document.CDATA_SECTION_NODE:
      case document.COMMENT_NODE:
        return document.createTextNode(node.nodeValue);
        break;
    }
  };
}

function switchMenuFolding(element, foldingId)
{
  var nextElement = element.nextSibling;
  while (nextElement != null) {
    if (nextElement.tagName == 'UL' || nextElement.tagName == 'OL') {
      var isCollapsed = (nextElement.style.display == 'none');
      if (isCollapsed) {
        nextElement.style.display = 'block';
        element.className = 'website-folding-expanded';
        saveSetting(foldingId, 1, true);
      } else {
        nextElement.style.display = 'none';
        element.className = 'website-folding-collapsed';
        saveSetting(foldingId, 0, true);
      }
      break;
    }
    nextElement = nextElement.nextSibling;
  }
}

function setOuterHtml(element, htmlCode)
{
  if (typeof(element.outerHTML) == "string") {
    if (element.tagName == 'TR') {
      alert("Error: Cannot refresh table row element in IE!");
      return;
    }
    element.outerHTML = htmlCode;
  } else {
    if (element.id) {
        Cornerstone.ui.destroyChildHints(element.id);
    }
    var range = element.ownerDocument.createRange();
    range.setStartBefore(element);
    var fragment = range.createContextualFragment(htmlCode);
    element.parentNode.replaceChild(fragment, element);
  }
}

function systemRemoveAllChildren(node)
{
  var element = node.lastChild;
  while (element != null) {
    node.removeChild(element);
    element = node.lastChild;
  }
}

function systemGetSubmitForm()
{
  var form = document.getElementById('system_submit_form');
  if (form == null) {
    var div = document.createElement('div');
    div.style.display = 'none'; // hide to debug
    document.body.appendChild(div);

    iframeId = 'system_submit_iframe';
    div.innerHTML = '<iframe style="border:1px solid black" src="about:blank" id="' + iframeId + '" name="' + iframeId + '"></iframe>';

    form = document.createElement('form');
    form.id = 'system_submit_form';
    form.action = '';
    form.method = 'POST';
    form.setAttribute('target', iframeId);
    div.appendChild(form);
  } else {
    systemRemoveAllChildren(form);
  }
  return form;
}

function systemAppendHidden(form, name, value)
{
  var element = document.createElement('input');
  element.type = 'hidden';
  element.name = name;
  element.value = value;
  form.appendChild(element);
}

function systemAppendCloned(form, node)
{
  var element = node.cloneNode(true);
  element.value = node.value;
  form.appendChild(element);
}

function systemAppendClonedWithSwap(form, node)
{
  var element = node.cloneNode(false);
  element.value = "";
  node = node.parentNode.replaceChild(element, node);
  form.appendChild(node);
  return element;
}

var clonedValues = {};

var systemCloneIds_ = {};

var systemMultiCheckBoxesSet_ = {};
var systemMultiCheckBoxesUnset_ = {};

function systemCloneToForm(node, form)
{
  // Do not use filtering by default values. The reason:
  // Cannot rely on that if served from server, that state is known on server.

  // Prevent muliple inclusion of the same nodes
  // Do not use names here as names can be the same (for multi-choices)
  if (node.id != null && node.id != "") {
      if (systemCloneIds_[node.id] != null) return node;
      systemCloneIds_[node.id] = true;
  }

  if (node.disabled) return node;

  /* Sorting out the hidden textarea which ckeditor is using to post the text to server.
     Article use body at the end, textview and quarry use editor */
  /*
  if(node.tagName == 'TEXTAREA' && (node.name.substr(-4) == 'body' || node.name.substr(-6) == 'editor')){
        var editor = CKEDITOR.instances[node.name];
        if (editor != null) {
          node.value = editor.getData();
          //node.value = editor.GetXHTML();
        }
  }
  */

  // Clone all hidden, checkbox, multiselect, password and file values
  // Clone text, textarea, radio and select only if changed
  if (node.tagName == 'INPUT') {
    if (node.type == 'text') {
      systemAppendHidden(form, node.name, node.value);
    } else if (node.type == 'radio') {
      if (node.checked) {
        systemAppendHidden(form, node.name, node.value);
      }
    } else if (node.type == 'hidden') {
        /*
      try {
        var editor = FCKeditorAPI.GetInstance(node.name);
        if (editor != null) {
          node.value = editor.GetXHTML();
        }
      } catch (e) {
      }
      */
      systemAppendHidden(form, node.name, node.value);
    } else if (node.type == 'checkbox') {
      var pos = node.name.lastIndexOf('[');
      if (pos != -1 && node.name.substr(pos) == '[]') {
        if (node.checked) {
          systemAppendHidden(form, node.name, node.value);
          systemMultiCheckBoxesSet_[node.name.substr(0, node.name.length - 2)] = true;
        } else {
          systemMultiCheckBoxesUnset_[node.name.substr(0, node.name.length - 2)] = true;
        }
      } else {
        if (node.checked) {
          systemAppendHidden(form, node.name, '1');
        } else {
          systemAppendHidden(form, node.name, '0');
        }
      }
    } else if (node.type == 'password') {
      form.encoding = "multipart/form-data"; // To indicate that it should be posted
      return systemAppendClonedWithSwap(form, node);
    } else if (node.type == 'file') {
      form.encoding = "multipart/form-data";
      return systemAppendClonedWithSwap(form, node);
    }
  } else if (node.tagName == 'TEXTAREA') {
    var nodeValue = node.value;
    if (window.CKEDITOR != null) {
        var editor = CKEDITOR.instances[node.name];
        if (editor != null) {
          nodeValue = editor.getData();
        }
    }
    systemAppendHidden(form, node.name, nodeValue);
  } else if (node.tagName == 'SELECT') {
    if (node.type == 'select-multiple') {
      var isAtLeastOneSelected = false;
      for (var i = 0; i < node.options.length; ++i) {
        var option = node.options[i];
        if (option.selected) {
          isAtLeastOneSelected = true;
          systemAppendHidden(form, node.name, option.value);
        }
      }
      if (!isAtLeastOneSelected) {
          systemAppendHidden(form, node.name.substr(0, node.name.length - 2), '');
      }
    } else {
      if (node.options.length == 0) return node; // For select without options

      var option = node.options[node.selectedIndex];
      systemAppendHidden(form, node.name, option.value);
    }
  } else {
    var element = node.firstChild;
    while (element != null) {
      // element can be swapped to form, so we need to get
      // element that replaces current one
      element = systemCloneToForm(element, form);
      element = element.nextSibling;
    }
  }
  return node;
}

function systemCloneElementsToForm(elementIds, form)
{
  systemMultiCheckBoxesSet_ = {};
  systemCloneIds_ = {};
  for (var i = 0; i < elementIds.length; ++i) {
    var node = document.getElementById(elementIds[i]);
    if (node != null) {
      systemCloneToForm(node, form);
    }
  }
  for (var multiSelectName in systemMultiCheckBoxesUnset_) {
    if (systemMultiCheckBoxesSet_[multiSelectName] == null) {
        systemAppendHidden(form, multiSelectName, '');
    }
  }
  systemCloneIds_ = {};
  systemMultiCheckBoxesSet_ = {};
}

var systemSubmitElementsInProgress_ = 0;

function systemSubmitElements_(elementIds, eventType, eventId, additionalParameters)
{
  $('#' + eventId).each(function(){if (this.type == 'checkbox') this.focus();});
  systemSaveFocus();
  var form = systemGetSubmitForm();
  form.encoding = "application/x-www-form-urlencoded";
  systemAppendHidden(form, 'system_ui_event_type_', eventType);
  systemAppendHidden(form, 'system_ui_event_id_', eventId);

  // Check if it view edit form
/*  var parts = eventId.split('_', 5);
  if (parts.length > 3) {
    var viewId = parseInt(parts[1]);
    if (parts[0] == 'view' && viewId > 0 && parts[2] == 'edit' && parts[3] == 'form') {
      if (form.elements['is_website_action_mode_'] == null) {
        //TODO: Remove it, while it can be not necessary, but can be needed for UI 1.0
        systemAppendHidden(form, 'is_website_action_mode_', '1');
        systemAppendHidden(form, 'action_', 'edit_module_view');
        systemAppendHidden(form, 'view_id_', viewId);
      }
    }
  }*/
  systemCloneElementsToForm(elementIds, form);

  if (form.encoding != "application/x-www-form-urlencoded") {
      // Processing via IFRAME because of password or file fields

      /* Uploader init progress bar */
      var uploaders = {};
      var isUploader = false;
      var uploaderInputs = $('#' + form.id + ' input[type=file]').each(
      function() {
          if (this.value == '') return;

          var name = this.name;
          if (name.substr(name.length - 2) == '[]') {
              name = name.substr(0, name.length - 2);
          }
          uploaders[name] = true;
          isUploader = true;
      });
      if (isUploader) {
          var uploadId = Math.round(Math.random()*1000000000);
          var el = document.createElement('input');
          el.type = 'hidden';
          el.name = 'APC_UPLOAD_PROGRESS';
          el.value = uploadId;
          $(form).prepend(el);
          systemInitUpload(uploaders, uploadId);
      }

    if (additionalParameters != null) {
      for (var key in additionalParameters) {
        systemAppendHidden(form, key, additionalParameters[key]);
      }
    }
    form.submit();
    systemRemoveAllChildren(form);
  } else {
    var options = (additionalParameters != null ? additionalParameters : {});
/*    var options = {};
    if (additionalParameters != null) {
        for (var property in additionalParameters) {
            options[property] = additionalParameters[property];
        }
    }*/
    for (var i = 0; i < form.elements.length; ++i) {
      var element = form.elements[i];
      if (element.name in options) {
        if (!$.isArray(options[element.name])) options[element.name] = [options[element.name]];
        options[element.name].push(element.value);
      } else {
        options[element.name] = element.value;
      }
    }
    options["system_ui_json_"] = 1;
    systemRemoveAllChildren(form);
    $.ajax({
        type: "POST",
        data: options,
        dataType: 'text',
        success: function(responseText, type) {
          if (responseText == '') return;
          try {
            systemUpdateScreen(eval('(' + responseText + ')'));
          } catch (e) {
            alert(e.toString() + ": '" + responseText + "'");
          }
          Cornerstone.system.Event.switchInProcessOff();
        },
        error: function (request, status, error) {
          Cornerstone.system.Event.switchInProcessOff();
          if (status == 'timeout') {
              alert('Request is timed out. Check your internet connection.');
          } else if (error != null) {
              alert(error);
          }
        }
    });
  }
}

function systemUpdateScreen(response)
{
  var elements = response.elements;
  var errors = response.errors;
  for (id in elements) {
    var element = window.top.document.getElementById(id);
    if (element != null) {
      setOuterHtml(element, elements[id]);
    } else {
        element = document.getElementById(id);
        if (element != null) {
            setOuterHtml(element, elements[id]);
        }
    }
  }
  try {
    eval(response.script);
  } catch (e) {
    errors += "\n" + e.toString() + ":\n";
    errors += response.script;
  }
  if (errors != '') {
    alert(errors);
  }
  if (response.restoreFocus) systemRestoreFocus();
}

function systemGetObjectSource(object)
{
  var source = "{";
  var isFirst = true;
  for (keyName in object) {
    if (isFirst) {
      isFirst = false;
    } else {
      source += ", ";
    }
    var value = "" + object[keyName]; // convert to string
    source += keyName + ':"' + value.replace(/"/gi, "\\\"") + '"';
  }
  source += "}";
  return source;
}

function systemSubmitElements(sourceElement, eventType, elementIds, additionalParameters)
{
  var now = new Date();
  var time = now.getTime();
  if (Cornerstone.system.Event.isInProcess && (time - Cornerstone.system.Event.startTime) < 5000) {//  && eventType == 'click'
    return; // Ignore double clicks or other double events
  }
  Cornerstone.system.Event.switchInProcessOn();

  var additionalParametersSource = 'null';
  if (additionalParameters != null) {
    if (additionalParameters.toSource != null) {
        additionalParametersSource = additionalParameters.toSource();
    } else {
        additionalParametersSource = systemGetObjectSource(additionalParameters);
    }
  }

  var sourceElementId = sourceElement.id;
  if (sourceElement.name != null && sourceElement.name.length > 0) { // The length check needed for link elements.
    sourceElementId = sourceElement.name;
    if (sourceElementId.length > 2 &&
        sourceElementId.substr(sourceElementId.length - 2) == '[]')
    {
      sourceElementId = sourceElementId.substr(0, sourceElementId.length - 2);
    }
  }

  setTimeout("systemSubmitElements_(['" + elementIds.join("','") + "'], '" + eventType + "', '" +
    sourceElementId + "', " + additionalParametersSource + ")", 100);
}

function systemSubmitElement(sourceElement, submitElementId)
{
  systemSubmitElements(sourceElement, 'submit', [submitElementId], null);
}

var systemFocusedElement_ = null;

function systemGetFocusedElementId()
{
  if (systemFocusedElement_ != null) {
    return systemFocusedElement_.id;
  }
  return null;
}

function systemFocus(element)
{
  systemFocusedElement_ = element;
}

var systemSavedFocusedId_ = null;

function systemSaveFocus()
{
  window.top.systemSavedFocusedId_ = systemGetFocusedElementId();
}

function systemRestoreFocus_()
{
  var id = window.top.systemSavedFocusedId_;
  if (id != null) {
    var element = window.top.document.getElementById(id);
    if (element != null) {
      try {
        element.focus();
      } catch (e) {
      }
    }
  } else {
    var inputs = window.top.document.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; ++i) {
      var element = inputs[i];
      if (element.type == 'text' && element.id != null) {
          try {
            element.focus();
            window.top.systemSavedFocusedId_ = element.id;
            break;
          } catch (e) {
          }
      }
    }
  }
}

function systemRestoreFocus()
{
  // delay is needed for IE to set focus right
  setTimeout('systemRestoreFocus_()', 10);
}

function systemShowElement(id)
{
    var element = window.top.document.getElementById(id);
    element.style.display = 'block';
}

function systemHideElement(id)
{
    var element = window.top.document.getElementById(id);
    element.style.display = 'none';
}

function systemScreenLog(message)
{
  var log = window.top.document.getElementById('system_screen_log_');
  if (log == null) {
      log = window.top.document.createElement('div');
      log.id = 'system_screen_log_';
      log.style.position = 'absolute';
      log.style.top = '300px';
      log.style.right = '300px';
      log.style.zIndex = '1000';
      window.top.document.body.appendChild(log);
  }
  var entry = window.top.document.createElement('div');
  entry.innerHTML = log.childNodes.length + '. ' + message;
  log.appendChild(entry);
}

var elementsToShowWidth = 0;
var elementToShowTop = 0;
var elementToShowOffsetParent = null;

var overElements = {};
var menuShowProcessIndex = 0;
var menuShowProcessElements = {};
var menuShowProcessIndexedElements = [];

function websiteRegisterMenuShow(isShow, ids)
{
  for (var i = 0; i < ids.length; ++i)
  {
    var id = ids[i];
    var showFlagObject = menuShowProcessElements[id];
    if (showFlagObject == null) {
      var element = window.top.document.getElementById(id);
      //TODO: Why element can be null? Because of hidden menu items logic?
      if (element == null || (isShow && element.style.visibility == 'visible') ||
          (!isShow && element.style.visibility == 'hidden')) {
        continue;
      }
      showFlagObject = {};
      showFlagObject.isShow = isShow;
      showFlagObject.id = id;
      showFlagObject.element = element;
      showFlagObject.index = menuShowProcessIndex++;
      menuShowProcessElements[id] = showFlagObject;
      menuShowProcessIndexedElements[showFlagObject.index] = showFlagObject;
    } else {
      if ((isShow && showFlagObject.element.style.visibility == 'visible') ||
          (!isShow && showFlagObject.element.style.visibility == 'hidden')) {
        menuShowProcessIndexedElements[showFlagObject.index] = null;
        menuShowProcessElements[id] = null;
      }
    }
  }
}

function websiteMenuShowElement(element, top, offsetParent, width)
{
  if (element.getAttribute('is_panel_link') == '1') return;

  var panelMenuItemId = element.getAttribute('panel_menu_item_id');
  var isPanelMenu = (panelMenuItemId != null);
  if (isPanelMenu) {
    element.style.position = 'absolute';
    element.style.zIndex = 1001;
  }
  if (isPanelMenu) {
    var panelMenuItem = document.getElementById(panelMenuItemId);
    element.style.position = 'fixed';
    element.style.bottom = '0px';
    if (panelMenuItem != null) {
      var isSyncWidth = (element.getAttribute('panel_menu_item_sync_width') != null);
      var parent = panelMenuItem.parentNode;
      if (parent.style.position != 'fixed') parent = parent.parentNode;
      element.style.bottom = (parent.offsetHeight - panelMenuItem.offsetTop) + 'px';
      element.style.left = panelMenuItem.offsetLeft + 'px';
      if (isSyncWidth) {
          element.style.width = panelMenuItem.offsetWidth + 'px';
      }
    }
    element.style.visibility = 'visible';
    element.style.display = 'block';
  } else {
    element.style.visibility = 'visible';
    element.style.display = 'block';
    // element.className != '' - for panel module pages menu
    if (top != 0 && element.style.top == '' && element.className != 'website-drop-menu-table' && element.className != '') {
      while (element.offsetParent != offsetParent && offsetParent != null && offsetParent != offsetParent.offsetParent && offsetParent.tagName != 'HTML') {
        top += offsetParent.offsetTop;
//systemScreenLog('iteration parent : ' + offsetParent.tagName + ', id: ' + offsetParent.id + ', top: ' + offsetParent.offsetTop + ', result: ' + top);
        offsetParent = offsetParent.offsetParent;
      }
      element.style.top = top + 'px';
      if (element.offsetTop != top) {
        element.style.top = (top + (top - element.offsetTop)) + 'px';
//systemScreenLog('end fix : ' + (top - element.offsetTop) + ', end top: ' + element.offsetTop);
      }
    }
    if (element.style.width == '' && width > 0 && element.className != 'website-drop-menu-table') {
      element.style.width = width + 'px';
    }
    if (element.className == 'cs-toolbar-drop-menu') { // Drop to upper for module pages panel menu
      var offsetTop = element.parentNode.offsetHeight - element.offsetHeight;
      var offsetLeft = element.parentNode.offsetWidth;
      /*Element.clonePosition(element, element.parentNode,
          {setWidth: false, setHeight: false, offsetTop: offsetTop, offsetLeft: offsetLeft});*/
      var parentPosition = $(element.parentNode).position();
      $(element).css('left', parentPosition.left+offsetLeft).css('top', parentPosition.top+offsetTop);
      element.style.margin = '0px';
    }
  }
}

function websiteMenuHideElement(element)
{
  element.style.visibility = 'hidden';
  element.style.display = 'none';
}

var isWebsiteProcessMenuInProgress = false;
var websiteMenuTimeoutId = null;

function websiteProcessMenuShow()
{
  if (isWebsiteProcessMenuInProgress) return;
  isWebsiteProcessMenuInProgress = true;

  if (websiteMenuTimeoutId != null) {
      clearTimeout(websiteMenuTimeoutId);
      websiteMenuTimeoutId = null;
  }

  var objectsToShow = [];
  for (var i = menuShowProcessIndexedElements.length - 1; i >= 0; --i) {
    var showFlagObject = menuShowProcessIndexedElements[i];
    if (showFlagObject == null) continue;

    if (showFlagObject.isShow) {
      objectsToShow[objectsToShow.length] = showFlagObject;
      continue;
    }
    websiteMenuHideElement(showFlagObject.element);
    var overElement = overElements[showFlagObject.id];
    if (overElement != null && overElement.className.substr(overElement.className.length - 5) == '-over') {
      overElement.className = overElement.className.substr(0, overElement.className.length - 5);
//      overElements[idsToHide[i]] = null;
    }
  }
  for (var i = objectsToShow.length - 1; i >= 0; --i) {
    var showFlagObject = objectsToShow[i];
    var overElement = overElements[showFlagObject.id];
    if (overElement != null && overElement.className.substr(overElement.className.length - 5) != '-over') {
      overElement.className = overElement.className + '-over';
//      overElements[idsToHide[i]] = null;
    }
//    alert('BEFORE: ' + showFlagObject.element.id + ' ' + showFlagObject.element.innerHTML);
    websiteMenuShowElement(showFlagObject.element, elementToShowTop, elementToShowOffsetParent, elementsToShowWidth);
//    alert(showFlagObject.element.innerHTML);
  }
  menuShowProcessIndex = 0;
  menuShowProcessElements = {};
  menuShowProcessIndexedElements = [];
  isWebsiteProcessMenuInProgress = false;
}

function websiteHideElements(ids)
{
//  elementsToHide = elementsToHide.concat(ids);
  websiteRegisterMenuShow(false, ids);
  if (websiteMenuTimeoutId != null) {
      clearTimeout(websiteMenuTimeoutId);
  }
  websiteMenuTimeoutId = setTimeout('websiteProcessMenuShow()', 1000);
}

function websiteShowElements(ids, width)
{
//  elementsToShow = elementsToShow.concat(ids);
  websiteRegisterMenuShow(true, ids);
  elementsToShowWidth = width;
  websiteProcessMenuShow();
//  setTimeout('websiteProcessMenuShow()', 15);
}

function websiteOverMenu(element, childMenuId, pageIds, isAdjustWidth)
{
//systemScreenLog('over menu: ' + childMenuId + ' ; [' + pageIds.join(',') + ']');
  if (childMenuId == '' && element.className.substr(element.className.length - 5) != '-over') {
    element.className = element.className + '-over';
  } else {
    overElements[childMenuId] = element;
  }
  var table = null;
  if (isAdjustWidth) {
    var td = element.parentNode;
    var i = 7;
    while (td.tagName != 'TD' && i >= 0) {
        td = td.parentNode;
    }
    table = td.parentNode.parentNode.parentNode;
    elementToShowTop = table.offsetTop + table.offsetHeight;
    elementToShowOffsetParent = table.offsetParent;
//systemScreenLog('source parent : ' + table.offsetParent.tagName + ', id: ' + table.offsetParent.id + ', top: ' + table.offsetTop + ', height: ' + table.offsetHeight);
  }
  websiteShowElements(pageIds, (isAdjustWidth ? table.clientWidth : 0));
}

function websiteOutMenu(element, childMenuId, pageIds)
{
//systemScreenLog('out menu: ' + childMenuId + ' ; [' + pageIds.join(',') + ']');
  if (childMenuId == '' && element.className.substr(element.className.length - 5) == '-over') {
      element.className = element.className.substr(0, element.className.length - 5);
  } else {
    overElements[childMenuId] = element;
  }
  websiteHideElements(pageIds);
}

function websiteOverDropMenu(element, pageIds)
{
//systemScreenLog('over drop menu: ' + element.id + ' ; [' + pageIds.join(',') + ']');
  websiteShowElements(pageIds, 0);
}

function websiteOutDropMenu(element, pageIds)
{
//systemScreenLog('out drop menu: ' + element.id + ' ; [' + pageIds.join(',') + ']');
  websiteHideElements(pageIds);
}

function websiteOverPanelMenu(element, childMenuId, pageIds, isSyncWidth)
{
//  alert('page_ids:' + pageIds.concat(','));
  element.setAttribute('is_panel_link', '1');
  var childMenuElement = document.getElementById(childMenuId);
  if (childMenuElement == null) {
    websiteShowElements([], 0);
    return;
  }
  if (isSyncWidth) {
    childMenuElement.setAttribute('panel_menu_item_sync_width', '1');
  }
  childMenuElement.setAttribute('panel_menu_item_id', element.id);
  websiteOverMenu(element, childMenuId, pageIds, false);
/*
  if (childMenuId == '' && element.className.substr(element.className.length - 4) != 'Over') {
    element.className = element.className + 'Over';
  } else {
    overElements[childMenuId] = element;
  }
  var table = element.parentNode.parentNode.parentNode.parentNode;
  if (isAdjustWidth) {
    elementToShowTop = table.offsetTop + table.offsetHeight;
    elementToShowOffsetParent = table.offsetParent;
//systemScreenLog('source parent : ' + table.offsetParent.tagName + ', id: ' + table.offsetParent.id + ', top: ' + table.offsetTop + ', height: ' + table.offsetHeight);
  }
  websiteShowElements(pageIds, (isAdjustWidth ? table.clientWidth : 0));


    var menuElement = document.getElementById(childMenuId);
    if (menuElement == null) {
      websiteShowElements([], 0);
      return;
    }

    if (menuElement.style.display == 'block') return;

    menuElement.style.position = 'absolute';
    menuElement.style.zIndex = 1001;
//    alert(menuElement.style.bottom + ' ' + menuElement.parentNode.offsetHeight + 'px');

//    menuElement.style.display = 'block';
//    alert(menuElement.outerHTML);
    websiteShowElements([menuId], 0);

    menuElement.style.position = 'fixed';
    menuElement.style.bottom = '0px';
    menuElement.style.bottom = menuElement.parentNode.offsetHeight + 'px';
    menuElement.style.left = element.offsetLeft + 'px';
    */
}

function websiteOutPanelMenu(element, childMenuId, pageIds)
{
    websiteOutMenu(element, childMenuId, pageIds);
}

// Radio options changings for IE
var systemRadioElements_ = [];

function systemIsRadioChanged(element)
{
  if (systemRadioElements_[element.name] == null) {
      systemRadioElements_[element.name] = element.id;
      return !element.defaultChecked;
  }
  var result = (systemRadioElements_[element.name] != element.id);
  systemRadioElements_[element.name] = element.id;
  return result;
}

function formSetTextareaParameters(textareaId, minRows) {

	var textarea = $('#' + textareaId);
	var div = $('#' + textareaId + '_copy');
	var lineHeightCoeff = 1.3;
	var fontSize = parseInt(textarea.css('font-size'));
	var rowHeight = lineHeightCoeff*fontSize;
	/*alert(textarea.getStyle('font-size') + ',' + textarea.getWidth());*/
	div.width(textarea.width());
	textarea.height(parseInt(minRows*rowHeight));

}

function formExpandTextarea(box, minRows, maxRows, isInit) {

	if (typeof box != 'object') {
	    box = $('#' + box);
	} else {
	    box = $(box);
	}

	var lineHeightCoeff = 1.3;
	var fontSize = parseInt(box.css('font-size'));
	var rowHeight = Math.round(lineHeightCoeff*fontSize);
	var boxCopy = $('#' + box.attr('id') + '_copy');

	boxCopy.width(box.width()).empty().append(box.val().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
	    .replace(/\r\n|\r|\n/g, "<br />&nbsp;"));

	var currentRows = Math.round(boxCopy.height()/rowHeight);

	if (currentRows > minRows && currentRows < maxRows) {
		box.css('overflow', 'hidden');
		box.height(boxCopy.height()+rowHeight);
	} else if (currentRows <= minRows) {
		box.css('overflow', 'hidden');
		box.height(rowHeight*minRows);
	} else if (currentRows >= maxRows) {
		box.height(maxRows*rowHeight);
		box.css('overflow', '');
	}

	return;

}

function systemPanelClick(event, element)
{
  if (document.all) {
    event = window.event;
  }
  if (event == null || !event.ctrlKey) return;

  var value = getCookieValue('is_system_panel_locked_');
  value = (value != '1' ? '1' : '0');
  saveSetting('is_system_panel_locked_', value, true);
}

var systemPanelIsTransforming_ = false;

function systemPanelCreateUnderPaddingElement()
{
  //<div style="position:absolute;z-index:1;width:1px;height:30px;"></div>
  var el = document.createElement('div');
  el.style.position = 'absolute';
  el.style.zIndex = '1';
  el.style.width = '1px';
  el.style.height = '34px';//Bottom marging for scrolling in case of bottom toolbar
  return el;
}

function systemPanelGetUnderPaddingElement()
{
    var element = window.top.document.getElementById('system_panel_under_padding_');
    if (element == null) {
        element = systemPanelCreateUnderPaddingElement();
        element.id = 'system_panel_under_padding_';
        var body = window.top.document.getElementsByTagName('body')[0];
        body.appendChild(element);
        element.style.display = 'none';
    }
    return element;
}

function systemShowPanelUnderPaddingElement()
{
    var element = systemPanelGetUnderPaddingElement();
    element.style.display = 'block';
}

function systemHidePanelUnderPaddingElement()
{
    var element = systemPanelGetUnderPaddingElement();
    element.style.display = 'none';
}

function systemPanelMouseOver(event, element)
{
  if (systemPanelIsTransforming_) return;

  if (document.all) {
    event = window.event;
  }
  if (event == null || !event.ctrlKey) return;

  systemOpenPanel(element);
}

function systemOpenPanel(element)
{
  if (element.className == 'cs-toolbar') return;

  systemPanelIsTransforming_ = true;
  element.className = 'cs-toolbar';
  element.style.height = 'auto';
  var height = element.offsetHeight;
  element.style.bottom = '-' + element.offsetHeight + 'px';

  $('#view_777777777____panel').animate({bottom: '0px'}, 300, 'linear', function() {
      element.style.height = 'auto';
      saveSetting('is_system_panel_locked_', '1', true);
      systemShowPanelUnderPaddingElement();
      systemPanelIsTransforming_ = false;
      var openLinkElement = {id: 'view_777777777____open_link', name: 'view_777777777____open_link'};
      systemSubmitElements(openLinkElement, 'click', [''], null);
    });
}

function systemClosePanel(id)
{
  var panel = $('#' + id);
  if (panel.length == 0) return;

  var bottom = '-' + panel.get(0).offsetHeight + 'px';
  panel.animate({bottom: bottom}, 300, 'linear', function() {
      saveSetting('is_system_panel_locked_', '0', true);
      panel.addClass('cs-toolbar-off').height('2px').css('bottom', '0px');
      systemHidePanelUnderPaddingElement();
      systemPanelIsTransforming_ = false;
    });
}

function systemPanelMouseOut(element)
{
}

function systemUpdateUploadFrame(url, uploaders)
{
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'text',
        success: function(response, type) {
            var value = parseInt(response);
            if (value == 100) {
                for (var id in uploaders) {
                    var obj = uploaders[id];
                    obj.progressLine.style.width = (obj.progressWidth-1) + 'px';
                }
            } else {
                for (var id in uploaders) {
                    var obj = uploaders[id];
                    obj.progressLine.style.width =
                        Math.round(value * (obj.progressWidth/100)) + 'px';
                }
                setTimeout(function() {
                    systemUpdateUploadFrame(url, uploaders);}, 1000);
            }
        },
        error: function (request, status, error) {
        }
    });
}

function systemInitUpload(uploaders, uploadId) {
    var url = '/_service/system/upload_response/fhash/' + uploadId + '/';
    var isUploader = false;
    var progressObjects = {};
    for (var id in uploaders) {
        var progress = $('#' + id + '_progress');
        if (progress.size() == 0) {
            continue;
        }

        $('#' + id + '_upload_container').hide();
        progress.show();
        progressObjects[id] = {
            progressWidth: progress.width(),
            progressLine: $('#' + id + '_line').get(0)
        };
        isUploader = true;
    }

    if (isUploader) {
        setTimeout(function() {systemUpdateUploadFrame(url, progressObjects);},
            500);
    }
}

var websiteViewHoverOutStates_ = {};

function websiteProcessHoverOuts()
{
  for (var elementId in websiteViewHoverOutStates_) {
    var hoverState = websiteViewHoverOutStates_[elementId];
    if (hoverState == null) continue;

    var element = hoverState.element;
    var menuElement = hoverState.menuElement;
    var logoButton = hoverState.logoButton;
    var previousBorder = hoverState.previousBorder;

    element.setAttribute('is_mouse_over', '0');
//  alert(offset.left + ' x ' + eventX + ' x ' + (offset.left + dimentions.width) + '  ' +
//      offset.top + ' y ' + eventY + ' y ' + (offset.top + dimentions.height));
//    element.style.display = 'none';
//    element.innerHTML = element.innerHTML + ' elementOut<br />';
    element.style.border = previousBorder;
    var transparentPanel = menuElement.firstChild;
    var menu = transparentPanel.nextSibling;
    menu.style.display = 'none';
    transparentPanel.style.display = 'none';
    menuElement.style.display = 'none';
    logoButton.style.display = 'none';
  }
}

function isCtrlKey(event) {

	if (document.all) {
    	event = window.event;
  	}
  	if (event != null) {
  		return event.ctrlKey;
  	}
  	return false;

}

function isCodeKey(event, code)
{
    if (document.all) {
        event = window.event;
    }
    if (event != null) {
        return event.keyCode == code;
    }
    return false;
}

function isEnterKey(event)
{
    return isCodeKey(event, 13);
}

function isTabKey(event)
{
    return isCodeKey(event, 9);
}

function isEscapeKey(event)
{
    return isCodeKey(event, 27);
}

function getCookieNamespace() {

	return getCookieValue('authentication_namespace_');

}

function cookieNameWithNamespace(name) {

	var namespace = getCookieNamespace();
	if (!namespace) {
		return name;
	} else {
		return namespace + '.' + name;
	}

}

function systemCollapseBlock(link, block)
{
    if (block.style.display == 'none') {
        block.style.display = 'block';
        link.className = 'system-not-collapsed-link';
    } else {
        block.style.display = 'none';
        link.className = 'system-collapsed-link';
    }
}

function systemSwitchTab(tabControlId, tab, count, className) {

	var tabSet = $('#' + tabControlId);
	var tabIndex = $('#' + tabControlId + '_index');
	if (tabSet.length > 0) {
		tab = $(tab);
		var childElements = tabSet.children(':not(:first)');
		var openIndex = 0;
		for (i = 0; i < count; i++) {
			if ($(childElements.get(i)).hasClass(className)) {
				$(childElements.get(i)).removeClass(className);
			}
			if (childElements.get(i) == tab.get(0)) {
				openIndex = i;
				tabIndex.val(i);
			}
		}
		$(childElements.get(count)).nextAll(':visible').hide();
		var toShow = $(childElements.get(count+1+openIndex));
                toShow.show();
		$('.map', toShow).trigger('resize');
		tab.addClass(className);
	}
	return false;

}

function websiteViewGetHoverButton()
{
    var button = window.top.document.getElementById('cs_context_button_');
    if (button == null) {
        var button = document.createElement('div');
		button.id = 'cs_context_button_';
		button.className = 'cs-context-button';
        var body = window.top.document.getElementsByTagName('body')[0];
        body.insertBefore(button, body.firstChild);
    }
    return button;
}

function websiteViewHideHoverButton()
{
	var hoverButton = websiteViewGetHoverButton();
	hoverButton.onclick = function() {}
	hoverButton.onmouseover = function() {}
	$(hoverButton).hide();
    hoverButton.setAttribute('element_id', '');
}

function websiteViewGetHoverPanel()
{
    var panel = window.top.document.getElementById('cs_context_cover_');
    if (panel == null) {
        panel = document.createElement('div');
        panel.id = 'cs_context_cover_';
        panel.className = 'cs-context-cover';
        panel.style.position = 'absolute';
        panel.style.zIndex = '999'; // Below toolbox
        var innerDiv = document.createElement('div');
        panel.appendChild(innerDiv);
        var body = window.top.document.getElementsByTagName('body')[0];
        body.style.zIndex = '1';
        body.insertBefore(panel, body.firstChild);
    }
    return panel;
}

var websiteViewActiveHoverMenu = null;

function websiteViewShowHoverMenu(element, hoverMenu)
{
    if (websiteViewActiveHoverMenu != null) {
        if (hoverMenu == websiteViewActiveHoverMenu.hoverMenu) return;

        websiteViewHideHoverMenu();
    }
    var body = window.top.document.getElementsByTagName('body')[0];
    if (hoverMenu.parentNode != body) {
        hoverMenu.parentNode.removeChild(hoverMenu);
        body.appendChild(hoverMenu);
    }

    var offset = $(element).offset();
    var panel = websiteViewGetHoverPanel();
//	Element.clonePosition(panel, element);
    $(panel).show()
        .css('left', offset.left - 1)
        .css('top', offset.top - 1)
        .width($(element).outerWidth())
        .height($(element).outerHeight());
	hoverMenu.style.zIndex = '1999';
	var item = hoverMenu.firstChild.nextSibling;
	while (item != null) {
	    item.style.display = 'block';
	    item = item.nextSibling;
	}
	$(hoverMenu).show();
    $(hoverMenu).css('left', offset.left);
    $(hoverMenu).css('top', offset.top);
	var hoverButton = websiteViewGetHoverButton();
	hoverButton.onclick = function() {}
	websiteViewActiveHoverMenu = {element: element, hoverMenu: hoverMenu};
	$(hoverButton).hide();
}

function websiteViewHideHoverMenu()
{
	hidePopupContainer();
    if (websiteViewActiveHoverMenu == null) return;

    var element = websiteViewActiveHoverMenu.element;
    var hoverMenu = websiteViewActiveHoverMenu.hoverMenu;

    var panel = websiteViewGetHoverPanel();
    $(panel).hide();
	$(hoverMenu).hide();
	websiteViewHideHoverButton();
	websiteViewActiveHoverMenu = null;
	hoverMenu.parentNode.removeChild(hoverMenu);
	element.insertBefore(hoverMenu, element.firstChild);
}

var websiteViewOverActions = [];

function websiteViewProcessOverActions()
{
    var isShow = false;
    var event = null;
    var element = null;
    for (var i = 0; i < websiteViewOverActions.length; ++i) {
        isShow = websiteViewOverActions[i].isShow;
        event = websiteViewOverActions[i].event;
        element = websiteViewOverActions[i].element;
    }
    if (element != null) {
        if (isShow) {
            websiteViewShowHoverButton(event, element);
        } else {
            websiteViewHideHoverButton();
        }
    }
    websiteViewOverActions = [];
}

function websiteViewShowHoverButton(event, element)
{
    // Check for menu is shown for this view
    if (websiteViewActiveHoverMenu != null && websiteViewActiveHoverMenu.element == element) return;

    // Check for button already shown for this view
    var hoverButton = websiteViewGetHoverButton();
    if (hoverButton.getAttribute('element_id') == element.id) return;

    hoverButton.setAttribute('element_id', element.id);
    var hoverMenu = window.top.document.getElementById(element.id + '_context_menu');
    if (hoverMenu == null) {
        $(hoverButton).hide();
        return;
    }

    var offset = $(element).offset();
    $(hoverButton).css('left', offset.left);
    $(hoverButton).css('top', offset.top);
//	Element.clonePosition(hoverButton, element, {setWidth: false, setHeight: false, offsetTop: 0, offsetLeft: 0});
    $(hoverButton).click(function() {
        websiteViewShowHoverMenu(element, hoverMenu);
    });
    $(hoverButton).mouseover(function() {
        websiteViewOnMouseOver2(event, element);
    });
    $(hoverButton).mouseout(function() {
        websiteViewOnMouseOut2(event, element);
    });
    $(hoverButton).show();
}

function websiteSwitchViewHoverMenu(switcherLink, onText, offText)
{
    var isOff = websiteIsViewHoverMenuOff();
    if (isOff) {
        saveSetting("cs_context_menu_off_", "0", true);
    } else {
        saveSetting("cs_context_menu_off_", "1", true);
    }

    if (switcherLink == null) return;

    $('img', switcherLink).attr('src', (isOff ? "/_static/system/images/cube_on.png" : "/_static/system/images/cube_off.png"));

    $('span', $(switcherLink).next()).html(isOff ? onText : offText);
}

function websiteIsViewHoverMenuOff()
{
    var isOff = false;
    try {
      isOff = (getCookieValue("cs_context_menu_off_") == '1');
    } catch (e) {
    }
    return isOff;
}

function websiteViewOnMouseOver2(event, element)
{
    if (websiteIsViewHoverMenuOff()) return;

    websiteViewOverActions[websiteViewOverActions.length] = {isShow: true, event: event, element:element};
    setTimeout('websiteViewProcessOverActions()', 10);
}

function websiteViewOnMouseOut2(event, element)
{
    if (websiteIsViewHoverMenuOff()) return;

    websiteViewOverActions[websiteViewOverActions.length] = {isShow: false, event: event, element:element};
    setTimeout('websiteViewProcessOverActions()', 10);
}

function websiteViewOnMouseOut(event, element) {

	if (document.all) {
    	event = window.event;
  	}
  	Event.extend(event);
	var element = $(element);
	var coord = [event.pointerX(), event.pointerY()];
	var offset = element.cumulativeOffset();
	var dim = element.getDimensions();
	var border = 5;
	if ((offset[0]+border) < coord[0] && coord[0] < (offset[0]+dim.width-border)
	    && (offset[1]+border) < coord[1] && coord[1] < (offset[1]+dim.height-border)) return;
	if (element.getAttribute('is_opened') != '1') {
		$(element.id + '_button_').hide();
	}

}

function switchLoginForm() {

	var authForm = $('#_auth____login');
	var openidForm = $('#_auth_openid_form');
	if (authForm.visible()) {
		authForm.hide();
		openidForm.show();
	} else {
		authForm.show();
		openidForm.hide();
	}

}

function switchWebsiteMode()
{
 var value = getCookieValue("is_website_design_mode_");
 //var value = getCookieValue(cookieNameWithNamespace('is_website_design_mode_'));
 if (value == '1') {
  value = '0';
 } else {
  value = '1';
 }
 saveSetting("is_website_design_mode_", value, true);
 //saveSetting(cookieNameWithNamespace('is_website_design_mode_'), value, true);

 var loc = window.top.location + '';
 if( loc.indexOf('#') > -1 ){
 	var parts = loc.split('#');
 	window.top.location = parts[0];
 } else {
 	window.top.location = window.top.location;
 }

}

function systemShowNotifications(notifications)
{
  var container = window.top.document.getElementById('cs_notifications_');
  if (container == null) {
    container = window.top.document.createElement('div');
    container.id = 'cs_notifications_';
    container.className = 'cs-notification';
    container.style.display = 'none';
    container.style.position = 'fixed';
    container.style.bottom = '0px';
    container.style.right = '0px';
    container.style.zIndex = '9005';
    window.top.document.body.appendChild(container);
  }

  while (container.lastChild != null) {
    container.removeChild(container.lastChild);
  }

  for (var i = 0; i < notifications.length; ++i) {
    var notification = notifications[i];
    var titleElement = window.top.document.createElement('p');
    titleElement.className = 'ui-body';
    titleElement.innerHTML = notification.body;
    container.appendChild(titleElement);
    var bodyElement = window.top.document.createElement('p');
    bodyElement.className = 'ui-title';
    bodyElement.innerHTML = notification.title;
    container.appendChild(bodyElement);
  }

  if (notifications.length > 0) {
    setTimeout('window.top.$("#cs_notifications_").slideDown()', 300);
    setTimeout('window.top.$("#cs_notifications_").slideUp()', 5000);
  }
}

function systemSubmitElementsImage_(imageedit, action, eventType, eventId, additionalParameters)
{
    var options = (additionalParameters != null ? additionalParameters : {});
    options["system_ui_json_"] = 1;
    options["system_ui_event_type_"] = eventType;
    options["system_ui_event_id_"] = eventId;

    $.ajax({
        type: "POST",
        data: options,
        dataType: 'json',
        success: function(response, type) {
          if (action) {
              if (response.parameters) {
          	      imageedit.action = action;
                  imageedit.action(response.parameters.url + '&moduleId=68');
                  // console.log('Received Parameters: ' + response.parameters.url);
              } else {
                  // console.log('Received Error: ' + response);
              }
          }
        },
        error: function (request, status, error) {
          if (status == 'timeout') {
              alert('Request is timed out. Check your internet connection.');
          } else if (error != null) {
              alert(error);
          }
        }
    });
}

function playerReady(obj)
{
	/*var player = document.getElementById(obj['id']);
	console.log('Log: ' . player.getConfig().autoplay);
	player.sendEvent("PLAY","true");*/
}

function menuColumnDistributeSwitchProperties(namespace)
{
    overflowBlock = $('#' + namespace + '____overflow_block');
    var value = $('[name=' + namespace + '____distribution]:checked').val();
    if (1 == value) {
    	overflowBlock.show();
    } else {
    	overflowBlock.hide();
    }
}


/* Functionality to apply style link using ajax. Check all LINK elements in
 * HEAD: Do not append link if it exists. */
function applyStyleLink(styleHref)
{
	if (styleHref.length == 0) { return; }

	$('head').children('LINK').each(function() {
		if (this.rel == 'stylesheet') {
			var regex = new RegExp(styleHref + "$", "i");
			if (regex.test(this.href) ) {
				return; // style is there. do not add it once more!
			}
		}
	});

	// Append the link element
	var styleLink = $('<link/>')
    	.attr('href', styleHref)
    	.attr('rel','stylesheet')
    	.attr('type', 'text/css')
    	.appendTo('head');
	//$('head').append('<link href="'+ styleHref + '" rel="stylesheet" type="text/css" />');
}

