
/**
 * Plugin APP
 *
 * @copyright Copyright (c) 2010, ecto.lt
 * @author    Benas Valančius <benas@ecto.lt>
 * @package   Framework
 *
 * $Id: plugin_app.js 548 2010-05-14 16:21:32Z noen $
 */

var app = {
    categoriesListItem : '<div id="{$id}" class="c_row oh nowrap" style="cursor:default;">{$actions}{$name}</div>',
    itemsListItem      : '<div id="{$id}" class="c_row" style="cursor:default;">{$actions}<div class="oh nowrap">{$name}</div></div>'
};

/**
 * Init
 */
app.activateApp = function()
{
    if(typeof appType == 'undefined')
    {
        alert('undefined: appType');
        return false;
    }

    $(document).ready(function(){
        if(activeCategories)
        {
            $('#dialogCategory').dialog({
                width   : 400,
                loading : '/design/sys/loading.small.gif',
                buttons : [
                    {
                        title : _('Save'),
                        action : function()
                        {
                            $('#dialogCategory .icon_ok').parent().parent().attr('disabled',true);
                            $('#dialogCategory .ui-dialog-loading').show();

                            var status = formHandler.checkForm(formCheck_dialogCategory, '#errorOutputCategory');

                            if(status)
                            {
                                switch(appType)
                                {
                                    case 'app':
                                        //$('#dialogCategory form').submit();
                                        $('#dialogCategory .formSubmiter').click();
                                        break;

                                    case 'ajax':
                                        new Ajax.Post(
                                        {
                                            url     : modulePath + app.addSystemSettings('/appHandler/saveCategory/'),
                                            data    : $('#dialogCategory form').serializeArray(),
                                            json    : true,
                                            success : function(data)
                                            {
                                                $('#dialogCategory .icon_ok').parent().parent().removeAttr('disabled');
                                                $('#dialogCategory .ui-dialog-loading').hide();

                                                if(data.error == undefined)
                                                {
                                                    app.getCategories();
                                                    $('#categoryItem___'+ data).click();
                                                    $('#dialogCategory').dialog('close');
                                                }
                                                else
                                                {
                                                    ecto.alert(data.error);
                                                }
                                            }
                                        });
                                        break;
                                }
                            }
                            else
                            {
                                $('#dialogCategory .icon_ok').parent().parent().removeAttr('disabled');
                                $('#dialogCategory .ui-dialog-loading').hide();
                            }
                            return false;
                        },
                        template : {
                            className : 'icon_ok'
                        }
                    },
                    {
                        title : _('Cancel'),
                        action : function()
                        {
                            $('#dialogCategory').dialog('close');
                            return false;
                        },
                        template : {
                            className : 'icon_cancel'
                        }
                    }
                ]
            });
        }

        switch(appType)
        {
            case 'app':
                $('#dialogItem').dialog({
                    width   : 700,
                    loading : '/design/sys/loading.small.gif',
                    buttons : [
                        {
                            title : _('Save'),
                            action : function()
                            {
                                /*$('#dialogItem .icon_ok').parent().parent().attr('disabled',true);
                                $('#dialogItem .ui-dialog-loading').show();

                                var status = formHandler.checkForm(formCheck_dialogItem, '#errorOutputItem');

                                if(status)
                                {*/
                                    switch(appType)
                                    {
                                        case 'app':
                                            //$('#dialogItem form').submit();
                                            $('#dialogItem .formSubmiter').click();
                                            break;

                                        case 'ajax':
                                            // ajax`ui nereikia sito
                                            break;
                                    }
                                /*}
                                else
                                {
                                    $('#dialogItem .icon_ok').parent().parent().removeAttr('disabled');
                                    $('#dialogItem .ui-dialog-loading').hide();
                                }*/
                                return false;
                            },
                            template : {
                                className : 'icon_ok'
                            }
                        },
                        {
                            title : _('Cancel'),
                            action : function()
                            {
                                $('#dialogItem').dialog('close');
                                return false;
                            },
                            template : {
                                className : 'icon_cancel'
                            }
                        }
                    ]
                });

                if(activeCategories && categorySortable)
                {
                    app.sortableCategories();
                }

                if(itemSortable)
                {
                    app.sortableItems();
                }
                break;

            case 'ajax':
                $('#btn5').addClass('disabled');
                $('#btn6').addClass('disabled');

                app.disableForm();

                if(activeCategories)
                {
                    $('#btn2').addClass('disabled');
                    $('#btn3').addClass('disabled');
                    $('#btn4').addClass('disabled');
                    app.getCategories();
                }
                else
                    app.getItems();
                break;
        }
    });
};

