var disable_div, chform_div;
var attach_error = new Array();
attach_error["limit"] = "You've already reached the maximum number of attached files!";
attach_error["bigfile"] = "File is too big!";
attach_error["nofile"] = "File is empty or too big!";

$(document).ready(function(){
    initCommon();

    $("div[@rel=disable]").each(function(){ disable_div = $(this);});
    $("div[@rel=chform]").each(function(){ chform_div = $(this);});
    $("input:file").change(function(){
        $("#attach_add").click();
    });
    // Set up target, check attachments
    $("input:submit").click(function(){
        $(this).attr('disabled', true);
        attach = "";
        $("form").attr("action", "/send");
        $("form").attr("target", "");

        if ($("input:file").attr('value')!=undefined)
            attach = $("input:file").attr('value');
        // If user choose file but not attach it
        if (attach!=""){
            
            $("#attach_input").remove();
            $("#send").submit();
            return true;
        }

        $("#send").submit();
        return true;

    });
    
    // Add new attachment functional
//    $("#attach_add").click(function(){
    $("input:file").change(function(){
        attachfile();
        clearff();
    });
    // Attach file that are already attached
    $("input", $("#javascriptdata")).each(function(){
        addAttachedFile($(this).attr('name'), $(this).attr('size'));
    });
});

function attachfile(){
    if (($("input:file").attr('value') == undefined) || ($("input:file").attr('value') == "")){
            alert('You should select file first.');
            return;
        }
        // Upload file using AJAX
        $("form").attr("action", "/attach");
        disablepage();
        $.ajaxUpload({
            'url': '/attach',
            secureuri: false,
            uploadform: $("form"),
            dataType: 'xml',
            success: function(data, status){
                        enablepage();
                        var error =0;
                        $("error", data).each(function(){
                            addon='';
                            if ($(this).attr('code') == 'bigfile')
                                addon=" (size: "+$(this).attr('size')+" bytes)";
                            alert(attach_error[$(this).attr('code')]+addon);
                            error = 1;
                        });
                        if (!error){
                            filename = $("file", data).attr('name');
                            filesize = $("file", data).attr('filesize');
                            addAttachedFile(filename, filesize);
                        }
                     },
            error:   function (data, status, e){
                        alert('error occurs:('+e);
                     }
        });
}

var afiles = new Array();
// Function adds attached file and draw file table
function addAttachedFile(filename, filesize){
    n = afiles.length;
    afiles[n] = {
        filename: filename,
        filesize: filesize
    };    
    // draw table
    drawAttachTable();
    
}
function drawAttachTable(){
    ret = "<table ><tr><td style=\"border:1px solid #aaa\"><strong>File name:</strong></td><td style=\"border:1px solid #aaa\"><strong>File size (bytes)</strong></td><td></td></tr>";
    for (i=0; i<afiles.length; i++){
        ret+= "<tr><td style=\"border:1px solid #aaa\">"+afiles[i].filename+"</td><td style=\"border:1px solid #aaa\">"+afiles[i].filesize+"</td><td>[<a onclick=\"removeAttachedFile("+i+")\">remove</a>]</td></tr>";
    }
    ret += "</table>";
    n = afiles.length;
    if (n==0) n = "0";
    $("span[@rel=number]", $("#attach_total")).html(n);
    if (afiles.length == 0) ret = "";
    
    $("#attach_info").html(ret);
     
}
function removeAttachedFile(n){
    $.post(
        "/attach",
        {
            remove:"yes",
            n: n
        },
        function(){
            afiles.splice(n, 1);
            drawAttachTable();
        }
    );
}

// function disables page and shows editing window 
function disablepage(){
    //$("div[@rel=all]").css("
    disable_div.css("display", "block").css("height", getDocumentHeight()).css("width", "100%");
    chform_div.css("display", "block").css("top", getBodyScrollTop()+200);

    
    
}
// function enables page
function enablepage(){
    disable_div.css("display", "none");
    chform_div.css("display", "none");
}

// Document's height
function getDocumentHeight()
{
    return (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}

// Document's width
function getDocumentWidth()
{
    return (document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
}
// Returns position of the left scroller 
function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}
// Returns position of the bottom scroller
function getBodyScrollLeft()
{
  return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}
function clearff(){
    $("#ff").empty();
    $("#ff").html("<input type=\"file\" name=\"attachment\" onchange=\"attachfile(); clearff();\" />");
    
}
