j$(function() {
        DOM = {
link: j$('#link'),
progressbar: j$('#progressbar'),
rate: j$('#rate'),

status: j$('#status'),
msg: j$('#msg'),
err: j$('#err')
};

document.post.onsubmit = submitform;
j$('#submit').click(function() {
    document.post.onsubmit();
    });
});

var pe = null;
var count = 0;
var preserviceURL = "/generate_stream.yaws";
var serviceURL = "/upload_status.yaws";
var inProgress = false;
var retryLimit = 30;
var retryCount = 0;

function unloadHandler(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'A file transfer is currently in progress! '+
        'If you leave now, it will be cancelled and your file '+
        'will not be uploaded.';

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
};

function postjson(url,data,s) {
    j$.ajax({type:'POST',url:url,data:data,dataType:"json",success:s});
};

function open_links_in_new_window(bool){
    if(bool){
        j$('a').each(function(n,o) {
                if (typeof o.href != "undefined" &&
                    (typeof o.target == "undefined" |
                     o.target.length == 0)) {
                o.popupized = true;
                o.target = "_new";
                }
                });
    }else{
        j$('a').each(function(n,o) {
                if (typeof o.href != "undefined" &&
                    (typeof o.target != "undefined" |
                     o.target.length != 0)) {
                o.popupized = false;
                o.target = '_self';
                }
                });
    }
};

function submitform() {
    if (inProgress) {
        if (!confirm('An upload is in progress. Press OK to cancel it and start a new one.'));
        return false;
    }

    if (document.post.from_name.value == "Your name") {
        document.post.from_name.value = "";
    }
    if (document.post.from_email.value == "Additional message") {
        document.post.from_email.value = "";
    }


    if (document.getElementById("email")) {

        if (document.post.email.value.length == 0 ||
                document.post.email.title == document.post.email.value) {
            show_error("Please enter an email.");
            return false;
        }

        if (!document.post.email.value.match(
                    new RegExp('^(([a-zA-Z0-9])+([a-zA-Z0-9._\\-+])*@'+
                            '([a-zA-Z0-9])+((?:\\.|\\-)[a-zA-Z0-9]+)*\\.[a-zA-Z0-9]+\\,?( )*)+$','g'))) {
            show_error("Please enter a valid email.");
            return false;
        }
    }

    if ((document.post.from_email.value.length != 0) && 
            (!document.post.from_email.value.match(new RegExp('^Your.*','g')))  && 
            !document.post.from_email.value.match(
                new RegExp('^(([a-zA-Z0-9])+([a-zA-Z0-9._\\-+])*@'+
                        '([a-zA-Z0-9])+((?:\\.|\\-)[a-zA-Z0-9]+)*\\.[a-zA-Z0-9]+\\,?( )*)+$','g'))) {
        show_error("Please enter a valid email in optional box.");
        return false;
    }

    if (document.getElementById("terms")) {
        if (document.post.accept_terms.checked == false) {
            show_error("Please accept the terms.");
            return false;
        }	
    } 

    if (document.post.Filedata.value.length == 0) {
        show_error("Please choose a file.");
        return false;
    }

    // This should probably be replaced by JSON for better error handling.
    j$.ajax({
        cache: false,
        complete: function(xhr, status) {
            if (!(xhr.status == 200 && xhr.statusText == 'OK'))
                show_error("Oops, looks like there's a network issue. Check your "+
                "internet or try again soon. [Code 401]");
        },
        error: function(xhr, status, error) {
            show_error("Oops, looks like there's a network issue. Check your "+
            "internet or try again soon. [Code 402]");
        },
        success: function(data, status) {
            if (data.length < 10)
                show_error("Oops, looks like there's a network issue. Check your "+
                "internet or try again soon. [Code 403]");
            else {
                streamID = j$.trim(data);
                j$('#stream').val(streamID);

                document.post.submit();
                window.onbeforeunload = unloadHandler;

                // find all the input elements with title attributes
                j$('input[title!=""]').hint();

                open_links_in_new_window(true);

                DOM.progressbar.css('width', '0%');
                clearInterval(pe);
                pe=null;

                check_upload_status();

                setTimeout(function(){document.post.reset();},100);
            }
        },
        dataType: "text",
        data: {},
        url: preserviceURL
    });
    return false;
}

