$(document).ready(function() {

    $(".enc_tooltip").tooltip({
        bodyHandler: function() {
            return $($(this).attr("block")).html();
        },
        showURL: false
    });

    $("#TsT").css({
        "border":"2px solid",
        "margin":"10px",
        "padding":"10px",
        "text-align":"center",
        "position":"fixed",
        "top":"0",
        "background-color":"#EBD8C9",
        "display":"none"
    });

    $("#refresh").click(function(event){
        var src1;
        src1 = $("input[name='mwlink']").val();
        $("#wpage").attr("src", src1);
        event.preventDefault();
    });

    //tabs ->
    $(function() {
        var $tab_title_input = $('#tab_title');
        var $tab_type_input = $('#tab_type');
        var tab_counter;
        var mtab;

        mtab = $("input[name='curtabs']").val();

        if (mtab > 0 ){
            mtab++
            tab_counter = mtab;
        }
        else {
            tab_counter = 2;
        }

        // tabs init with a custom tab template and an "add" callback filling in the content
        var $tabs = $('#tabs').tabs({
            selected: 0,
            tabTemplate: '<li><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-trash">Удалить вкладку</span></li>',
            add: function(event, ui) {
                var tab_type = $tab_type_input.val();// || ' '+tab_counter+' content.';
                var tab_title = $tab_title_input.val() || 'Вкладка № '+tab_counter;
                switch (tab_type) {
                    case '0':
                        $(ui.panel).append(
                            '<div class="form-row">'+
                            '<div class="label">Ссылка на статью ВИКИПЕДИИ</div>'+
                            '<div class="input-container"><input type="text" name="owlink[]" class="input wiki-link" /></div>'+
                            '</div>'+
                            '<div class="form-row">'+
                            '<div class="label">Описание</div>'+
                            '<div class="input-container"><textarea name="otext[]" rows="10" cols="80" class="textarea req-string" ></textarea><br /><a href="javascript:setup();">[ Загрузить визуальный редактор ]</a></div>'+
                            '</div>'+
                            '<div id="phg_'+tab_counter+'"></div>'+
                            '<div class="clear"></div>'+
                            '<hr width="100%"/>'+
                            '<input type="hidden" name="tab_id[]" value="'+tab_counter+'"/>'+
                            '<input type="hidden" name="tab_type[]" value="'+tab_type+'"/>'+
                            '<input type="hidden" name="tab_title[]" value="'+tab_title+'"/>'+
                            '<input type="file" name="img_'+tab_counter+'" id="phtgallery_'+tab_counter+'"/>'+
                            '<a href="javascript:$(\'#phtgallery_'+tab_counter+'\').uploadifyUpload();">Загрузить</a> |'+
                            '<a href="javascript:$(\'#phtgallery_'+tab_counter+'\').uploadifyClearQueue();">Очистить очередь</a><br/ ><br />'+
                            '<input type="text" name="ilink_'+tab_counter+'" class="input" style="width: 500px;" > <a href="#" id="ilinkAdd_'+tab_counter+'" >Добавить изображение по ссылке</a>'
                            );
                        $("#ilinkAdd_"+tab_counter).click(function(event){
                            $.post('/encyclopaedia/functions/', {
                                pare_id: $("input[name='id']").val(),
                                ilink: $("input[name='ilink_"+(tab_counter-1)+"']").val(),
                                phg: tab_counter-1
                            }, function(msg){
                                var k = tab_counter-1;
                                var id = '#phg_'+k;
                                $(id).append(msg);
                                $("input[name='ilink_"+tab_counter+"']").text('');
                                $("input[name='ilink_"+tab_counter+"']").val('')
                            });
                            event.preventDefault();
                        });
                        $('#phtgallery_'+tab_counter).uploadify({
                            'uploader':'/public_scripts/newcoder/uploadify/uploadify.swf',
                            'script':'/public_scripts/newcoder/uploadify/uploadify_enc_phtgal.php',
                            'folder':'/public_images/enc/'+$("input[name='id']").val()+'/phtgal',
                            'cancelImg':'/public_scripts/newcoder/uploadify/cancel.png',
                            'buttonText':'',
                            'buttonImg':'/images/standart/upload.png',
                            'rollover':'true',
                            'width':'94',
                            'height':'26',
                            'fileDesc':'Изображения',
                            'fileExt':'*.jpg;*.JPG;*.png;*.bmp',
                            'scriptData':{
                                'pare_id': $("input[name='id']").val(),
                                'phtgal_id': tab_counter
                            },
                            'multi':true,
                            'onComplete': function(event,queueID,fileObj,response,data) {
                                var k = tab_counter-1;
                                var id = '#phg_'+k;
                                $(id).append(response);
                                return true;
                            },
                            'onAllComplete': function() {
                                var k = tab_counter-1;
                                var id = '#phg_'+k;
                                $(id).append('<div class="clear"></div><b>Фотографии загружены, сохраните статью, чтобы отредактировать их параметры.</b>');
                            }
                            
                        });
                        break;
                    case '1':
                        $(ui.panel).append(
                            '<div class="form-row">'+
                            '<div class="label">Введите слово дял поиска</div>'+
                            '<div class="input-container"><input type="text" name="" class="input" /></div>'+
                            '<input type="hidden" name="tab_id[]" value="'+tab_counter+'"/>'+
                            '<input type="hidden" name="tab_type[]" value="'+tab_type+'"/>'+
                            '<input type="hidden" name="tab_title[]" value="'+tab_title+'"/>'+
                            '<button id="" type="" class="">Поиск</button>'+
                            '</div>'+
                            '<div class="clear"></div>'
                            );
                        break;
                    default:
                        break;
                }
            }
        });

        // modal dialog init: custom buttons and a "close" callback reseting the form inside
        var $dialog = $('#dialog').dialog({
            autoOpen: false,
            modal: true,
            title: 'Добавлени вкладки',
            buttons: {
                'Добавить': function() {
                    addTab();
                    $(this).dialog('close');
                },
                'Отмена': function() {
                    $(this).dialog('close');
                }
            },
            open: function() {
                $tab_title_input.focus();
            },
            close: function() {
                $form[0].reset();
            }
        });

        // addTab form: calls addTab function on submit and closes the dialog
        var $form = $('form',$dialog).submit(function() {
            addTab();
            $dialog.dialog('close');
            return false;
        });

        // actual addTab function: adds new tab using the title input from the form above
        function addTab() {
            var tab_title = $tab_title_input.val() || 'Вкладка № '+tab_counter;
            $tabs.tabs('add', '#tabs-'+tab_counter, tab_title);
            tab_counter++;
        }

        // addTab button: just opens the dialog
        $('#add_tab')
        .button()
        .click(function(event) {
            $dialog.dialog('open');
            event.preventDefault();
        });

        // close icon: removing the tab on click
        // note: closable tabs gonna be an option in the future - see http://dev.jqueryui.com/ticket/3924
        $('#tabs span.ui-icon-trash').live('click', function() {
            var index = $('li',$tabs).index($(this).parent());
            if (confirm('Вы действительно хотите удалить эту вкладку? Восстановить ее будет уже невозможно!')) {
                $tabs.tabs('remove', index);
            }
        });
    });

    //<-tabs
    /*
    $("#photogallerychb").click(function(){
        $("#photogallery").slideToggle();
    });

    $("#photogallerychb").button({
        icons: {
            primary:'ui-icon-check'
        }
    },{
        text: false
    });*/

    $('#phtgallery').uploadify({
        'uploader':'/public_scripts/newcoder/uploadify/uploadify.swf',
        'script':'/public_scripts/newcoder/uploadify/uploadify_enc_phtgal.php',
        'folder':'/public_images/enc/'+$("input[name='id']").val()+'/phtgal',
        'cancelImg':'/public_scripts/newcoder/uploadify/cancel.png',
        'buttonText':'',
        'buttonImg':'/images/standart/upload.png',
        'rollover':'true',
        'width':'94',
        'height':'26',
        //'fileDesc':'Изображения',
        //'fileExt':'*.jpg;*.JPG;*.png;*.PNG;*.bmp;*.BMP',
        'scriptData':{
            'pare_id': $("input[name='id']").val()
        },
        'multi':true,
        'onComplete': function(event,queueID,fileObj,response,data) {
            $("#phtGalImgs").append(response);
            return true;
        },
        'onAllComplete': function() {
            $("#phtGalImgs").append('<div class="clear"></div><b>Фотографии загружены, сохраните статью, чтобы отредактировать их параметры.</b>');
        }
    });

    $("#ilinkAdd").click(function(event){
        $.post('/encyclopaedia/functions/', {
            pare_id: $("input[name='id']").val(),
            ilink: $("input[name='ilink']").val()
        }, function(msg){
            $("#phtGalImgs").append(msg);
            $("input[name='ilink']").text('');
            $("input[name='ilink']").val('')
        });
        event.preventDefault();
    });

    $('#aMainPicture').uploadify({
        'uploader':'/public_scripts/newcoder/uploadify/uploadify.swf',
        'script':'/public_scripts/newcoder/uploadify/uploadify_main.php',
        'folder':'/public_images/enc/'+$("input[name='id']").val(),
        'cancelImg':'/public_scripts/newcoder/uploadify/cancel.png',
        'buttonText':'',
        'buttonImg':'/images/standart/upload.png',
        'rollover':'true',
        'width':'94',
        'height':'26',
        'auto':true,
        //'fileDesc':'Изображения',
        //'fileExt':'.jpg;*.JPG;*.png;*.PNG;*.bmp;*.BMP',
        'scriptData':{
            'pare_id':$("input[name='id']").val()
        },
        'onComplete': function(event,queueID,fileObj,response,data) {
            $("#mImage").html(response);
            return true;
        }
    });

    $("a#edToggle").click(function(event) {
        $("div.editors").slideToggle();
        event.preventDefault();
    });
});
