/* ЗАПОМНИ ЗАРЕЗЕРВИРОВАННЫЕ СЛОВА JS!!!!
 * А ТО ЭТА ***** С ИМЕНАМИ ОТНЯЛА У МЕНЯ ДЕНЬ ЛОПАЧИВАНИЯ КОДА!!!!
 * status
 * self
 *
 * В jQuery события вешаются не на сам input (при live), а на (контейнер_input)
 */

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') { //Array/Hashes/Objects
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

function merge_objects(objects) {
    var result = new Object();

    for(var i in objects) {
        for(var j in objects[i]) {
            result[j] = objects[i][j];
        }
    }

    return result;
}


function leading_zero(number, symbols) {
    if( symbols == null) symbols = 2;

    var output = ""+number+"";
    for(var i = output.length; i < symbols; i++) {
        output = "0"+output;
    }
    return output;
}




// OnLoad
$(document).ready(function() {
    var start = document.cookie.indexOf("PHPSESSID=");
    var end = document.cookie.indexOf(";", start); // First ; after start
    if(end == -1) end = document.cookie.length; // failed indexOf = -1
    var session_id = document.cookie.substring(start+10, end);

    // определение ширины полосы загрузки прогресс-бара
    var progress_bar_width = $("#upload_progress").css("background-position");
    if( progress_bar_width != null )
        progress_bar_width = Math.abs( /(-?\d+)px.*/i.exec(progress_bar_width)[1] );

    /*
     * в SWFUpload объект файл имеет следущие атрибуты (для примера был выбран файл "uibookII.pdf"):
		'id' => "SWFUpload_0_0"
		'name' => "uibookII.pdf"
		'filestatus' => "-1"
	    'post' ...
		'type' => ".pdf"
	    'creationdate' ...
		'index' => "0"
	    'modificationdate' ...
		'size' => "5733689"
     */

    $("#upload_from_pc_container")
    .swfupload({
        // настройка кнопки, по нажатию на которую происходит выбор файла (появл. диалог. окна)
        //button_image_url : '/tpl/swfupload/vendor/XPButtonUploadText_61x22.png',
        button_image_url : '/tpl/images_finfile/obzor.png',
        button_width : 75,
        button_height : 25,
        button_placeholder : $('#button')[0],

        // настройка допустимых файлов
        file_size_limit : 1024*1024*1024*4, // 4Гб
        file_types : "*.*",
        file_types_description : "All Files",
        file_upload_limit : "0",

        // не изменять. Параметры отправки файла, имена и прочее
        flash_url : "/tpl/swfupload/vendor/swfupload.swf",
        upload_url: "/upload.php",
        file_post_name: "upload_file",
        post_params: {
            'action'    : "upload",
            'uploader'  : "flash",
            'PHPSESSID' : session_id
        }
    })
    .bind('fileQueued', function(event, file) {
        $("#swfu_text").val(file.name);
    })
    .bind('uploadStart', function(event, file) {
        $.swfupload.getInstance("#upload_from_pc_container").addPostParam('file_desc', $('#file_desc').val())
        $.swfupload.getInstance("#upload_from_pc_container").addPostParam('file_cat', $('#file_cat').val())
    })
    .bind('uploadProgress', function(event, file, bytesLoaded) {
        var new_offset = parseInt( progress_bar_width*bytesLoaded/file.size );

        $("#upload_progress").css({
            "backgroundPosition": sprintf("%dpx 0px", new_offset-progress_bar_width )
        });

        $("#upload_progress_percents").text(sprintf("%.1f%%",99*bytesLoaded/file.size));
    })
    .bind("uploadSuccess", function(event, file, serverData) {
        serverData = eval( '(' + serverData + ')' );
        
        if( serverData.success == "1" ) {
            document.location.href = "/upload.php?action=update_page&file_id=" + serverData.file_id;
        //alert(serverData.file_id);
        } else {
            msg = "Ошибка! Файл не загружен. ";
            switch( parseInt(serverData.error) ) {
                case 1:
                case 2:
                    msg += "Выбранный Вами файл слишком большой.";
                    break;
                case 4:
                case 16:
                    msg += "Файл не был загружен.";
                    break;
                default:
                    msg += "Error " + serverData.error + ". Системная ошибка.";
                    break;
            }
            alert(msg);
        }
    //alert(dump(serverData));
    })
    ;

    // поле ввода URL для скачки
    var upload_from_url_text = $("#upload_from_url_field").val();
    $("#upload_from_url_field").focus(function() {
        if( $(this).val() == upload_from_url_text ) $(this).val("");
    }).blur(function() {
        if( $(this).val() == "" ) $(this).val(upload_from_url_text);
    });

    // инициализация автоматической установки "галочек" при редактировании загруженного файла
    $("textarea[name='file_description']").bind("keyup keydown keypress", function() {
        $("input[name='file_insert_description']").attr( "checked", ($(this).val() != "") );
        if( $(this).val() != "" ) {
            $("input[name='file_is_hidden']").attr( "checked", false );
        }
    });
    $("select[name='file_category_id']").change(function() {
        $("input[name='file_insert_to_cat']").attr( "checked", ($(this).val() != 1) );
        if( $(this).val() != 1 ) {
            $("input[name='file_is_hidden']").attr( "checked", false );
        }
    });

    $(".selectable").click(function() {
        $(this).select();
    });
});

