﻿token = "LOOP";

function select_all(obj) {
    $(obj).parent().parent().find('input[type=checkbox]').attr("checked",$(obj).is(":checked"));
};

function check_callback() {
    var file = this;
    if(file.sheets)
        $(file.sheets.control).unbind('click').bind('click', function(){
            urchinTracker('/LOOP/PickSheets');
            var url = "/files/"+encodeURIComponent(file.filename)+"/sheets?i="+token+"&nocache="+(new Date()).getTime();
            $text = $('<div></div>')
                .append('<p>Pick your excel sheets</p>')
                .append('<label for="check_all_box"><input type="checkbox" id="check_all_box" onclick="select_all(this);" /> Select All</label><br />');
            $.get(url, function(data){
                var tags = data.getElementsByTagName("sheet");
                for(var i = 0; i < tags.length; i++) {
                    var sheet = tags[i].firstChild.nodeValue;
                    $text
                        .append(
                            $('<label></label>')
                                .attr('for', '_'+sheet)
                                .append(
                                    $('<input type="checkbox" />')
                                        .attr('id', '_'+sheet)
                                        .attr('value', sheet)
                                )
                                .append(sheet)
                        )
                        .append('<br />');
                }
                var prompt = Prompt({
                    question:   $text.html(),
                    title:      'Excel Sheets',
                    width:      '350px',
                    textbox:    false,
                    pass:       '$(obj).find("input[type=checkbox]:checked")'
                }, function(checked){
                    file.setStatus("updating...");
                    file.img.src = "/images/widgets/throbber.gif";
                    file.img.alt = "processing";
                    var sheet_list = {};
                    var x = 1;
                    checked.each(function(){
                        if(this.id != 'check_all_box') {
                            sheet_list['sheet_'+x] = this.value;
                            x++;
                        }
                    });
                    $.post(url, sheet_list, function(){
                        file.checkFile();
                    });
                });
            });
        });
};

function file_change() {
    if(this.value != "") {
       var f = new File(this.value, this);
        f.createRow(document.getElementById("file_group"));
        f.checkCallback = check_callback;
        $(f.row).bind('click', select);
        f.post();
        
        $("div#add_file").prepend('<input size="1" class="file" type="file" />').find("input[type=file]");
        $("input[type=file]").bind("change", file_change);
    }
};

function select() {
    $("div.row").removeClass("selected");
    $(this).addClass("selected");
};

