Core.searchSubmit = function(id) {
    id = typeof id == 'undefined' ? 'searchField' : id;
    var sf = $(id);
    if (sf.value) {
//        alert('/index/search/by/' + encodeURIComponent(sf.value));
        window.location = '/index/search/by/' + encodeURIComponent(sf.value);
    }

    return false;
};

Core.searchKeyDown = function(obj, event) {
//    alert(event.keyCode);
    if (event.keyCode == 13) {
        Core.searchSubmit('search');
        return false;
    }
    return true;
}

Core.loginKeyDown = function(obj, event) {
//    alert(event.keyCode);
    if (event.keyCode == 13) {
        Core.loginSubmit();
        return false;
    }
    return true;

}

Core.loginSubmit = function() {
    var l = document.getElementById('loginEmail');
    var p = document.getElementById('loginPassword');
    var err = false;

    if (l.value == '' || false == Ext.form.VTypes.email(l.value)) {
        l.className = 'error';
        err = true;
    }
    if (p.value == '') {
        p.className = 'error';
        err = true;
    }

    if (!err) {
        document.forms.loginform.submit();
    }
}

/**
* Message box singleton.
*/
Core.messageBox = {};
Core.messageBox.windows = {};
Core.messageBox.toIdValue = null;
Core.messageBox.replyToId = null;

/**
* @param string|integer windowId Window identifier. Repeatable calls will be refered to previously created window.
* @param string backendController Controller name, this form should be submitted to.
* @param string backendAction Controller action name.
* @param string|integer toIdValue This value will be passed to server to identify message recipient.
* @param boolean showPrivateChk Defines whether "Private" checkbox should be displayed.
* @param boolean redirectToLastPage Defines whether the browser should be redirected to last page or the first one.
* @param string windowTitle Title of window.
*
* Creates window, if it has not been yet created. Shows window.
*/
Core.messageBox.windowOpen = function(windowId, backendController, backendAction, toIdValue, showPrivateChk, redirectToLastPage, windowTitle, doNotRedirect, onSuccessHandler, replyToId) {
    Core.messageBox.toIdValue = toIdValue;
    Core.messageBox.replyToId = typeof replyToId == 'number' ? replyToId : null;
    if (Core.messageBox.windows[windowId] == null) {
        showPrivateChk = showPrivateChk ? showPrivateChk : false;
        var items = [{
            'xtype' : 'textfield',
            'emptyText' : Core.translate.get('messageSubjectEmpty', 'all'),
            'id' : 'messageSubject',
            'name' : 'messageSubject',
            'hideLabel' : true,
            'value' : '',
            'allowBlank' : true,
            anchor: '100%'
        }, {
            'xtype' : 'textarea',
            'emptyText' : Core.translate.get('messageTextEmpty', 'all'),
            'id' : 'messageText',
            'name' : 'messageText',
            'hideLabel' : true,
            'value' : '',
            anchor: '100%',
            height : 260
        }];

//        if (showPrivateChk) {
            items.push({
                'xtype' : 'checkbox',
                'hideLabel' : true,
                'boxLabel' : Core.translate.get('messagePrivateLabel', 'all'),
                'id' : 'chkmessagePrivate',
                'name' : 'messagePrivate',
                'value' : 'y',
                'checked' : false,
                'hidden' : !(showPrivateChk || Core.messageBox.replyToId)
            });
//        }

        var formId = windowId + '-form';
        var form/*Core.messageBox.windows[windowId]*/ = new Ext.form.FormPanel({
            id : formId,
            baseCls : 'x-fieldset',
            defaults : {
                'allowBlank' : false,
                'preventMark' : true
            },
            border : false,
            items : items
        });

        windowTitle = windowTitle ? windowTitle : Core.translate.get('jsMessagePopupTitle', 'all');

        Core.messageBox.windows[windowId] = new Ext.Window({
            'modal' : true,
            'id' : windowId,
//            'animateTarget' : 'writeMessage',
            'resizable' : false,
            'title' : windowTitle,
            'border' : true,
            'width' : 600,
            'height' : 400,
            'closeAction' : 'hide',
            'items' : form,
            'buttons' : [{
                'text' : Core.translate.get('messageSubmit', 'all'),
                'handler' : function(button) {
                    var el = Ext.getDom('messageSubject'),
                        subjLabel = Core.translate.get('messageSubjectEmpty', 'all');
                    if (el.value == subjLabel) {
                        el.value = '';
                    }

                    if (Core.messageBox.replyToId) {
                        Core.formRequest(Ext.getCmp(formId), '/event/', 'Profile_Edit', 'postReply', {
                            success : function(form, action) {
                                Core.msg(Core.translate.get('reqSuccess'), action.result.msg);
                                if (typeof onSuccessHandler == 'function') {
                                    onSuccessHandler(action.result);
                                }
                                Core.messageBox.windows[windowId].hide();
                                var cmp = Ext.getCmp('messageSubject');
                                if (cmp) {
                                    cmp.setValue('');
                                }
                                cmp = Ext.getCmp('messageText');
                                if (cmp) {
                                    cmp.setValue('');
                                }
                                cmp = Ext.getCmp('chkmessagePrivate');
                                if (cmp) {
                                    cmp.setValue(false);
                                }
                            },
                            params : {
                                replyToId : Core.messageBox.replyToId
                            }
                        });
                    } else {
                        Core.formRequest(Ext.getCmp(formId), '/event/', backendController, backendAction, {
                            success : function(form, action) {
                                Core.msg(Core.translate.get('reqSuccess'), action.result.msg);
                                if (typeof onSuccessHandler == 'function') {
                                    onSuccessHandler(action.result);
                                }

                                if (doNotRedirect) {

                                } else {
                                    if (redirectToLastPage) {
                                        var url = Core.removeUrlParameter('offset').replace('http://', '');
                                        url = url.split('/');
                                        var domain = url[0];
                                        url.shift();
                                        url = '/' + url.join('/');
                                        if (url.indexOf('/') == url.lastIndexOf('/') && url.indexOf('/') != -1) {
                                            url += '/index';
                                        }
                                        Core.maskRedirect('http://' + domain + url + '/offset/last');
                                    } else {
                                        Core.maskRedirect(Core.removeUrlParameter('offset'));
                                    }
                                }

                                Core.messageBox.windows[windowId].hide();
                            },
                            params : {
                                toId : Core.messageBox.toIdValue
                            }
                        });
                    }
                }
            }]
        })
    } else {
        Ext.getCmp('chkmessagePrivate').setValue(false);
        if (showPrivateChk || Core.messageBox.replyToId) {
            Ext.getCmp('chkmessagePrivate').setVisible(true);
        } else {
            Ext.getCmp('chkmessagePrivate').setVisible(false);
        }
    }

    Core.messageBox.windows[windowId].show();
}