var selected_upload_type = "pc";

function toggleUploadSrc(src) {
    switch( src ) {
        case "pc":
            $("#upload_from_pc_container").show();
            $("#upload_from_pc_default_container").hide();
            $("#upload_from_url_container").hide();
            //$("#upload_submit").hide();
            selected_upload_type = "pc";
            break;
        case "pc_default":
            $("#upload_from_pc_container").hide();
            $("#upload_from_pc_default_container").show();
            $("#upload_from_url_container").hide();
            //$("#upload_submit").show();
            selected_upload_type = "pc_default";
            break;
        case "url":
            $("#upload_from_pc_container").hide();
            $("#upload_from_pc_default_container").hide();
            $("#upload_from_url_container").show();
            //$("#upload_submit").show();
            selected_upload_type = "url";
            break;
    }
}



function upload_it() {
    switch( selected_upload_type ) {
        case "pc":
            if( $("#swfu_text").val() == "" ) {
                alert("Выберите файл");
            } else {
                $(".upload_progress_cont").show();
                $("#upload_submit").hide();
                $("#upload_from_pc_container").swfupload('startUpload');
            }
            break;
        case "pc_default":
        case "url":
            $('#form_upload').submit();
            break;
    }
}


// TODO: multiple popups incorrect: use _opened_popups and push 'name' into that.
var Popup = {
    _opened_popups: {},
    _z_index_max: 1000,
    _name_to_close_on_esc: "",

    _defaults: {
        width: "650px",
        height: "400px",
        overlay_opacity: 0.6,
        title: "",
        content: "",
        close_on_esc: true
    },


    hide: function() {
        selfObj = this;
        $("#popup_overlay_"+selfObj._name_to_close_on_esc).remove();
        $("#popup_container_"+selfObj._name_to_close_on_esc).remove();
    },


    show: function(name, params) {
        selfObj = this;

        if( this._opened_popups[name] != undefined ) {
            alert("Window " + name + " already opened!");
            return;
        }

        // установка свойств
        params = merge_objects([this._defaults, params]);

        // установка сокрытия popup при нажатии ESC
        if( params.close_on_esc ) {
            this._name_to_close_on_esc = name;
            $(document).keypress(function(e) {
                if( e.keyCode == 27 ) selfObj.hide();
            });
        }

        // отображение затемняющего фона
        var background = document.createElement("div");
        $(background)
        .attr("id","popup_overlay_"+name)
        .addClass("popup-overlay")
        .css({
            position: "absolute",
            opacity: params.overlay_opacity,
            zIndex: selfObj._z_index_max++,
            height: $(document).height(),
            width: $(document).width(),
            top: 0,
            left: 0
        })
        .appendTo("body")
        .show()
        ;

        // отображение самого окна
        var container = document.createElement("div");
        $(container)
        .attr("id","popup_container_"+name)
        .addClass("popup-container")
        .css({
            zIndex: selfObj._z_index_max++,
            position: "fixed",
            width: params.width,
            top: "50px",
            left: $(window).width()/2 - parseInt(params.width)/2  // TODO: will be a bug, when width is a %
        })
        ;

        // структура контейнера
        $(container).html('\
			<table style="width:100%;height:100%;">\
				<tr>\
					<td class="popup-title">'+params.title+'</td>\
					<td class="popup-closer"><a href="javascript:Popup.hide(\''+name+'\');" class="popup-closer-text">X</a></td>\
				</tr>\
				<tr><td colspan="2" class="popup-content-container"><div class="popup-content" style="height:'+params.height+';" id="popup_content"></div></td></tr>\
				<tr><td colspan="2" class="popup-bottom-bar" id="popup_bottom_bar">&nbsp;</td></tr>\
			</table>\
		');

        // присобачивание
        $(container)
        .appendTo("body")
        .show();


        // установка кнопок
        for( var i in params.buttons ) {
            var butt = document.createElement("a");
            $(butt)
            .attr("href","javascript:void(0);")
            .text(params.buttons[i].title)
            .addClass("popup-bar-button")
            .click(params.buttons[i].callback)
            ;

            $("#popup_bottom_bar").append(butt);
        }


        // установка содержимого
        $("#popup_content").html(params.content);

    }
}




