var ui = {
    toggleblock:function(obj) {
        $(obj).parent().next().slideToggle("slow");
    },
    cnt: [],
    tabs:function(name, def) {
		var tab_titles = [];
        var i = 0;
		def = def | 0;

        $('#'+name+'>div').each(function(){
            if(i) $(this).hide();
            var ahref = $('<li style="cursor: pointer"><a href="javascript:{}">'+$(this).attr('title')+'</a></li>');
            ahref.click(function() {
                var el = $(this);
				el.parent().find('li').removeClass('active');
				el.addClass('active');
                $('#'+name+'>div').each(function(){
                    if($(this).attr('title') == el.find('a').html())
                        $(this).show();
                    else
                        $(this).hide();
                });
            });
            tab_titles.push(ahref);
            i++;
        });

		$('#'+name+'>ul.gstab_ttl').remove();
		
        var ttl = $('<ul class="gstab_ttl"></ul>');

        for(var t=0; t < tab_titles.length; t++) {
            ttl.append(tab_titles[t]);
			if(def == t) {
				tab_titles[t].click();
			}
        }

        $('#'+name).prepend(ttl);
    },
    addtotab: function(name, text, newname) {
        $('#'+name).hide();
        $('#'+name).append(text);
        $('#'+name).show();
        this.tabs(name);
        this.tabs(newname);
    },
    media: function(callback) {
        $('<div id="myelfinder" />').dialogelfinder({
                   url : '/core/library/php/elfinder-2.0/php/connectorEditor.php',
                   lang : 'ru',
                   width : 900, modal : true, title : 'Изображения', destroyOnClose : true,
                   getFileCallback : callback,
                   commandsOptions : {
                        // "getfile" command options.
                        getfile : {
                            onlyURL  : true,
                            // allow to return multiple files info
                            multiple : false,
                            // allow to return filers info
                            folders  : false,
                            // action after callback (""/"close"/"destroy")
                            oncomplete : 'destroy'
                        }
                   }
               });
    },
    mediaCallback:function(id, text) {
        ui.cnt[id](text);
    },
    showimg:function(name, str) {
        ui.media(function(t){
            core.action('getImageProperty', {name:str, value:t.url}, function(text){
				$(name).parent().parent().parent().parent().replaceWith(text);
			});
        });
    },
	showImgProp:function(name, str) {
        ui.media(function(t){
            core.action('getImageProperty', {name:str, value:t.url, prop:true}, function(text){
				$(name).parent().parent().parent().parent().replaceWith(text);
			});
        });
    },
	addImageProp: function(obj, name) {
		core.action('getImageProperty', {name:name, value:''}, function(text){
				var tmp = $(obj).clone();
				$(obj).removeAttr('onclick');
				$(obj).after(tmp);
				$(obj).find('table').replaceWith(text);
			});
	},
	addVariant:function() {
		var num = $('#variants tr').length;
        var html = $('#template_for_variant').html();
        html = html.replace(/%NUM%/ig, num);
        $('#variants').append(html);
	},
    relatives:function() {
        core.include('/core/library/js/jstree/jquery.jstree.js');
        core.include('/core/library/js/jstree/themes/classic/style.css', 'css');
        $('<div><div id="jsTreeC"></div></div>').appendTo('body').dialog({
            width:400,
            height:500,
            resizable:true,
            draggable:false,
            modal:true,
            title:'Выберите элемент',
            open:function() {
                $.jstree._themes = "/core/library/js/jstree/themes/";
                $("#jsTreeC").jstree({
                    "json_data" : {
                        "ajax" : {
                            "url" : "/admin/ajax/Core/ajax?action=jstree&shop_only=1",
                            "data" : function (n) {
                                return { id : n.attr ? n.attr("data-eid") : 0, did : n.attr ? n.attr("data-did") : 0  };
                            }
                        }
                    },
                    "plugins" : [ "themes", "json_data", "ui" ]
                }).bind("select_node.jstree", function (event, data) {
                    $("#jsTreeC").data('ncid', data.rslt.obj.attr("data-eid"));
                    $("#jsTreeC").data('name', data.rslt.obj.find('a').text());
                });
            },
            close: function() { $(this).dialog('destroy').remove(); },
            buttons: {
                "Выбрать":function() {
                    $('#rel_cats_list').append("<div><span class='gs'>"+$("#jsTreeC").data('name')+"</span><input type='hidden' name='dop_categories[]' value='"+$("#jsTreeC").data('ncid')+"' /><img width=\"16\" height=\"16\" style=\"margin-left: 15px;margin-top: 5px;cursor:pointer;\" onclick=\"$(this).parent().remove()\" title=\"Удалить\" src=\"/core/admin/templates/default/img/icons/delete-16.png\"></div>");
                    $(this).dialog('close');
                }
            }
        });
    },
    addDopCategory:function() {
        core.action('shopTree', {shop_only:1}, function(text){
            $('<div><div id="jsTreeC"></div></div>').appendTo('body').dialog({
                width:417,
                height:500,
                resizable:false,
                draggable:false,
                modal:true,
                title:'Выберите категории',
                open:function() { $('#jsTreeC').html(text); },
                close: function() { $(this).dialog('destroy').remove(); },
                buttons: {
                    "Выбрать":function() {
                        $('.my_checkbox',$("#jsTreeC")).each(function(){
                            //$('#rel_cats_list').html();
                            if($(this).parent().hasClass('type_category') && !$(this).parent().hasClass('tree_root') && $(this).data('checked'))
                                $('#rel_cats_list').append("<div><span class='gs'>"+$(this).data('name')+"</span><input type='hidden' name='dop_categories[]' value='"+$(this).data('neid')+"' /><img width=\"16\" height=\"16\" style=\"margin-left: 15px;margin-top: 5px;cursor:pointer;\" onclick=\"$(this).parent().remove()\" title=\"Удалить\" src=\"/core/admin/templates/default/img/icons/delete-16.png\"></div>");
                        });
                        $(this).dialog('close');
                    }
                }
            });
        });
    },
    addRecTovar:function() {
        core.action('shopTree', {}, function(text){
            $('<div><div id="jsTreeC"></div></div>').appendTo('body').dialog({
                width:417,
                height:500,
                resizable:false,
                draggable:false,
                modal:true,
                title:'Выберите товары',
                open:function() { $('#jsTreeC').html(text); },
                close: function() { $(this).dialog('destroy').remove(); },
                buttons: {
                    "Выбрать":function() {
                        $('.my_checkbox',$("#jsTreeC")).each(function(){
                            //$('#rec_tovars_list').html();
                            if($(this).parent().hasClass('type_element') && $(this).data('checked'))
                                $('#rec_tovars_list').append("<div><span class='gs'>"+$(this).data('name')+"</span><input type='hidden' name='rec_tovars[]' value='"+$(this).data('neid')+"' /><img width=\"16\" height=\"16\" style=\"margin-left: 15px;margin-top: 5px;cursor:pointer;\" onclick=\"$(this).parent().remove()\" title=\"Удалить\" src=\"/core/admin/templates/default/img/icons/delete-16.png\"></div>");
                        });
                        $(this).dialog('close');
                    }
                }
            });
        });
    },
    translit: function(text, space) {
        if(!space) space = '-';
        var arr = {
            'а':'a',
            'б':'b',
            'в':'v',
            'г':'g',
            'д':'d',
            'е':'e',
            'ё':'jo',
            'ж':'zh',
            'з':'z',
            'и':'i',
            'й':'j',
            'к':'k',
            'л':'l',
            'м':'m',
            'н':'n',
            'о':'o',
            'п':'p',
            'р':'r',
            'с':'s',
            'т':'t',
            'у':'u',
            'ф':'f',
            'х':'kh',
            'ч':'ch',
            'ц':'c',
            'ш':'sh',
            'щ':'shh',
            'ъ':'',
            'ы':'y',
            'ь':'',
            'э':'eh',
            'ю':'ju',
            'я':'ja',
            ' ':space
        };

        var arr_b = {
            'А':'A',
            'Б':'B',
            'В':'V',
            'Г':'G',
            'Д':'D',
            'Е':'E',
            'Ё':'Jo',
            'Ж':'Zh',
            'З':'Z',
            'И':'I',
            'Й':'J',
            'К':'K',
            'Л':'L',
            'М':'M',
            'Н':'N',
            'О':'O',
            'П':'P',
            'Р':'R',
            'С':'S',
            'Т':'T',
            'У':'U',
            'Ф':'F',
            'Х':'Kh',
            'Ч':'Ch',
            'Ц':'C',
            'Ш':'Sh',
            'Щ':'Shh',
            'Ъ':'',
            'Ы':'Y',
            'Ь':'',
            'Э':'Eh',
            'Ю':'Ju',
            'Я':'Ja',
            ' ':space
        };
        var newtext = '';
        for(var i = 0; i < text.length; i++) {
            if(arr[text[i]])
                newtext += arr[text[i]];
            else if(arr_b[text[i]])
                newtext += arr_b[text[i]];
            else if(text[i] == 'ь' ||text[i] == 'Ь'||text[i] == 'ъ'||text[i] == 'Ъ' )
                newtext += '';
            else
                newtext += text[i];
        }
        return newtext;
    },
    delimg: function(obj, full_delete){
		if(full_delete) {
			$(obj).parent().parent().parent().parent().parent().parent().remove();
			return;
		}
    },
	delImgProp: function(obj){
		var img = $($(obj).parent().parent().parent().parent().find('td').get(0)).find('img');
		var inp = $($(obj).parent().parent().parent().parent().find('td').get(1)).find('input');
        img.attr('src', '/core/admin/templates/default/img/icons/default.png');
        img.attr('width', 64);
        inp.val('/core/admin/templates/default/img/icons/default.png');
        $(obj).remove();
    },
    inputBox:function(elems) {
      $(elems).each(function(){
          if(!$(this).hasClass('gs-inputBox')) {
                var inp = $(this);
                inp.addClass('gs-inputBox');

                if(inp.val() == '')
                {
                    inp.val(inp.attr('def'));
                    inp.addClass('inputdefault');
                }
                inp.click(function() {
                    if(inp.val() == inp.attr('def'))
                        inp.val('');
                    inp.removeClass('inputdefault');
                });

                inp.blur(function() {
                    if(inp.val() == '')
                    {
                        inp.val(inp.attr('def'));
                        inp.addClass('inputdefault');
                    }
                });

                $(this).keydown(function() {
                    if(inp.val() == inp.attr('def'))
                        inp.val('');
                    inp.removeClass('inputdefault');
                });
          }
      });
    },
    input: function() {
        obj = '[def]';
        $(obj).each(function(){
            if($(this).val() == '')
            {
                $(this).val($(this).attr('def'));
                $(this).addClass('inputdefault');
            }
            $(this).click(function() {
                if($(this).val() == $(this).attr('def'))
                    $(this).val('');
                $(this).removeClass('inputdefault');
            });

            $(this).blur(function() {
                if($(this).val() == '')
                {
                    $(this).val($(this).attr('def'));
                    $(this).addClass('inputdefault');
                }
            });

            $(this).keydown(function() {
                if($(this).val() == $(this).attr('def'))
                    $(this).val('');
                $(this).removeClass('inputdefault');
            });

            $(this).focus(function() {
            });
        });
    },
    fade: {
        time:false,
        current_row:false,
		rows: function(table, row) {
            var ii = 0;
            $(table).children('tbody').children('tr').each(function(){
				if(ii > 0) {
					if(this == row) {
						$(this).addClass('gui_activeRow');
					} else
						$(this).removeClass('gui_activeRow');
				}
				ii++;
			});
		},
		element: function(table, row) {
			var ii = 0;
            var detached_tbody = $(table).children('tbody').detach();
            detached_tbody.children('tr').each(function(){
            //$(table).children('tbody').children('tr').each(function(){
				if(ii > 0) {
					if(this == row) {
						$(this).addClass('gui_tbl_active');
					} else {
						$(this).removeClass('gui_tbl_active');
					}
				}
				ii++;
			});
            $(table).append(detached_tbody);
		},
		removeFade: function(table) {
            //clearTimeout(ui.fade.time);
			$(table).children('tbody').children('tr').removeClass('gui_activeRow');
		}
	},
	overlay:function(obj, flag) {
		obj = obj || document;
		var dv = $('div[data-ui="overlay"]');
		if(obj == document) {
			var left = 0;
			var top = 0;
			var w = $(obj).width();
			var h = $(obj).height();
			dv.css({
				position:'fixed',
				right:0,
				bottom: 0,
				width:w,
				height:h,
				top:top+'px',
				left:left+'px',
				opacity: 0.98
			});
		} else if($(obj).offset()) {
			var left = $(obj).offset().left;
			var top = $(obj).offset().top;
			var w = $(obj).width();
			var h = $(obj).height();
			if(flag)
				h = $(document).height() - top;
			dv.css({
				width:w,
				height:h,
				top:top+'px',
				left:left+'px',
				opacity: 0.98
			})
		}
		dv.show();
	},
	overlayDestroy:function() {
		setTimeout(function(){$('div[data-ui="overlay"]').fadeOut('slow')}, 200);
	},
    uploader:function(obj, pid) {
        core.action('flashUpload',{},function(text){
            var of = $(obj).offset();
            var over = $('<div class="ui-widget-overlay"></div>').appendTo('body');
            var top = 170;
            //console.log(document, $('body'));
            var d = $('<div class="gs-gui-floatbox gs-gui-roundbox gs-gui-roundbox-shadow" style="width:400px;left: 50%; top: '+top+'px;margin-left: -200px;z-index: 10001;position:fixed;"></div>');
            d.append(text).append("<input type='button' value='Закрыть' onclick='$(this).parent().remove();$(\".ui-widget-overlay\").remove();core.ajaxReload();' style='float:right; margin-top: -20px;'>").appendTo('body');
            var swfu;

            var settings = {
                flash_url : "/core/library/js/swfupload/swfupload_fp10/swfupload.swf",
                flash9_url : "/core/library/js/swfupload/swfupload_fp9/swfupload_fp9.swf",
                upload_url: "/admin/ajax/Core/ajax?action=uploadImages&pid="+pid,
                post_params: {"PHPSESSID" : SID},
                file_size_limit : "100 MB",
                file_types : "*.*",
                file_types_description : "All Files",
                file_upload_limit : 100,
                file_queue_limit : 0,
                custom_settings : {
                    progressTarget : "fsUploadProgress",
                    cancelButtonId : "btnCancel"
                },
                debug: false,

                // Button settings
                button_width: 80,
                button_height: 22,
                button_placeholder_id: "spanButtonPlaceHolder",
                button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                button_text:'&nbsp;',

                // The event handler functions are defined in handlers.js
                swfupload_preload_handler : preLoad,
                swfupload_load_failed_handler : loadFailed,
                file_queued_handler : fileQueued,
                file_queue_error_handler : fileQueueError,
                file_dialog_complete_handler : fileDialogComplete,
                upload_start_handler : uploadStart,
                upload_progress_handler : uploadProgress,
                upload_error_handler : uploadError,
                upload_success_handler : uploadSuccess,
                upload_complete_handler : uploadComplete,
                queue_complete_handler : queueComplete	// Queue plugin event
            };
            swfu = new SWFUpload(settings);

        });
    },
    inputRadio: {
        click: function(obj) {
            var p = $(obj).parent().parent();
            var c = p.find('span');
            c.each(function() {
                $(this).removeClass('choosed');
                $(this).next().removeAttr('checked');
            })
            $(obj).addClass('choosed');
            $(obj).next().attr('checked', 'checked');
        }
    }
}
