/** js admin script
 * @author sergasd sergasd@gmail.com
 * @version 1.0
 */


(function($) {

    /*JQUERY WRAPPER BEGIN*/
    $(document).ready(function() {

        $(".toggleNext").click(function(e){
            $(this).next().toggle();
            e.preventDefault();
        });

        //relaxtypes
/*        $(".on_mouse_out_close").mouse(function(e){
            $(this).hide();
        });*/

        $("body").click(function(e){
            if(e.target.className != 'toggleNext')
                $(".on_mouse_out_close").hide();
            e.stopPropagation();
        });


    });
    /*JQUERY WRAPPER END*/



})(jQuery);


/**
 * Главный хелпер системы
 * @author sergasd sergasd@gmail.com
 * @version 1.0
 */

/* MAIN CMS HELPER BEGIN */

var Sg = (function(){


    //local copy
    var Sg = function() {
        return this;
    };


    /**
     * @function print Выводит в консоль свойства объекта
     * @param obj object  Объект, свойства которого хотим вывести
     * @param type string Тип (свойства либо функции) ('property' | 'function' | 'all')
     * */
    Sg.print = function(obj, type) {

        //нах ie
        if(typeof(window.console) == undefined)
            return;

        if (obj == null) obj = this;
        type = type || 'property';

        for (var i in obj) {
            var t = typeof(obj[i]);


            switch (t) {
                case 'function':

                    if(type == 'function' || type == 'all')
                    {
                        console.log('----------------FUNCTION----------------');
                        console.log(obj[i]);
                    }
                    break;

                case 'boolean':
                case 'number':
                case 'string':
                case 'object':

                    if(type == 'property' || type == 'all')
                    {
                        console.log('[' + i + ']' + '[' + typeof(obj[i]) + ']');
                        console.log(obj[i]);
                    }
                    break;

            }

        }

    };

    /**
     * @function extend Расширяет свойства и методы объекта Sg
     * @param options object Объект которым расширится Цель
     * @param obj object Объект цель (который расширяем)
     * @param replace boolean Если true - заменяет исходные свойства объекта
     * */
    Sg.extend = function(options, obj, replace){
        obj = obj || this;
        replace = replace || false;

        for(var item in options)
        {
            if( typeof(obj[item]) == 'undefined' ){
                obj[item] = options[item];
            }
            else if(replace) {
                obj[item] = options[item];
            }

        }

        return obj;
    };






    /**
     * Общие функции (инициализация)
     * */

    Sg.extend({
        /**
         * @function init Производит инициализацию хелпера
         * */
        init : function(){
            this._version = 1.001;
            this._debug = false;
        },
        /**
         * @function getVersion Возвращает версию хелпера
         * */
        getVersion : function(){
            return this._version;
        },
        getAjaxLoader : function(){
            return '<img src="'+ '/images/admin/ajax-loader.gif' + '" alt="loading..." class="ajax-loader" />';
        },
        /**
         * @function debug Устанавливает или отменяет режим отладки
         * Например Sg.debug() - включает отладочные сообщения
         * Sg.debug(false) - выключает отладочные сообщения
         * */
        debug : function(state){
            this._debug = (state != false);
        }
    });



    /**
     * Работа с формами
     * */


    //Рендерер сообщений от кмс (потом можно заменить, пока используется только в качестве интерфейса)
    Sg.extend({
        /**
         * @function showMessage Функция показа сообщения пользователю
         * @param type Тип сообщения ('ok' | 'error' | 'warning')
         * @param message Тело сообщения
         * @param options Опции
         * */
        showMessage : function(type, message, options){

            //default params
            var _options = {
                'text': message,
                'place_v':'top',
                'place_h':'right',
                'icon': '',
                'skin':'silver',
                'delay':'8000',
                'ex':'true',
                'effect':'fade'
            };

            //message type
            switch(type){
                case 'ok':
                    _options.icon = '/images/admin/icons/success.gif';
                    break;

                case 'error':
                    _options.icon = '/images/admin/icons/error.png';
                break;

                case 'warning':
                    _options.icon = '/images/admin/icons/warning.png';
                break;
            }

            //Складываем параметры по умолчанию с переданными
            this.extend(options, _options, true);

            //Выводим используюя плагин
            $().el7r_notify(_options);

            //scroll fix
           $("#el7r_notify_top_right").css({'top': $(document).scrollTop() + 60 +'px'});

        }
    });


    Sg.extend({
        /**
         * @function ajaxFormSubmit Функция отправляет на сервер форму и получает ответ
         * в виде {'status' : 'ok|error', 'content' : ''}
         * @param el object   Элемент, в контексте которого произошло событие
         * @param url string   Адрес скрипта, который отдаст данные
         * */
        'ajaxFormSubmit' : function(el, url, callback){
            var that = this;

            $.ajax({
                'type': 'POST',
                'url' : url,
                'cache': false,
                'data' : $(el).parents("form").serialize(),
                'dataType': 'json',

                'success': function(data){

                    if(that._debug)
                        console.log(data);

                    if(data.status == 'ok')
                    {
                        that.showMessage('ok', data.content);
                        //callback function
                        if(typeof(callback) == 'function')
                        {
                            callback.call(el, data);
                        }
                    }
                    else if(data.status == 'error')
                        that.showMessage('error', data.content);
                }

            });

            return true;
        }
    });


    /**
     * SG FILE API
     * */
    Sg.extend({
        'file' : {

            'settings' : {
                /**
                 * @vars
                 * */
                'dataUrl' : null,
                'deleteUrl' : null,
                'containerSelector' : null,
                'deleteSelector' : null,
                'tmpSelector' : '#files',
                'idAttribute' : 'fileid',

                /**
                 * @events
                 * */
                'afterInit' : null,
                'afterRebind' : null,
                'beforeUpload' : null, //todo
                'afterUpload' : null, //todo
                'beforeDelete' : null,
                'afterDelete' : null
            },

            '_trigger' : function(event, data){
                if(typeof(this.settings[event]) == 'function')
                {
                    this.settings[event].call(this, data);
                }
            },

            /**
             * @methods
             * */
            'init' : function(options){
                $.extend(this.settings, options);

                this.rebind();
                this._trigger('afterInit', 'myparam');
            },

            'rebind' : function(){
                var that = this;
                //ui buttons interface
                $(this.settings['deleteSelector']).button({
                    "icons" : {"primary" : "ui-icon-trash"},
                    "text" : false
                });

                //bind delete event
                $(that.settings['deleteSelector']).bind('click', function(e){
                    e.preventDefault();
                    var id = $(this).attr(that.settings['idAttribute']);
                    var tr = $(this).parents("tr").eq(0);

                    that._trigger('beforeDelete', this);

                    $.ajax({
                        'url' : that.settings['deleteUrl'],
                        'data' : {'id' : id},
                        'type' : 'POST',
                        'dataType' : 'JSON',

                        'success' : function(data){
                            if(data.status == 'ok')
                            {
                                tr.remove();
                                Sg.showMessage('ok', data.content);
                                that._trigger('afterDelete', this);
                            }
                        }

                    });



            });

                this._trigger('afterRebind');
            },

            'updateFiles' : function(){
                var that = this;
                $.ajax({
                    'type' : 'GET',
                    'dataType' : 'HTML',
                    'url' : that.settings['dataUrl'],

                    'success' : function(data){
                        $(that.settings['containerSelector']).html(data);
                        $(that.settings['tmpSelector']).empty();
                        that.rebind();
                    }
                });

            }
        }
    });


    /**
     * SG TREE API
     * */
    Sg.extend({
        tree: {
            /**
             * @var lastSelectedId Ид последнего выбранного элемента
             * */
            lastSelectedId : 0,

            /**
             * @deprecated
             * @function getSelectedItems - Функция получает ид выбранных элементов
             * в виде массива или строки, разделенной запятыми
             * @param treeId - идентификатор контейнера дерева с "#"
             * @param resultType - тип результата, может быть string | array
             * */
            getSelectedItems : function(treeId, resultType){
                resultType = resultType || 'string';
                var items = $(".tree_selected", treeId);
                var result = [];

                items.each(function(){
                    result.push(parseInt($(this).attr("contentid")));
                });

                if(resultType == 'array'){
                    return result;
                }
                else if(resultType == 'string'){
                    return result.join(',');
                }
            },

            /**
             * @deprecated
             * @function deselect Снимает выделение с элементов
             * @param treeId - идентификатор контейнера дерева с "#"
             * */
            deselect : function(treeId){
                 $(".tree_selected", treeId).removeClass("tree_selected");
            },

            /**
             * @deprecated
             * @function add
             * @param e - данные для добавления в формате json
             * */
            add : function(e){
                var typeName = e.typename;
                var parentNode = $("a[contentid='"+e.parent+"']").parent().parent();

                var ul = $(">ul", parentNode).length;

                if(ul == 0)
                {

                    console.log(parentNode);
                    parentNode.prepend('<div class="hitarea hasChildren-hitarea collapsable-hitarea"></div>');

                    parentNode.append('<ul></ul>');

                    

                    parentNode.addClass("collapsable");
                }






                var id = $("li[id='21']>ul");

               // console.log(id);


                var branches = $("<li class='closed'><span class=''>New Sublist</span></li>").prependTo("li[id='"+e.parent+"']>ul");
				$("li[id='"+e.parent+"']>ul").treeview({
					add: branches
				});

                //hitarea hasChildren-hitarea collapsable-hitarea

                //$("div.hasChildren-hitarea").unbind('click');
                
               $("div.hasChildren-hitarea").click(function(e){
                    e.stopPropagation();
                    //var a = $(this).removeClass("collapsable").addClass("expandable");

                   $(this).parent().find("ul").eq(0).toggle();

                    //console.log(a);
                   // $(this).css('border', '1px red solid');

                });

            },

            
            addNode : function(e){
                $("#cmsTree").jstree("create", null, "last", {
                    'attr' : {
                        'contentid' : e.id,
                        'rel' : e.typename
                    },
                    'state' : '',
                    'data' : e.name
                }, false, true);
            },

            editNode : function(e) {
                console.log(e);

                //icon change
                var el = $("li[contentid='"+e.id+"']");
                el.attr("rel", e.typename);
                $.jstree._focused().hover_node(el);

                //renaming
                el.find(">a").html('<ins class="jstree-icon">&nbsp;</ins>' + e.name);

            }


        }
    });


    /**
     * SG FIX API
     * */
    Sg.extend({
        'fix' : {
            /**
             * @function gridViewFix
             * Фиксит ссылки, для формы фильтрации
             * @param grid_s селектор таблицы
             * */
            'gridViewFix' : function(grid_s, modelName){
                grid_s = grid_s || '#grid_view';
                modelName = modelName || 'Tags';

                var keys = $(grid_s).find('.keys'), url = keys.attr('title');

                url = url.replace(modelName, '?' + modelName);

                keys.attr('title', url);

            }
        }
    });


    Sg.init();

    return Sg;

})();



//Sg.debug();



//Sg.print(null, 'property');