/**
 * Activate sorting categories
 */
app.sortableCategories = function()
{
    $('#listCategories').sortable({
        axis: 'y',
        handle : '.icon_move',
        update: function(){
            var result = $('#listCategories').sortable('toArray');

            var ids = {};
            for(var x in result)
                ids[x] = result[x].substr(15);

            new Ajax.Post(
            {
                url     : modulePath + app.addSystemSettings('/appHandler/updateCategoryList/'),
                data    : ids,
                success : function(data) { }
            });
        }
    }).disableSelection();
};

/**
 * Get all app categories
 */
app.getCategories = function()
{
    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/getAllCategories/'),
        json    : true,
        success : function(data)
        {
            if(data)
            {
                $('#listCategories').html('');

                for(var x in data)
                {
                    var html = app.categoriesListItem;
                    var actions = '';

                    if(categorySortable)
                    {
                        actions = '<div class="fr"><span title="'+ _('Move') +'"><img class="icons icon_move" src="'+ IMG +'" alt="*" /></span></div>';
                    }

                    html = html.replace('{$id}',      'categoryItem___'+ data[x].id);
                    html = html.replace('{$name}',    data[x].name);
                    html = html.replace('{$actions}', actions);

                    $(html).click(function(){
                        $('#selectedCategory').val(this.id.substr(15));
                        $('#listCategories .c_row').removeClass('c_row_on');
                        $(this).addClass('c_row_on');
                        app.getItems(this.id.substr(15));

                        $('#btn2').removeClass('disabled');
                        $('#btn3').removeClass('disabled');
                        $('#btn4').removeClass('disabled');
                        $('#btn5').addClass('disabled');
                        $('#btn6').addClass('disabled');

                        app.disableForm();

                    }).appendTo($('#listCategories'));
                }

                if(categorySortable)
                {
                    app.sortableCategories();
                }
            }
        }
    });
};

/**
 * Edit app category
 */
app.editCategory = function(categoryId)
{
    if(typeof categoryId == 'undefined')
    {
        if($('#selectedCategory').val() == '')
            return false;
        else
            categoryId = $('#selectedCategory').val();
    }

    $('#dialogCategory').dialog('open');
    $('#dialogCategory .ui-dialog-loading').show();
    $('#dialogCategory *').attr('disabled',true);

    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/getCategory/'),
        data    : {id:categoryId},
        json    : true,
        success : function(data)
        {
            if(data)
            {
                for(var x in formFields_dialogCategory)
                {
                    $(formFields_dialogCategory[x].selector).val(data[formFields_dialogCategory[x].field]);
                }

                $('#dialogCategory *').removeAttr('disabled');
            }
            else
            {
                $('#dialogCategory').dialog('close');
                ecto.alert('error');
            }
            $('#dialogCategory .ui-dialog-loading').hide();
        }
    });
};

/**
 * Call delete app category promotion
 */
app.deleteCategory = function(categoryId)
{
    if(typeof categoryId == 'undefined')
    {
        if($('#selectedCategory').val() == '')
            return false;
        else
            categoryId = $('#selectedCategory').val();
    }

    ecto.confirm(_('Confirm deletig?'), 'app.deleteCategoryContinue('+ categoryId +')');
};

/**
 * Delete app category
 */
app.deleteCategoryContinue = function(categoryId)
{
    if(typeof categoryId == 'undefined')
    {
        if($('#selectedCategory').val() == '')
            return false;
        else
            categoryId = $('#selectedCategory').val();
    }

    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/deleteCategory/'),
        data    : {id:categoryId},
        json    : true,
        success : function(data)
        {
            if(data)
            {
                switch(appType)
                {
                    case 'app':
                        ecto.alert(_('Loading...'));
                        window.location.reload();
                        break;

                    case 'ajax':
                        app.getCategories();
                        $('#selectedCategory').val('');
                        $('#selectedItem').val('');
                        break;
                }
            }
        }
    });
};

/**
 * Get all app item by category
 */
