﻿token = "GG";

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.text.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.text.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.');
                            }
                        }, 0);
                    },
        error:      function(){
                        file.setError('There was an error uploading your file.');
                        $.post("/jserror?i="+token,{
                            'error': 'Problem uploading a url: '+file.fullname
                        });
                    }
    });
};

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.text.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;height:1px;width:1px;"></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");

    var handle = document.createElement("div");
    $(handle).addClass("handle");
	handle.style.height = "10px";
	
    this.open = new Control("open");
    this.docuSign = new Control('free esign');
	
    
    this.remove = new Control("remove");
    this.remove.addClickAction(function(){file.removeRow();});
    
    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");
    
    this.label = document.createElement("div");
    this.label.text = document.createElement("span");
    
    this.img = new Image();

    this.img.onload = function() {
        var src = this.src.substring(this.src.lastIndexOf("/")+1); 
        
        /*re = /.png$/i;
        if(re.exec(src))
        {
            $(file.img).IEPNGHack();
        }*/
        
        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).add(file.docuSign.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 = "/Google/images/widgets/throbber.gif";
    this.img.alt = "processing";
    
    $(this.label).addClass("label cell").append(this.img).append(this.label.text);
    $(this.label.text).append(this.filename);
    
    this.controls = document.createElement("div");
    $(this.controls).append(this.open.control).append(this.remove.control).addClass("controls cell");
    if(this.email) {
        $(this.controls).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&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)
        $(this.controls).append(this.sheets.control);
    $(this.controls).append(this.docuSign.control);

    this.error = document.createElement("div");
    $(this.error).addClass("error");

    $(this.row).append(handle).append(this.label).append(this.controls).append(this.error);
    $(container).append(this.row);
    
    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.text.innerHTML = file.filename = doc.getElementsByTagName("file")[0].firstChild.nodeValue;
                file.checkFile();
				$(obj).remove();
            } 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 = "/Google/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);
                                file.docuSign.addClickAction(function(){
                                    showDSSection();
                                    $('#dsExpress .submit')
                                        .unbind('click')
                                        .click(function() {
                                            urchinTracker('/LOOP/PostOffice');
                                            var $form = $('#dsExpress');
                                            if ($form.find('#dsSections'))
                                            {
                                                $form.find('#dsSections').remove();
                                            }
                                            var $sections = $('<div id="dsSections"></div>');
                                            $sections
                                                .append(
                                                    $('<input type="hidden" name="Section_1"/>')
                                                        .attr('value', '/files/' + file.filename + '/PDF')
                                                )
                                                .append(
                                                    $('<input type="hidden" name="filename"/>')
                                                        .attr('value', file.filename)
                                                );
                                            $form.append($sections);
                                        });
                                    $('#senderEmail').focus();
                                });                           
                                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 = "/Google/images/widgets/error.gif";
    this.img.alt = error;

    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;
}