function check_upload_status() {
    if (pe == null) {
        DOM.progressbar.prev().text('Starting upload...');
        toggle_result();
        pe = setInterval(check_upload_status, 2000);
        return false;
    } else if (count == 30) {
        clearInterval(pe);
        pe = setInterval(check_upload_status, 5000);
    } else if (count == 60) {
        clearInterval(pe);
        pe = setInterval(check_upload_status, 15000);
    }
    count = count + 1;

    try {
        /*  JSON-RPC calls look like:
            To-server: {"id":"httpReq", "method":"get_status", "params":["2KkIZPrvFSCL51J1LQIXiqoyxAfgN"]}
            Response: {"result":"{state:'starting'}","id":"httpReq"}
            Where the thing in "params" is the stream ID
        */
        postjson(serviceURL,
                '{"id":"httpReq", "method":"get_status", "params":["'+streamID+'"]}',
                function(data, status) {
                eval('var upload = '+data.result+';');
                var active = ((upload.state == 'done') || (upload.state == 'uploading') || (upload.state == 'received'));
                var err = (upload.state == 'error');

                if (active) {
                DOM.link.html('This link was sent to '+upload.emails+' and exists for '+ upload.expire  +' hours and ' + upload.left + ' downloads.<br/> ' + upload.link);
                DOM.link.fadeIn();

                var width = parseFloat(100 * upload.received / upload.size)
                .toFixed(1)+'%';

                DOM.progressbar.css('width', width);
                DOM.progressbar.prev().text(width);

                if (upload.rate){
                DOM.rate.text('('+upload.rate+')');
                } else {
                //DOM.rate.text = '';
                }
                }
                else {
                    if(err && retryCount > 3)
                    {
                        DOM.link.html('Error: '+ upload.error_msg);
                        DOM.link.fadeIn();
                    }else if(err){
                        DOM.link.html('Please wait, connecting...');
                        DOM.link.fadeIn();
                    }
                }

                switch (upload.state) {
                    case 'starting':
                        break;
                    case 'error':
                        window.onbeforeunload = null;
                        fade_msg(' ');
                        DOM.rate.fadeOut();
                        open_links_in_new_window(false)

                        if(retryLimit == retryCount){
                            clearInterval(pe);
                        }else{
                            retryCount += 1;
                        }
                        break;
                    case 'done':
                        window.onbeforeunload = null;
                        //fade_msg(' ');
                        DOM.rate.fadeOut();
                        open_links_in_new_window(false)

                        clearInterval(pe);
                        break;
                    case 'nofile':
                        fade_msg('This file has expired or was never uploaded.');
                        clearInterval(pe);
                        break;
                    case 'received':
                        window.onbeforeunload = null;
                        clearInterval(pe);
                        DOM.rate.fadeOut();
                        open_links_in_new_window(false)
                        fade_msg('This file was successfully streamed and delivered.');
                        break;
                }
                });
    } 
    catch (e) {
        show_error(e);
    } 
    return false;
}

function toggle_result(hide) {
    var show = show || 0;
    if (show == 0) show = true;
    if (show) {
        try { DOM.status.fadeIn(); } catch(e) {}
        try { DOM.rate.fadeIn(); } catch(e) {}
        try { DOM.link.fadeIn(); } catch(e) {}
    }
    return false;
}

function fade_msg(msg) {
    // Faster than using innerHTML
    DOM.msg[0].childNodes[0].nodeValue = msg;
    DOM.msg.fadeIn();
}

var error_timeout = null;
function show_error(err, timeout) {
    var timeout = timeout || 4000;
    DOM.err.text(err).css('display','block');
    clearTimeout(error_timeout);
    if (timeout > 0) error_timeout = setTimeout(
            function(){DOM.err.text('').css('display','none')}, timeout);
}
