﻿token = "GG";

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();
            var text = '<div style="overflow:auto;height:116px;"><p>Pick your excel sheets</p>';
            text += '<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 += '<label for="_'+sheet+'"><input type="checkbox" id="_'+sheet+'" value="'+sheet+'" /> '+sheet+'</label><br />';
                }
                text += '</div>';
                var width = $('#documents').parent().parent().width()-50;
                Prompt({
                    question:   text,
                    title:      'Excel Sheets',
                    width:      (width > 230 ? 230 : width) + 'px',
                    textbox:    false,
                    pass:       '$(obj).find("input[type=checkbox]:checked")'
                }, function(checked){
                    file.setStatus("updating...");
                    file.img.src = "/Google/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("documents"));
        f.checkCallback = check_callback;
        //$(f.row).bind('click', select);
        f.post();
        //$("#documents").SortableAddItem(f.row);
        
        $("#add_file").prepend('<input size="1" class="file" type="file" />').find("input[type=file]");
        $("input[type=file]").bind("change", file_change);
    }
};

function select() {
  /*  $("li").removeClass("selected");
    $(this).addClass("selected");*/
};

function validateAll(id) {
    var isValid = true;
    $('#' + id).find(':input[validation]').each(function() {
        var re = new RegExp(this.getAttribute('validation'), 'i');
        if (!this.value.match(re))
        {
            isValid = false;
            $('#errors_on_page').show();
        }
    });
    if (isValid) 
    {
        $('#errors_on_page').hide();
    }
    return isValid;
};

function validateSections($tabs, startIndex, endIndex) {
    var panels = $tabs.data('tabs.ui').panels;
    var selectedIndex = $tabs.tabs('option', 'selected');
    var isValid;
    if (endIndex == undefined)
    {
        endIndex = panels.length - 1;
    }
    for (var i = startIndex; i <= endIndex; i++)
    {
        isValid = validateAll(panels[i].id);
        if (!isValid)
        {
            if (selectedIndex != i)
            {
                $tabs.tabs('select', i);
            }
            return false;
        }
    }
    return true;
};