function category_edit( cat_id ) {
    $.ajax({
        url: '/admin.php',
        data: {
            action: "get_form_category_edit",
            category_id: cat_id,
            rand: Math.random()
        },
        async: false,
        dataType : "html",
        cache: true,
        type: "get",
        complete: function(data,textStatus) {
            Popup.show( 'category', {
                title: "Редактирование категории",
                content: data.responseText,
                width: 500,
                buttons: {
                    "close": {
                        title: "Закрыть",
                        callback: function() {
                            Popup.hide('category');
                        }
                    }
                }
            });
        }
    });
}


function category_delete( cat_id ) {
    $.ajax({
        url: '/admin.php',
        data: {
            action: "get_form_category_delete",
            category_id: cat_id,
            rand: Math.random()
        },
        async: false,
        dataType : "html",
        cache: true,
        type: "get",
        complete: function(data,textStatus) {
            Popup.show( 'category', {
                title: "Удаление категории",
                content: data.responseText,
                width: 500,
                buttons: {
                    "close": {
                        title: "Закрыть",
                        callback: function() {
                            Popup.hide('category');
                        }
                    }
                }
            });
        }
    });
}

function reason_edit( reason_id ) {
    $.ajax({
        url: '/admin.php',
        data: {
            action: "get_form_reason_edit",
            reason_id: reason_id,
            rand: Math.random()
        },
        async: false,
        dataType : "html",
        cache: true,
        type: "get",
        complete: function(data,textStatus) {
            Popup.show( 'reason', {
                title: "Редактирование причины удаления",
                content: data.responseText,
                width: 500,
                buttons: {
                    "close": {
                        title: "Закрыть",
                        callback: function() {
                            Popup.hide('reason');
                        }
                    }
                }
            });
        }
    });
}


function reason_delete( reason_id ) {
    $.ajax({
        url: '/admin.php',
        data: {
            action: "get_form_reason_delete",
            reason_id: reason_id,
            rand: Math.random()
        },
        async: false,
        dataType : "html",
        cache: true,
        type: "get",
        complete: function(data,textStatus) {
            Popup.show( 'reason', {
                title: "Удаление причины удаления",
                content: data.responseText,
                width: 500,
                buttons: {
                    "close": {
                        title: "Закрыть",
                        callback: function() {
                            Popup.hide('reason');
                        }
                    }
                }
            });
        }
    });
}
