﻿token = "LOOP";
errorUrl = "Bad Url";

function Control(label) {
    this.control = document.createElement("div");
    this.control.innerHTML = label;
    $(this.control).addClass("pointer").addClass("text-link").addClass("control");
};

Control.prototype.addClickAction = function(func) {
    if(this.control.attachEvent)
        this.control.attachEvent('onclick', func);
    else
        this.control.onclick = func;
};

function File(name, input) {
    this.input = input || null;
    this.fullname = name;
    this.filename = (this.fullname.indexOf("/") >= 0 ? this.fullname.substring(this.fullname.lastIndexOf("/")+1) : this.fullname);
    this.filename = (this.fullname.indexOf("\\") >= 0 ? this.fullname.substring(this.fullname.lastIndexOf("\\")+1) : this.fullname);
};

File.prototype.postURL = function() {
    var file = this;
	
    var name = validateUrl(file.filename);
    var index = name.indexOf('#');
    if (index > -1)
        name = name.substring(0, index);
    file.filename = name;
    file.fullname = name;
    file.label.textContent = name;

    $.ajax({
        type:       "POST",
        url:        "/files?xml=true&i="+token,
        data:       {URL_1: file.fullname},
        complete:   function(req){
                        var data = req.responseXML;
                        setTimeout(function(){
                            try {
                                file.label.innerHTML = file.filename = data.getElementsByTagName("file")[0].firstChild.nodeValue;
                                file.checkFile();
                            } catch(e) {
                                $.post("/jserror?i="+token,{
                                    'error':    "Problem with postURL\n\n"+e.message+"\n\nfile: "+file.fullname
                                });
                                file.setError('There was an error uploading your file.');
                                file.filename = errorUrl;
                            }
                        }, 0);
                    },
        error:      function(){
                        file.setError('There was an error uploading your file.');
                        $.post("/jserror?i="+token,{
                            'error': 'Problem uploading a url: '+file.fullname
                        });
                        file.filename = errorUrl;
                    }
    });
};

File.prototype.postSF = function() {
    var file = this;
    $.ajax({
        url:        "/files?xml=true&i="+token,
        type:       "POST",
        data:       {SF_1:this.sfid},
        complete:   function(req){
                        var data = req.responseXML;
                        setTimeout(function(){
                            try {
                                file.label.innerHTML = file.filename = data.getElementsByTagName("file")[0].firstChild.nodeValue;
                                file.checkFile();
                            } catch(e) {
                                $.post("/jserror?i="+token,{
                                    'error':    "Problem with postSF\n\n"+e.message+"\n\nfile: "+file.fullname
                                });
                                file.setError('There was an error uploading your file.');
                            }
                        }, 0);
                    },
        error:      function(){
                        file.setError('There was an error uploading your file.');
                        $.post("/jserror?i="+token,{
                            'error': 'SF Upload Error with: '+file.sfid+"\n\nfile: "+file.fullname
                        });
                    }
    });
};

File.prototype.post = function() {
    if(this.label && this.input) {
        var inputID = "_"+Math.round((Math.random()*100000));
        var formID  = "_"+Math.round((Math.random()*100000));
        var frameID = "_"+Math.round((Math.random()*100000));

        this.input.id = this.input.name = inputID;

        $(this.label)
            .append('<form name="'+formID+'" id="'+formID+'" action="/files?xml=true&i='+token+'" method="POST" enctype="multipart/form-data" target="'+frameID+'"></form>')
            .append('<iframe id="'+frameID+'" name="'+frameID+'" src="/blank.html" frameborder="0" style="border:0;"></iframe>');

        var form = document.getElementById(formID);
        var frame = document.getElementById(frameID);
        
        $(form).append(this.input).addClass("invisible");
        $(frame).addClass("invisible");
        
        var file = this;

        var func = function() { file.updateFile(frame) };

        if(frame.attachEvent)
            frame.attachEvent('onload', func);
        else
            frame.onload = func;

        form.submit();
    }
};

