/**
 *  функция выполняет действие нажатия на кнопку удаление.
 */
function deleteListItem(){
    if (cb){
        arr = cb.getArrCheckboxes();
        $.post(DOCUMENT_ROOT + url_to_post,  { action:'delete_item', data: JSON.stringify(arr)}, function(data){
            if (data=='success'){
                location.href = location.href;
            } else if (data=='bad_request'){
                alert("Неправильно передан параметр data. Код ошибки #1001-304");
            } else if (data=='bad_query'){
                alert("Ошибка в сформированном запросе. Код ошибки #1001-305");
            } else if (data=='bad_method'){
                alert("Не найден метод в библиотеке класса");
            } else if (data=='bad_object'){
                alert("Не найден объект библиотеки");
            } else if (data=='empty_data'){
                alert("Ошибка в сформированном запросе. Код ошибки #1001-306");
            }
        });
    }
}

/**
 *  функция выполняет действие нажатия на кнопку видимость.
 */
function visibility(){
    if (cb){
        arr = cb.getArrCheckboxes();
        
        $.post(DOCUMENT_ROOT + url_to_post,  { action:'change_visibility', data: JSON.stringify(arr)}, function(data){
            if (data=='success'){
                location.href = location.href;
            } else if (data=='bad_request'){
                alert("Неправильно передан параметр data. Код ошибки #1001-307");
            } else if (data=='bad_query'){
                alert("Ошибка в сформированном запросе. Код ошибки #1001-308");
            } else if (data=='empty_data'){
                alert("Ошибка в сформированном запросе. Код ошибки #1001-309");
            }
        });
    }
}

/* Управляет левым меню
*  leftMenuControl object
*  par integer - количество главных пунктов левого меню */
function leftMenuControl(count){
    countPoints = count ? count : 0;
    
    this.toggleSlide = function(idItem,idBlock) {
        for (var f=1;f<=countPoints;f++) {
            f=f+'';
            if (node = document.getElementById('item'+f) ) {
                if ('item'+f == idItem ) {
                    node.className = 'expanded';
                } else {
                    node.className = '';
                }
            }
         
            if (node = document.getElementById('subBlock'+f) ) {
                if ('subBlock'+f == idBlock ) {
                    node.style.display = 'block';
                } else {
                    node.style.display = 'none';
                }
            }	
        }
    } 
}

/* Управляет списком
*  centerContentListControl object
*  par integer - управление списком текущего раздела */
function centerContentListControl(count){
    countPoints = count ? count : 0;
    
    this.showEditButton = function(butNum) {
        
        for (var f=1;f<=countPoints;f++) {
            f=f+'';
            if (node = document.getElementById('num'+f) ) {
              if ('num'+f == butNum ) {
                node.style.visibility = 'visible';
              } else {
                node.style.visibility = 'hidden';
              }
            }
        }
    }
} 

function listFlag(){
    checkboxes = new Array();
    
    constructor();

    this.getArrCheckboxes = function(){
        return checkboxes;
    }
    
    function constructor(){
        if (checkboxes.length>0){
            $('#mult_delete').show();
            $('#mult_visibility').show();
        } else {
            $('#mult_delete').hide();
            $('#mult_visibility').hide();
        }
    }
    
    this.checkFlags = function(id){
        found = false;
        temp_arr = new Array();
        k = 0;
        for(var i in checkboxes){
            if (id==checkboxes[i]){
                found = true;
            } else {
                temp_arr[k] = checkboxes[i];
                k++;
            }
        }

        checkboxes = temp_arr;
        
        if (!found) checkboxes.push(id);
        constructor();
    }
}