app.getItems = function(categoryId, selectedId)
{
    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/getItems/'),
        data    : {categoryId:categoryId},
        json    : true,
        success : function(data)
        {
            if(data)
            {
                $('#listItems').html('');

                for(var x in data)
                {
                    var html = app.itemsListItem;
                    var actions = '';
                    actions += '<div class="fr" style="padding-left:3px;">';

                    if(itemSortable)
                    {
                        actions += '<span title="'+ _('Move') +'"><img class="icons icon_move" src="'+ IMG +'" alt="*" /></span>';
                    }

                    actions += '<span title="'+ _('Status') +'" class="hand"><img onclick="ecto.toggleItem(this,[\'icon_on\',\'icon_off\'],\''+ modulePath + app.addSystemSettings('/appHandler/changeItemStatus/?id='+ data[x].id) +'\');" class="icons icon_'+ (data[x].status == 0 ? 'off' : 'on') +'" src="'+ IMG +'" alt="*" /></span>';
                    actions += '</div>';

                    html = html.replace('{$id}',      'listItem___'+ data[x].id);
                    html = html.replace('{$name}',    data[x].name);
                    html = html.replace('{$actions}', actions);

                    $(html).click(function(){
                        $('#selectedItem').val(this.id.substr(11));
                        $('#listItems .c_row').removeClass('c_row_on');
                        $(this).addClass('c_row_on');

                        $('#btn5').removeClass('disabled');
                        $('#btn6').removeClass('disabled');

                        app.disableForm();

                    }).appendTo($('#listItems'));
                }

                if(itemSortable)
                {
                    app.sortableItems();
                }

                if(selectedId != undefined)
                {
                    $('#selectedItem').val(selectedId);
                    $('#listItems .c_row').removeClass('c_row_on');
                    $('#listItem___'+ selectedId).addClass('c_row_on');
                }
            }
            else
            {
                $('#listItems').html('<div class="loadingMsg">'+ _('Empty list.') +'</div>');
            }
        }
    });
};

/**
 * Activate sorting categories
 */
app.sortableItems = function()
{
    var fixHelper = function(e, ui){
        ui.children().each(function(){
            $(this).width($(this).width());
            $(this).height($(this).height());
        });
        return ui;
    };

    $('#listItems').sortable({
        axis: 'y',
        handle : '.icon_move',
        helper : fixHelper,
        update: function(){
            var result = $('#listItems').sortable('toArray');

            var ids = {};
            for(var x in result)
                ids[x] = result[x].substr(11);

            new Ajax.Post(
            {
                url     : modulePath + app.addSystemSettings('/appHandler/updateItemList/'),
                data    : ids,
                success : function(data) { }
            });
        }
    }).disableSelection();
};

/**
 * Create app item
 */
app.createItem = function(categoryId)
{
    if(activeCategories && typeof categoryId == 'undefined')
    {
        if($('#selectedCategory').val() == '')
            return false;
        else
            categoryId = $('#selectedCategory').val();
    }

    switch(appType)
    {
        case 'app':
            $('#dialogItem').dialog('open');
            break;

        case 'ajax':
            app.disableForm();

            $('#dialogItem .icon_ok').parent().parent().removeAttr('disabled');
            $('#dialogItem button').removeAttr('disabled');
            $('#dialogItem input').removeAttr('disabled');
            $('#dialogItem textarea').removeAttr('disabled');
            break;
    }

    if(activeCategories)
        $('#dialogItem input[name="categoryId"]').val(categoryId);

    $('#dialogItem input:first').focus();
};

/**
 * Edit app item
 */
app.editItem = function(itemId)
{
    if(typeof itemId == 'undefined')
    {
        if($('#selectedItem').val() == '')
            return false;
        else
            itemId = $('#selectedItem').val();
    }

    switch(appType)
    {
        case 'app':
            $('#dialogItem').dialog('open');
            $('#dialogItem .icon_ok').parent().parent().attr('disabled',true);
            $('#dialogItem .ui-dialog-loading').show();
            break;

        case 'ajax':
            $('#dialogItem .spiner').show();
            break;
    }

    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/getItem/'),
        data    : {id:itemId},
        json    : true,
        success : function(data)
        {
            if(data)
            {
                for(var x in formFields_dialogItem)
                {
                    var obj = $(formFields_dialogItem[x].selector);

                    if(obj.get(0).tagName.toLowerCase() == 'input' && obj.attr('type').toLowerCase() == 'checkbox')
                    {
                        if(data[formFields_dialogItem[x].field] == 1)
                            obj.attr('checked',true);
                    }
                    else
                        obj.val(data[formFields_dialogItem[x].field]);
                }

                switch(appType)
                {
                    case 'app':
                        break;

                    case 'ajax':
                        $('#dialogItem button').removeAttr('disabled');
                        $('#dialogItem input').removeAttr('disabled');
                        $('#dialogItem textarea').removeAttr('disabled');
                        break;
                }

                $('#dialogItem .icon_ok').parent().parent().removeAttr('disabled');
                $('#dialogItem input:first').focus();
            }
            else
            {
                ecto.alert('error');
            }

            switch(appType)
            {
                case 'app':
                    $('#dialogItem .ui-dialog-loading').hide();
                    break;

                case 'ajax':
                    $('#dialogItem .spiner').hide();
                    break;
            }
        }
    });
};