$(document).ready(function(){
    $("input[type=file]").bind("change",file_change);
    
    $("div#move_up").bind('click', function(){
        var div = $("div.selected").get(0);
        $(div).prev().before(div);
    });
    
    $("div#move_down").bind('click', function(){
        var div = $("div.selected").get(0);
        $(div).next().after(div);
    });
    
    $("input#combine_all").bind("click", combineAll);

    $("input#filename").bind('keypress', function(event){
        if(event.keyCode == 13) {
            $("input#combine_all").get(0).click();
            return false;
        }
            
    });
    
    $("div#file_group").sortable({
        axis:           'y',
        cancel:         'div.text-link',
        containment:    'parent',
        placeholder:    'row sorthelper',
        handle:         'div.handle'
    });
    
    $.get("/files?xml=true&i="+token+"&nocache="+(new Date()).getTime(), function(data) {
        var elements = data.getElementsByTagName('file');
        for(var i = 0; i < elements.length; i++) {
            var f = new File(elements[i].firstChild.nodeValue);
            f.createRow(document.getElementById("file_group"));
            f.checkCallback = check_callback;
            $(f.row).bind('click', select);
            f.checkFile();
        }
    });
    
    $('#add_url').bind('click', function(){
        Prompt({
            question:   'Paste or type the URL below.',
            title:      'Add URL',
            label:      'URL',
            width:      '350px'
        }, function(url){
            if(url != "") {
                urchinTracker('/LOOP/AddUrl');
                var f = new File(url);
                f.createRow(document.getElementById('file_group'));
                $(f.row).bind('click', select);
                f.checkCallback = function(){};
                f.postURL();
            }
        });
    });
    
    $('#dsInfo').dialog({
            'autoOpen':   false,
            'resizable':  false,
            'modal':      true,
            'overlay':    {
                            opacity:    0.3,
                            background: 'black'
                        },
            'height':     440,
            'width':      680,
            'title':      'About DocuSign Express'

    });
       
    $('.dsInfo').click(function() {
        $('#dsInfo').dialog('open');
    }); 
        
    $('#dsDiv')
        .dialog({
            'autoOpen':   false,
            'resizable':  false,
            'modal':      true,
            'overlay':    {
                            opacity:    0.3,
                            background: 'black'
                        },
            'height':     576,
            'width':      680,
            'title':      'Email through DocuSign',
            'buttons':    {
                            "submit":     function() {
                                
                            },
                            "cancel": function() {
                                        $('#dsDiv').dialog('close');
                                    }
                        }
        })        
        .closest('.ui-dialog').find('.ui-dialog-buttonpane').height(40);
        
    if ($.browser.msie)
    {
        $('#dsDiv').dialog('option', 'height', 591);
    }
    
    $('#docuSignBtn').click(function(){
        if (!allowCombine())  {
            alert('You need at least 1 successfully converted PDF to submit for e-signature.');
        } else {    
            var filename = $('#filename').val();
            if (!filename)
            {
                filename = 'File.pdf';
            }
            else if (filename.substring(filename.length - 4) != '.pdf')
            {
                filename += '.pdf';
            }
            $('#dsFrm').show();
            $('#dsDiv')
                .closest('.ui-dialog')
                    .find('.ui-dialog-buttonpane')
                        .show()
                .end()
                    .find('.dsResults')
                        .hide()
                .end()
            .end()
                .dialog('option', 'title', 
                    $('<div>Send through DocuSign - </div>')
                        .append($('<a href="javascript:;">' + filename + '</a>')
                            .bind('click', combineAll)
                        )
                )
                .dialog('open')
                .dialog('option', 'buttons', {
                    'submit': function(){
                            urchinTracker('/LOOP/PostOfficeCombined');
                            var $form = $('#dsFrm');
                            var url = "/ddps/148?nocache=" + (new Date()).getTime();
                            if ($form.find('#dsSections'))
                            {
                                $form.find('#dsSections').remove();
                            }                        
                            var $sections = $('<div id="dsSections"></div>');
                            var i = 1;
                            $("div#file_group div.row").each(function(){
                                if (this.owner.status && this.owner.status == 'ok')
                                {
                                    $sections.append(
                                        $('<input type="hidden" name="Section_' + i + '"/>')
                                            .attr('value', '/files/' + this.owner.filename + '/PDF')
                                    );
                                    //url += "&Section_"+i+"=/files/"+encodeURIComponent(this.owner.filename)+"/PDF";
                                    i++;
                                }
                            });
                            $sections.append(
                                $('<input type="hidden" name="filename"/>')
                                    .attr('value', filename)
                            );
                            $form.append($sections).submit();
                            $sections.remove();
                    },
                    'cancel': function() {
                                $('#dsDiv').dialog('close');
                    }
                });
            $('#senderEmail').focus();
        }
    });
    
    $('.dsClose').click(function() {
        $('#dsDiv').dialog('close')
    });
    
    $('#dsFrm').submit(function() {
        var isValid = document.getElementById('dsTerms').checked;
        if (isValid)
        {
            $(this).find(':input[validation]').each(function() {
                var re = new RegExp(this.getAttribute('validation'), 'i');
                if (!this.value.match(re))
                {
                    isValid = false;
                }
            });
        }
        if (isValid)
        {
            var offset = $('#dsDiv').closest('.ui-dialog');
            // hide error message and dialog buttons
            $('#errors_on_page').add($('#dsDiv').closest('.ui-dialog').find('.ui-dialog-buttonpane')).hide();
            // add overlay (abuse.js hsubmit)
            if($.browser.msie){
                $("#dsFrm *").css({
                    "filter":       "alpha(opacity=30)",
                    "-moz-opacity": "0.3"
                });
            }
            else
            {
                $("#dsFrm *").css({
                    "opacity":      ".30",
                    "-moz-opacity": "0.3"
                });
            }
            $("select").css("visibility", "hidden");
            $("#form_loading_img").prependTo('#dsFrm').find("img").remove().end().show().prepend('<img src="/images/widgets/throbber.gif" alt="processing" />');
            window.scrollTo(offset.left, offset.top);
            $('#downloader').unbind('load').bind('load', function() {
                var doc = this.contentDocument || window.frames['downloader'].document;
                setTimeout(function(){
                    if (window.dsSubmitHandle)
                    {
                        dsSubmitHandle();
                    }
                    else
                    {
                        var response = (doc.body.innerHTML ? doc.body.innerHTML.substring(0,7).toLowerCase() : undefined);
                        
                        if (response == 'success')
                        {
                            $('#dsSuccess').show();
                            $('#dsFrm, #dsError, #dsUpgrade').hide();
                        }
                        else if (response == 'upgrade')
                        {
                            $('#dsUpgrade').show();
                            $('#dsFrm, #dsSuccess, #dsError').hide();
                        }
                        else
                        {
                            $('#dsError').show();
                            $('#dsFrm, #dsSuccess, #dsUpgrade').hide();
                        }
                        if($.browser.msie){
                            $("#dsFrm *").css({
                                "filter":       "alpha(opacity=100)",
                                "-moz-opacity": "1"
                            });
                        }
                        else
                        {
                            $("#dsFrm *").css({
                                "opacity":      "1",
                                "-moz-opacity": "1"
                            });
                        }
                        $("select").css("visibility", "visible");
                        $("#form_loading_img").hide();
                    }
                }, 0);                
            });
            return true;
        }
        else
        {
            $('#errors_on_page').show();
            return false;
        }
    });
    
    $('#addRecipient').click(function(){
        var rNum = $('#dsRecipients .recipient').length + 1;
        var $dlg = $(this).closest('.ui-dialog');
        var $section = $('<div class="recipient"></div>')
            .append('<div class="remove"><a href="javascript:;"><img src="/graphics/icons/cross.gif" alt="remove" /></a></div>')
            .append(
                $('<div class="section"></div>')
                    .append('<div class="item"><span class="label"><label>email</label></span><input type="edit" class="email" id="rEmail' + rNum + '" name="rEmail' + rNum + '" /></div>')
                    .append('<div class="item"><span class="label"><label>name</label></span><input type="edit" class="name" id="rName' + rNum + '" name="rName' + rNum + '" /></div>')
            )
            .append(
                $('<div class="section"></div>')
                    .append('<span class="label"><label>note</label></span><textarea class="note" id="rNote' + rNum + '" name="rNote' + rNum + '"></textarea>')
            )
            .mouseover(function(){
                $(this).find('.remove').show();
            })
            .mouseout(function(){
                 $(this).find('.remove').hide();
            });
        $section
            .find('.remove a')
                .click(function(){
                    $dlg.height($dlg.height() - $section.height());
                    $section.remove();
                    if ($('.recipient').length < 3)
                    {
                        $('#addRecipient').show();
                    };
                });
        $('#dsRecipients').append($section);
        if ($('.recipient').length >= 3)
        {
            $(this).hide();        
        };
        $dlg.height($dlg.height() + $section.height());
        return false;
    });
    
    $('div#sf_docs').dialog({
        modal:      true,
        overlay:    {
                        opacity:    0.3,
                        background: "black"
                    },
        autoOpen:   false
    });
    
   $("#add_file").hover(function(){
        $(this).find(".button").css("background-position", "0px -24px");
    },function(){
        $(this).find(".button").css("background-position", "0px 0px");
    });
    $("#move_up").hover(function(){
        $(this).find(".button").css("background-position", "-83px -23px");
    },function(){
        $(this).find(".button").css("background-position", "-83px 0px");
    });
    $("#move_down").hover(function(){
        $(this).find(".button").css("background-position", "-59px -23px");
    },function(){
        $(this).find(".button").css("background-position", "-59px 0px");
    });
    $("#add_url").hover(function(){
        $(this).find("div").css("background-position", "-30px -23px");
    },function(){
        $(this).find("div").css("background-position", "-30px 0px");
    });
    $("#advanced").hover(function(){
        $(this).find(".button").css("background-position", "-108px -23px");
    },function(){
        $(this).find(".button").css("background-position", "-108px 0px");
    });
    $("#sf_docs_trigger").hover(function(){
        $(this).find(".button").css("background-position", "-130px -24px");
    },function(){
        $(this).find(".button").css("background-position", "-130px 0px");
    });
});