function openDialogEdit(id_element, type){
    //функции для всплывающего окна
    function onSave(popup){
        var wasIteration = false;
        var bValid = true;
            
        if (document.forms[popup]){
            obj = document.forms[popup].elements;
            
            i = 0;

            tab = false;

            code_tmp = '';
            for(var j in obj){
                if (obj[j] && obj[j].id) {
                    isFieldValid = wasIteration = true;
                    current_id = obj[j].id;

                    if (textAreaFields[current_id] && tinyMCE.get(current_id)){
                        obj_value = tinyMCE.get(current_id).getContent();
                        $('#' + current_id).val(obj_value);
                    } else {
                        obj_value = obj[j].value;
                    }

                    if (current_id==code_id && old_code!=obj_value) code_tmp = obj_value;

                    if (allFields[current_id]){
                        cur_obj = $('#' + current_id);
                        cur_obj.removeClass('ui-state-error');

                        if (allFields[current_id]["min"] || allFields[current_id]["max"]){
                            min = allFields[current_id]["min"] ? allFields[current_id]["min"] : 0;
                            max = allFields[current_id]["max"] ? allFields[current_id]["max"] : 0;
                            //bValid = bValid && dialogChecker.checkLength(current_id, min, max);
                            isFieldValid = dialogChecker.checkLength(current_id, min, max);
                            bValid = bValid && isFieldValid;
                        }

                        if (isFieldValid && allFields[current_id]["rule"]){
                            isFieldValid = dialogChecker.checkRegexp(current_id,allFields[current_id]["rule"],(allFields[current_id]["info"] ? allFields[current_id]["info"] : ''));
                            bValid = bValid && isFieldValid;
                        }

                        if (isFieldValid && allFields[current_id]["selected"]){
                            isFieldValid = dialogChecker.checkSelection(current_id, allFields[current_id]["info"] ? allFields[current_id]["info"] : '');
                            bValid = bValid && isFieldValid;
                        }


                        if (!isFieldValid && !tab && allFields[current_id]["tabs"] && allFields[current_id]["tabs"]["id"] && allFields[current_id]["tabs"]["tab"]){
                            $('#' + allFields[current_id]["tabs"]["id"]).tabs('select', '#' + allFields[current_id]["tabs"]["tab"]);
                            tab= true;
                        }

                    }

                    i++;
                }
            }


            if (bValid && wasIteration){
                dialogChecker.runLight();
                dialog_object = this;

                if (code_tmp){
                    $.post(DOCUMENT_ROOT + url_to_post,  { action:'check_code', field_code: code_tmp}, function(data){
                        if (data=='code_exists') dialogChecker.code_exists(code_id);
                        else document.forms[popup].submit();
                    });
                } else {
                    document.forms[popup].submit();
                }
            }
        } else {
            alert('Не найдена форма form_popup');
        }
    }

    function  onOpen(type){
        if (code_id) old_code = $('#' + code_id).val();
        $('#' + type).dialog('option', 'minHeight', $('#' + type).dialog('option', 'height'));
        $('#' + type).dialog('option', 'minWidth', $('#' + type).dialog('option', 'width'));
        if (current_id>0) $('#ui-dialog-title-' + type).html(type=='dfolder' ? 'Редактирование каталога' : 'Редактирование элемента');
        else $('#ui-dialog-title-' + type).html(type=='dfolder' ? 'Новый каталог' : 'Новый элемент');
    }
    /* Функция диалогового окна
     * Вызывается при обращении к элементу: $('#dialog').dialog('open');
     */

    //$('#test').html(this.sizeH + '; ' + $('#dialog').dialog('option', 'height'));
    $("#dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: height_popup,
            width: width_popup,
            modal: true,
            open: function(event, ui) {
                 <!-- TinyMCE -->
                 tinyMCE.init({
                    width : width_popup - 100,
                    mode : "textareas",
                    theme : "advanced",
                    skin : "o2k7",
                    skin_variant : "black",
                    //plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template, images",
                    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,images,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
                    theme_advanced_buttons1 : "bold,italic,underline,formatselect,link,justifyleft,justifycenter,justifyright,pasteword,pastetext,table,images,|,bullist,numlist,|,undo,redo,|,code,fullscreen",
                    theme_advanced_buttons2 : "fontsizeselect,forecolor,backcolor",
                    //theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
                    //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                    theme_advanced_toolbar_location : "top",
                    theme_advanced_toolbar_align : "left",
                    theme_advanced_statusbar_location : "bottom",
                    theme_advanced_resizing : true
                });
                <!-- TinyMCE -->
                onOpen('dialog');
            },
            buttons: { 'Сохранить': function() { onSave('form_popup');} },
            close: function() {
                tinyMCE.triggerSave();
                var i, t = tinyMCE.editors;
                for (i in t){
                    if (t.hasOwnProperty(i)){
                        t[i].remove();
                    }
                }
                $("#dialog").dialog( 'destroy' );
                $("#dialog").html("");
            }
    });

    $("#dfolder").dialog({
            bgiframe: true,
            autoOpen: false,
            height: height_popup_folder,
            width: width_popup_folder,
            modal: true,
            open: function(event, ui) {
                <!-- TinyMCE -->
                tinyMCE.init({
                    width : width_popup_folder - 100,
                    mode : "textareas",
                    theme : "advanced",
                    skin : "o2k7",
                    skin_variant : "black",
                    //plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template, images",
                    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,images,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
                    theme_advanced_buttons1 : "bold,italic,underline,formatselect,link,justifyleft,justifycenter,justifyright,pasteword,pastetext,table,images,|,bullist,numlist,|,undo,redo,|,code,fullscreen",
                    theme_advanced_buttons2 : "fontsizeselect,forecolor,backcolor",
                    //theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
                    //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                    theme_advanced_toolbar_location : "top",
                    theme_advanced_toolbar_align : "left",
                    theme_advanced_statusbar_location : "bottom",
                    theme_advanced_resizing : true
                });
                <!-- TinyMCE -->
                onOpen('dfolder');
            },
            buttons: { 'Сохранить': function() {onSave('form_popupf');}},
            close: function() {
                tinyMCE.triggerSave();
                var i, t = tinyMCE.editors;
                for (i in t){
                    if (t.hasOwnProperty(i)){
                        t[i].remove();
                    }
                }
                $("#dfolder").dialog( 'destroy' );
                $("#dfolder").html("");
            }
    });
    
    current_id = id_element;

    $.post(DOCUMENT_ROOT + url_to_post, {action:'open_popup', id_element: id_element, type: (type=='dialog' ? 1 : 0)}, function(data){
        $('#' + type).html('<DIV style="padding:5px 5px 5px 5px;  background:#0C0D0E none repeat scroll 0 0">' + data + '</DIV>');
        $('#' + type).dialog('open');
    });
}