/**
 * Save app item
 */
app.saveItem = function(errorOutput)
{
    $('#dialogItem .icon_ok').parent().parent().attr('disabled',true);
    $('#dialogItem .spiner').show();

    var status = formHandler.checkForm(formCheck_dialogItem, errorOutput);

    if(status)
    {
        new Ajax.Post(
        {
            url     : modulePath + app.addSystemSettings('/appHandler/saveItem/'),
            data    : $('#dialogItem form').serializeArray(),
            json    : true,
            success : function(data)
            {
                $('#dialogItem .icon_ok').parent().parent().removeAttr('disabled');
                $('#dialogItem .spiner').hide();

                if(data.error == undefined)
                {
                    app.getItems($('#selectedCategory').val(), data);
                    app.disableForm();
                }
                else
                {
                    ecto.alert(data.error);
                }
            }
        });
    }
    else
    {
        $('#dialogItem .icon_ok').parent().parent().removeAttr('disabled');
        $('#dialogItem .spiner').hide();
    }
    return false;
};

/**
 * Call delete app item promotion
 */
app.deleteItem = function(itemId)
{
    if(typeof itemId == 'undefined')
    {
        if($('#selectedItem').val() == '')
            return false;
        else
            itemId = $('#selectedItem').val();
    }

    ecto.confirm(_('Confirm deletig?'), 'app.deleteItemContinue('+ itemId +')');
};

/**
 * Delete app item
 */
app.deleteItemContinue = function(itemId)
{
    if(typeof itemId == 'undefined')
    {
        if($('#selectedItem').val() == '')
            return false;
        else
            itemId = $('#selectedItem').val();
    }

    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/deleteItem/'),
        data    : {id:itemId},
        json    : true,
        success : function(data)
        {
            if(data)
            {
                switch(appType)
                {
                    case 'app':
                        ecto.alert(_('Loading...'));
                        window.location.reload();
                        break;

                    case 'ajax':
                        app.getItems($('#selectedCategory').val());
                        $('#selectedItem').val('');

                        $('#btn5').addClass('disabled');
                        $('#btn6').addClass('disabled');

                        app.disableForm();
                        break;
                }
            }
        }
    });
};

/**
 * Disable all form items
 */
app.disableForm = function()
{
    $('#dialogItem .icon_ok').parent().parent().attr('disabled',true);
    $('#dialogItem button').attr('disabled',true);
    $('#dialogItem input').attr('disabled',true).val('');
    $('#dialogItem input[type="checkbox"]').removeAttr('checked').val(1);
    $('#dialogItem textarea').attr('disabled',true).val('');
};

/**
 * Generate path like string from any text
 */
app.generatePath = function(selector, base, form)
{
    var id = $(form +' input[name="id"]').val();
    var name = $(form +' input[name="'+ base +'"]').val();

    if(name == '')
        return;

    $(form +' button').attr('disabled',true);

    new Ajax.Post(
    {
        url     : modulePath + app.addSystemSettings('/appHandler/createItemPath/'),
        data    : {id:id,name:name},
        json    : true,
        success : function(data)
        {
            if(data)
                $(form +' input[name="'+ selector +'"]').val(data);

            $(form +' button').removeAttr('disabled');
        }
    });
};

/**
 * Toggle item status
 */
app.toggleItem = function(appName, e, icons, itemId, field, url)
{
    if(typeof(url) == 'undefined')
        url = modulePath +'/appHandler/toggleItem/?appType=app&appName='+ appName +'&field='+ field +'&id='+ itemId;
    else
        url = url + itemId;

    ecto.toggleItem(e, icons, url);
};

/**
 * Add system vars to url
 */
app.addSystemSettings = function(url)
{
    return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'appName='+ appName +'&appType='+ appType;
};

/**
 * Auto form check
 *
 * @param string formName - Form name
 *
 * @return bool
 */
app.autoCheckForm = function(formName)
{
    eval('var formCheck = formCheck_'+ formName +';');

    $('#'+ formName +' .spiner').show();
    $('#'+ formName +' .ui-dialog-loading').show();
    $('#'+ formName +' .icon_ok').parent().parent().attr('disabled',true);
    
    var status = formHandler.checkForm(formCheck, '#errorOutput_'+ formName);
    
    if(!status)
    {
        $('#'+ formName +' .spiner').hide();
        $('#'+ formName +' .ui-dialog-loading').hide();
        $('#'+ formName +' .icon_ok').parent().parent().removeAttr('disabled');
        return false;
    }
    
    return true;
};