function allowCombine() {
    var $rows = $("#documents 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;
};

function showLoopSection() {
    $('#dsExpress').tabs('select', 0).hide();
    $('#loop').show();
    window.onresize();    
};

function showDSSection() {
    $('#loop').hide();
    $('#dsExpress').show()
    window.onresize();    
};

$(function(){
    $("input[type=file]").bind("change", file_change);
    
    $("#filename").bind('keypress', function(event){
        if(event.keyCode == 13)
            $("#combine_tool").click();
    });
    
    $('#documents').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('documents'));
            f.checkCallback = check_callback;
            $(f.row).bind('click', select);
            f.checkFile();
            //$('#documents').SortableAddItem(f.row);
        }
    });

    //$('body').prepend($('.jqmWindow'));
    
    $('#add_url').bind('click', function(){
        var width = $('#documents').parent().parent().width()-50;
        Prompt({
            question:   'Paste or type the URL below.',
            title:      'Add URL',
            label:      'URL',
            width:      (width > 230 ? 230 : width) + 'px',
            height:     ($.browser.msie && $.browser.version <= 6 ? 250 : 'auto')
        }, function(url){
            if(url != "") {
                //urchinTracker('/LOOP/AddUrl');
                var f = new File(url);
                f.createRow(document.getElementById('documents'));
                $(f.row).bind('click', select);
                //f.checkCallback = function(){};
                f.postURL();
                //$("#documents").SortableAddItem(f.row);
            }
        });
    });
    
    $('#advanced').bind('click', function(){
       window.open('/loop/order', '_blank'); 
    });
    
    $('#combine_tool').bind('click', function(){
        //urchinTracker('/LOOP/CombineDownload');
        
        var formID  = "_"+Math.round((Math.random()*100000));
        $('body').append('<form id="'+formID+'" method="post"></form>')
        var form = $('#'+formID);
        
        var url = "/ddps/loop?i="+token;
        $('#documents .row').each(function(i){
            if (this.owner.status == 'ok')
            {
                form.append('<input type="hidden" name="Section_'+(i+1)+'" value="/files/'+this.owner.filename.replace(/"/, '&quot;')+'/PDF" />');
                //url += "&"+"Section_"+(i+1)+"=/files/"+encodeURIComponent(this.owner.filename)+"/PDF";
            }
        });

        url += "&nocache="+(new Date()).getTime();

        var filename = document.getElementById("filename").value;
        if(filename != "")
            url += "&filename="+encodeURIComponent(filename);
        
        form.attr('action', url).attr('target', 'downloader').submit().remove();
        
        //document.getElementById("downloader").src = url;
    });
    
    $('.jqInfo').each(function(){
        var info = this;
        $(info).dialog({
            resizable:  false,
            modal:      true,
            overlay:    {
                            opacity:    0.3,
                            background: "black"
                        },
            autoOpen:   false
        });
        $('.help[field="' + info.getAttribute('field') + '"]').click(function(){
            $(info).dialog('open');
        });
    });
    
    $dsSection = $('#dsExpress').tabs({
        select: function(event, ui) {
            var prevIndex = $dsSection.find('.ui-tabs-panel').index($('.ui-tabs-panel:visible'));
            var isValid = true;
            if (prevIndex > -1 && prevIndex < ui.index)
            {
                isValid = validateSections($dsSection, prevIndex, ui.index - 1);
            }
            if (isValid)
            {
                $('.tabs a').removeClass('selected');
                $(ui.tab).addClass('selected');                            
            }
            return isValid;
        }
    });
    
    $('#docuSignBtn').click(function() {
        if (!allowCombine())  {
            alert('You need at least 1 successfully converted PDF to submit for e-signature.');
        } else {
            showDSSection();
            $('#dsExpress .submit')
                .unbind('click')
                .click(function(){
                    urchinTracker('/LOOP/PostOfficeCombined');
                    var $form = $('#dsExpress');
                    if ($form.find('#dsSections'))
                    {
                        $form.find('#dsSections').remove();
                    }                        
                    var $sections = $('<div id="dsSections"></div>');
                    var filename = $('#filename').val();
                    if (!filename)
                    {
                        filename = 'File.pdf';
                    }
                    else if (filename.substring(filename.length - 4) != '.pdf')
                    {
                        filename += '.pdf';
                    }
                    var i = 1;
                    $("#documents 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')
                            );
                            i++;
                        }
                    });
                    $sections.append(
                        $('<input type="hidden" name="filename"/>')
                            .attr('value', filename)
                    );
                    $form.append($sections);
                });
        }
    });
    
    $dsSection
        .find('.cancel')
            .click(function() {
                showLoopSection();
                return false;
            })
    .end()
        .find('.next')
            .click(function() {
                $dsSection.tabs('select', $dsSection.tabs('option', 'selected') + 1);
                return false;
            })
    .end()
        .find('.previous')
            .click(function() {
                $dsSection.tabs('select', $dsSection.tabs('option', 'selected') - 1);
                return false;
            });
            
    $('#dsExpress').submit(function() {
        var $form = $(this);
        var isValid = document.getElementById('dsTerms').checked;
        if (isValid)
        {
            isValid = validateAll(this.id);
        }
        if (isValid)
        {
            if($.browser.msie){
                $form.find("*").css({
                    "filter":       "alpha(opacity=30)",
                    "-moz-opacity": "0.3"
                });
            }
            else
            {
                $form.find("*").css({
                    "opacity":      ".30",
                    "-moz-opacity": "0.3"
                });
            }
            $("select").css("visibility", "hidden");
            $("#form_loading_img").prependTo($form).find("img").remove().end().show().prepend('<img src="/images/widgets/throbber.gif" alt="processing" />');
            window.scrollTo(0, 0);
            $('#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);
                        var openUrl = function(url) {
                            if ($.browser.safari)
                            {
                                var w = window.open();
                                w.opener = null;
                                w.document.location = url;
                            }
                            else
                            {
                                window.open(url);
                            }
                        };
                        var url = 'http://www.drawloop.com/docusign/error/';
                        if (response == 'success')
                        {
                            url = 'http://www.drawloop.com/docusign/confirmation/';
                        }
                        else if (response == 'upgrade')
                        {
                            url = 'http://www.drawloop.com/docusign/upgrade/';
                        }
                        else
                        {
                            url = 'http://www.drawloop.com/docusign/error/';
                        }
                        win = window.open(url);
                        
                        $("#form_loading_img").hide();
                        if ($form.find('.results').length)
                        {
                            $form.find('.results').remove();
                        }
                        $results = $('<div class="results"><p>If the results page didn\'t open for you, click <a class="resultsA" href="" target="_blank">here</a>.</p><br/><p>Click <a class="loopA" href="javascript:;">here</a> to return to LOOP.</p>')
                            .find('.resultsA')
                                .attr('href', url)
                        .end()
                            .find('.loopA')
                                .click(function() {
                                    $results.remove();
                                    if($.browser.msie) {
                                        $form.find("*").css({
                                            "filter":       "alpha(opacity=100)",
                                            "-moz-opacity": "1"
                                        });
                                    }
                                    else
                                    {
                                        $form.find("*").css({
                                            "opacity":      "1",
                                            "-moz-opacity": "1"
                                        });
                                    }
                                    $("select").css("visibility", "visible");
                                    showLoopSection();
                                })
                        .end()
                            .prependTo($form);

                    }
                }, 0);
            });
            return true;
        }
        else
        {
            $('#errors_on_page').show();
            return false;
        }
    });
    
//    $('div#sheet_pick').jqm({
//        overlay:        30,
//        overlayClass:   'jqmOverlay'
//    });
    
    /*$('div#sf_docs').jqm({
        trigger:        '#sf_docs_trigger',
        overlay:        30,
        overlayClass:   'jqmOverlay'
    });*/

    //innerHeight method not supported by IE
    var yFrame = (window.innerHeight ? window.innerHeight : 
        (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)
        );
    var yBody = $('body').height();
    $('#documents').height(yFrame-yBody);
        
    window.onresize = function(){
        var yFrame = (window.innerHeight ? window.innerHeight : 
            (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)
            );
        if ($('#dsExpress:visible').length)
        {
            $('#dsExpress').height(yFrame);
        }
        else
        {
            var yBody = $('body').height()-$('#documents').height();
            $('#documents').height(yFrame-yBody);
        }
    };
        
   $("#add_file").hover(function(){
        $(this).find(".button").css("background-position", "0px -24px");
    },function(){
        $(this).find(".button").css("background-position", "0px 0px");
    });
    
    $("#add_url").hover(function(){
        $(this).find(".button").css("background-position", "-30px -23px");
    },function(){
        $(this).find(".button").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");
    });    
	
});