function dialogChecker(){
    function updateTips(id, text) {
        tips_obj = $('#' + id + '_error');
        if (typeof(tips_obj)=='object') tips_obj.html(text);
    }

    this.runLight = function(){
        $('.popup_field_error').fadeIn(50).fadeOut(100).fadeIn(50);
    }

    this.checkLength = function(id, min,max) {
        o = $('#' + id);
        
        $('#' + id + '_error').html("&nbsp;");
        
        if ( max>0 || min>0 ) {
            error = false;
            if (max>0 && min>0){
                if ( o.val().length > max || o.val().length < min ) {
                    updateTips(id, "Длина поля должна быть от "+min+" до "+max+" символов.");
                    error = true;
                }
            } else if (max>0 && !min){
                if ( o.val().length > max ) {
                    updateTips(id, "Максимальная длина поля "+max+" символов.");
                    error = true;
                }
            } else if (min>0 && !max){
                if ( o.val().length < min ) {
                    updateTips(id, "Минимальная длина поля "+min+" символов.");
                    error = true;
                }
            }
            
            if (error) {
                o.addClass('ui-state-error');
                return false;
            }
        }

        return true;
    }

    this.checkRegexp = function checkRegexp(id,regexp,text) {
        o = $('#' + id);
        
        $('#' + id + '_error').html("&nbsp;");
        if ( !( regexp.test( o.val() ) ) ) {
                o.addClass('ui-state-error');
                updateTips(id, text);
                return false;
        } else {
                return true;
        }
    }

    this.code_exists = function(id){
        o = $('#' + id);
        
        $('#' + id + '_error').html("&nbsp;");
        o.addClass('ui-state-error');
        updateTips(id, 'Такой код уже используется');
    }

    this.checkSelection = function(id, text){
        o = $('#' + id);

        $('#' + id + '_error').html("&nbsp;");
        if (o.val()>0) {
            return true;
        } else {
            o.addClass('ui-state-error');
            updateTips(id, text);
            return false;
        }
        
    }
}