Core.forgotPopupOpen = function() {
    Core.mask.show();
    Core.evalRequest('/event/', 'Index_Forgot', 'showPopup');
}

Ext.onReady(function() {
    var loginPopupTrigger = $('showLoginPopup');
    if (loginPopupTrigger) {
        addEvent(loginPopupTrigger, 'click', function(){
            if (Core.login == null) {
                Core.login = {};
            }

            if (Core.login.form == null) {
                Core.login.form = new Ext.form.FormPanel({
                    'defaultType' : 'textfield',
                    'baseCls' : 'x-fieldset-nopadding',
                    'border' : false,
                    'keys' : {
                        key : [10, 13],
                        fn : function(){
                            Core.loginSubmit(Core.login.window, Core.login.form);
                        }
                    },
                    'defaults' : {
                        'allowBlank' : false,
                        'anchor' : '100%',
                        'hideLabel' : true,
                        'preventMark' : true
                    },
                    'items' : [{
                        'emptyText' : 'E-mail',
                        'id' : 'formEmail',
                        'name' : 'email',
                        'vtype' : 'email',
                        'listeners' : {
                            'afterrender' : function() {
                                this.el.on('keydown', function(e, t) {
                                    var code = e.getCharCode();
                                    if (10 == code || 13 == code) {
                                        e.stopEvent();
                                        Ext.getCmp('formPassword').focus();
                                    }
                                });
                            }
                        },
                        'autoCreate' : {
                            'tag' : 'input',
                            'type' : 'text',
                            'autocomplete' : 'on'
                        },
                        'style' : 'margin-bottom: 4px;'
                    }, {
                        'emptyText' : Core.translate.get('jsPasswordLabel', 'all'),
                        'autoCreate' : {
                            'tag' : 'input',
                            'type' : 'password',
                            'autocomplete' : 'off'
                        },
                        'id' : 'formPassword',
                        'name' : 'password'
                    }, {
                        'xtype' : 'checkbox',
                        'id' : 'formRemember',
                        'name' : 'remember',
                        'boxLabel' : Core.translate.get('jsRememberMeLabel', 'all'),
                        'value' : 1
                    }, {
                        'xtype' : 'justtext',
                        'id' : 'formForgot',
                        'name' : 'forgot',
                        'value' : '<a href="javascript: void(0);" onclick="Core.forgotPopupOpen();">' + Core.translate.get('forgot password', 'all') + '?</a>'
                    }],
                    'layout' : 'anchor'
                });
            }

            if (Core.login.window == null) {
                Core.login.window = new Ext.Window({
                    'renderTo' : 'popupWindow',
                    'animateTarget' : 'showLoginPopup',
                    'resizable' : false,
                    'title' : Core.translate.get('jsProfiePopupTitle', 'all'),
                    'border' : false,
                    'width' : 300,
                    'height' : 121,
                    'closeAction' : 'hide',
                    'items' : Core.login.form,
                    'buttons' : [{
                        'text' : Core.translate.get('sign in', 'all'),
                        'handler' : function(){
                            Core.loginSubmit(Core.login.window, Core.login.form);
                        }
                    }]
                });
            }
            Core.login.window.show();
        });
    }
});

Core.savePageHeight = function()
{
    var bl = $('page-content');
    if (bl) {
        var url = window.location.pathname + window.location.search;
        Core.request('/event/', 'Index_HeightHandler', 'savePageHeight', {h: bl.offsetHeight, u: url}, function(o, s, r) {

        });
    }
}

Core.fixRange = function()
{
    if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
        Range.prototype.createContextualFragment = function(html)
        {
            var frag = document.createDocumentFragment(),
            div = document.createElement("div");
            frag.appendChild(div);
            div.outerHTML = html;
            return frag;
        };
    }
}

function preloadMenuImages()
{
    var a = new Image(); a.src = '/public/images/header/menu/active/1.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/2.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/3.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/4.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/5.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/6.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/7.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/8.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/active/9.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/1.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/2.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/3.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/4.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/5.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/6.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/7.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/8.jpg';
    var a = new Image(); a.src = '/public/images/header/menu/9.jpg';
}