File.prototype.createRow = function(container) {
    var file = this;
    
    this.row = document.createElement("div");

    this.row.owner = this;
    $(this.row).addClass("row");
    
    this.open = new Control("open");
    this.remove = new Control("remove");
    
    try {
        if(sflogin)
            this.email = new Control("email");
    } catch(e) {}
    
    var re = /.xlsx?$/i;
    
    if(re.exec(this.filename))
        this.sheets = new Control("pick sheets");
    
    var handle = document.createElement("div");
    var c1 = document.createElement("div");
    this.label = document.createElement("div");
    var c3 = document.createElement("div");
    this.error = document.createElement("div");
    
    this.img = new Image();
    
    $(this.row).append(handle).append(c1).append(this.label).append(c3).append('<div style="clear: both;"></div>');//.append(this.error);
    $(container).append(this.row);

    $(handle).addClass("handle").append("&nbsp;");
    $(c1).append(this.img).addClass("status").addClass("cell").append(this.error);
    $(this.label).addClass("label").html(this.filename).addClass("cell");
    $(c3).append(this.open.control).append(this.remove.control).addClass("controls").addClass("cell");
    
    if(this.email) {
        $(c3).append(this.email.control);
        $(this.email.control).bind('click', function(){
            $("div#page_throbber, div#toolbar, div#file_set").toggle();
            urchinTracker('/LOOP/UploadSFEmailSingle');
            var url = "/ddps/loop?i="+token+"&sfemail=true";
            url += "&Section_1=/files/"+encodeURIComponent(file.filename)+"/PDF&filename="+encodeURIComponent(file.filename);

            $.get(url, function(data){
                window.parent.location.href = decodeURIComponent(data.getElementsByTagName("location")[0].firstChild.nodeValue);
            });
        });
    }
    if(this.sheets)
        $(c3).append(this.sheets.control);

    $(this.error).addClass("error");
    
    this.remove.addClickAction(function() { file.removeRow(); });
    
    this.img.onload = function() {
        var src = this.src.substring(this.src.lastIndexOf("/")+1);
        switch(src.toLowerCase()) {
            case 'throbber.gif':
                $(file.row).find('.controls').hide();
                break;
            case 'download.gif':
                $(file.row).find('.controls').show();
                break;
            case 'error.gif':
                $(file.row).find('.controls').show();
                $(file.open.control).css('visibility', 'hidden');
                if(file.email)
                    $(file.email.control).css('visibility', 'hidden');
                if(file.sheets)
                    $(file.sheets.control).css('visibility', 'hidden');
                break;
        }
    };
    this.img.src = "/images/widgets/throbber.gif";
    this.img.alt = "processing";
    
    this.setStatus("uploading...");
};

File.prototype.updateFile = function(obj) {
    try {
        var doc = window.frames[obj.id].document.XMLDocument || obj.contentDocument;
        var file = this;
        setTimeout(function(){
            try {
                file.label.innerHTML = file.filename = doc.getElementsByTagName("file")[0].firstChild.nodeValue;
                file.checkFile();
            } catch(e) {
                $.post("/jserror?i="+token,{
                    'error':    "Problem with updateFile (inside setTimeout)\n\n"+e.message+"\n\nfile: "+file.fullname
                });
                file.setError('There was an error uploading your file.');
            }
        }, 0);
    } catch(e) {
        $.post("/jserror?i="+token,{
            'error':    "Problem with updateFile (outside setTimeout)\n\n"+e.message+"\n\nfile: "+this.fullname
        });
        this.setError('There was an error uploading your file.');
    }
};

File.prototype.checkFile = function() {
    this.setStatus("converting...");
    var url = "/files/"+encodeURIComponent(this.filename)+"/status?i="+token+"&nocache="+(new Date()).getTime();
    var file = this;
    
    $.ajax({
        'url':      url,
        complete: function(req){
                        var data = req.responseXML;
                        try {
                            var message = data.getElementsByTagName("message")[0].firstChild.nodeValue;

                            if(message == "Completed.") {
                                file.status = "ok";
                                file.img.src = "/images/widgets/download.gif";
                                file.img.alt = "download";
                                $(file.img).addClass("pointer");
                                var dlfunc = function(){
                                    urchinTracker('/LOOP/Open');
                                    document.getElementById("downloader").src = "/files/"+encodeURIComponent(file.filename)+"/PDF?i="+token;
                                };
                                    
                                if(file.img.attachEvent)
                                    file.img.attachEvent('onclick', dlfunc);
                                else
                                    file.img.onclick = dlfunc;
                                    
                                file.open.addClickAction(dlfunc);
                                
                                pdf = file.filename;
                                if(pdf.slice(-4).toLowerCase() != ".pdf")
                                    pdf += ".pdf";
                                
                                file.setStatus("");
                            } else {
                                file.setError(message);
                            }
                        } catch(e) {
                            $.post("/jserror?i="+token,{
                                'error':    "Problem with checkFile\n\n"+e.message+"\n\n"+data+"\n\nfile: "+file.fullname
                            });
                            file.setError('There was an error uploading your file.');
                        }
                    },
        error:    function(){
                        file.setError('There was an error uploading your file.');
                        $.post("/jserror?i="+token,{
                            'error': 'Problem with getting the status at '+url+"\n\nfile: "+file.fullname
                        });
                    }
    });
    if(this.checkCallback)
        this.checkCallback();
};

File.prototype.removeRow = function() {
    $(this.row).remove();
    $.ajax({
        'type': 'DELETE',
        'url':  "/files/"+encodeURIComponent(this.filename)+"/?xml=true&i="+token
    });
    if(this.removeCallback)
        this.removeCallback();
};

File.prototype.setError = function(error) {
    urchinTracker('/LOOP/UploadError');
    this.img.src = "/images/widgets/error.gif";
    this.img.alt = error;
    $(this.img).addClass("pointer");

    this.setStatus(error);
};

File.prototype.setStatus = function(text) {
    $(this.error).html(text);
};

function validateUrl(url)
{
    var regex = "^((http[s]?:)(/)?(/)?)?(.*)$";
    matches = url.match(regex);
    if (matches[1])
    {
        if(matches[2])
        {
            if(!matches[3] || !matches[4])
            {
                url = matches[2] + "//" + matches[5];
            }
        }
        else
            url = "http://" + matches[5]; 
    }
    return url;
}