/**
 *sdfdsf
 */
function uploadIMG(options){
    // настройки по умолчанию
    var options = jQuery.extend({
        link_upload_id: '',
        delete_id: '',
        path_id: '',
        input_id: '',
        image_id: '',
        log_id: '',
        side: false,
        img: '',
        url: '',
        width: 0,
        height: 0,
        watermark: 0
    },options);

    this.deletePic = function(){
        if (confirm("Удалить картинку с сервера?")) {
            if (options.input_id){
                $.post(DOCUMENT_ROOT + url_to_post,  { action:'delete_pic', image: $("#" + options.input_id).val(), side: options.side}, function(data){});
            }
        }

        $("#" + options.link_upload_id).css({"class": "middle"});
        $('#' + options.delete_id).hide();
        $('#' + options.path_id).hide();
        $("#" + options.input_id).attr({value: ""});
        $("#" + options.image_id).attr({src: DOCUMENT_ROOT + '/img/sample84b.gif'});//width="50px" height="50px"
    }

    this.upload = function(){
        URL = options.url;
        IMG = options.img;

        if ($('#' + options.input_id).val()) {
            $('#' + options.delete_id).show();
            $('#' + options.path_id).show();
        } else {
            $('#' + options.delete_id).hide();
            $('#' + options.path_id).hide();
        }
        
        // ------ ------
        new AjaxUpload(options.link_upload_id, {
             action: URL,
             onComplete : function(file, response){
                 complete = false;console.log(response);
                 response = eval(response);
                 side = result = file_name = '';
                 if (typeof(response)=='object' && response[0]){
                     for(var i in response[0]){
                         if (i=='name')        file_name = response[0][i];
                         else if (i=='result') result    = response[0][i];
                         else if (i=='side')   side      = response[0][i];
                         
                         if (result && file_name) complete = true;
                     }
                 }
                 if (complete) {
                     $("#" + options.path_id).html('<a style="width:290px" target="_blank" href="' + side + file_name + '">' + side + file_name + '</a>');
                     $("#" + options.link_upload_id).css({"class": "upper"});
                     $("#" + options.delete_id).show();
                     $("#" + options.path_id).show();
                     $("#" + options.input_id).attr({value: file_name});
                     $("#" + options.image_id).attr({src: IMG + file_name});//width="50px" height="50px"

                     if (options.log) $("#" + options.log).html("");
                 } else {
                     alert("Файл не загрузился");
                 }
             },
             onSubmit : function(file , ext){
                 //if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
                 if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
                     /* Setting data */
                     this.setData({ 'action': 'load_img', 'side': options.side, 'width': options.width, 'height': options.height, 'watermark': options.watermark});
                     if (options.log) $('#' + options.log).text('Uploading ' + file);
                 } else {
                     // extension is not allowed
                     if (options.log) $('#' + options.log).text('Ошибка загружаемого файла.');
                     // cancel upload
                     return false;
                 }
             }
        });
    }
}

function helpinitialization(){
    $("#help_desc").dialog({
            bgiframe: true,
            autoOpen: false,
            resizable: false,
            modal: true,
            height: 400,
            width: 600,
            close: function() {
                $("#dialog").dialog( 'destroy' );
                $("#dialog").html("");
            }
    });

    $('#help_desc').dialog('open');
}