function combineAll(urlEnd){
    urchinTracker('/LOOP/CombineDownload');

    var formID  = "_"+Math.round((Math.random()*100000));
    var $form = $('<form id="'+formID+'" method="post"></form>')
    var i = 1;
    $("div#file_group div.row").each(function(){
        if (this.owner.status && this.owner.status == 'ok')
        {
            $form.append(
                $('<input type="hidden" name="Section_' + i + '"/>')
                    .attr('value', '/files/' + this.owner.filename + '/PDF')
            );
            //url += "&Section_"+i+"=/files/"+encodeURIComponent(this.owner.filename)+"/PDF";
            i++;
        }
    });
    
    var url = "/ddps/loop?i=" + token + "&nocache="+(new Date()).getTime();
    var filename = document.getElementById("filename").value;
    if(filename != "")
        url += "&filename="+encodeURIComponent(filename);
    
    if(urlEnd && typeof(urlEnd) == "string") {
        url += urlEnd;
    }
    
    $('body').append($form);
    $form.attr('action', url).attr('target', 'downloader').submit().remove();
    //document.getElementById("downloader").src = url;
};

function allowCombine() {
    var $rows = $("div#file_set div.row");
    for (var i = 0; i < $rows.length; i++)
    {
        // allow if user has a successfully converted pdf
        if ($rows[i].owner.status == 'ok')
        {
            return true;
        }
    }
    return false;
};
