/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
*  Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement 
*  Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
*  jQuery plugin page : http://plugins.jquery.com/project/printElement 
*  
*  Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
*  For their great contributions!
* 
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*   
*   Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
(function (window, undefined) {
    var document = window["document"];
    var $ = window["jQuery"];
    $.fn["printElement"] = function (options) {
        var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
//        if (mainOptions["printMode"] == 'iframe') {
//            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
//                mainOptions["printMode"] = 'popup';
//        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();
        $('._JanelaModalPrintAberta').remove();

        return this.each(function () {
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn["printElement"]["defaults"] = {
        "printMode": 'iframe', //Usage : iframe / popup
        "pageTitle": '', //Print Page Title
        "DialogBox": true, //Exibe um formato Dialog Box padrão (true) ou exibe somente o DIV flutuante
        "overrideElementCSS": null,
        /* Can be one of the following 3 options:
        * 1 : boolean (pass true for stripping all css linked)
        * 2 : array of $.fn.printElement.cssElement (s)
        * 3 : array of strings with paths to alternate css files (optimized for print)
        */
        "printBodyOptions": {
            "styleToAdd": 'padding:0;margin:0;scrolling:yes;', //style attributes to add to the body of print document
            "classNameToAdd": '' //css class to add to the body of print document
        },
        "leaveOpen": false, // in case of popup, leave the print page open or not
        "extraHeight": 0,
        "iframeElementOptions": {
            //BORDIM
            //"styleToAdd": 'border:none;position:relative;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            "styleToAdd": 'border:none;position:relative;bottom:0px;left:0px;width:100%;height:100%;padding:0;', //style attributes to add to the iframe element
            "classNameToAdd": '' //css class to add to the iframe element
        }
    };
    $.fn["printElement"]["cssElement"] = {
        "href": '',
        "media": ''
    };
    function _printElement(element, opts) {

        //Create markup to be printed
        var html = _getMarkup(element, opts);

        //alert(html);

        var popupOrIframe = null;
        var documentToWriteTo = null;
        
        if (opts["printMode"].toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html

            var id_variant = (Math.round(Math.random() * 99999)).toString();
            var printElementID = "printElement_" + id_variant;
            var printDivID = "modalPrint_" + id_variant;

            //Cria container para o IFRAME
            var $printDiv = $('<div></div>')
                               .attr('id', printDivID)
                               .css('display', 'none')
                               .css('padding', 0)
                               .addClass('_JanelaModalPrintAberta')
                               .appendTo($(document.body));

            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
           
            var $iframe = $(iframe).attr({
                              style: opts["iframeElementOptions"]["styleToAdd"],
                              id: printElementID,
                              name: printElementID,
                              className: opts["iframeElementOptions"]["classNameToAdd"],
                              frameBorder: 0,
                              scrolling: 'auto',
                              src: 'about:blank'
                          }).appendTo($printDiv);


            //document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document)
                documentToWriteTo = documentToWriteTo.document;
//            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
//            popupOrIframe = iframe.contentWindow || iframe;

            focus();
            documentToWriteTo.open();
            documentToWriteTo.write(html);
            documentToWriteTo.close();

            if(opts["DialogBox"] == true){

                $printDiv.dialog({
                   width: $(element).width() + 100
                  ,height: 600
                  ,autoOpen: false
                  ,modal: true
                  ,title: opts["pageTitle"]
                  ,buttons: [
                    {text: "Imprimir", click: function() {
                        window.frames[printElementID].focus();
                        window.frames[printElementID].print();

                        $(this).dialog("close");
                      }}
                  ]
                  ,close: function(event, ui) {
                        try{
                          $(this).remove();
                        }catch(e){
                          //Gera uma exceção que não precisa ser tratada!
                        }
                  }

                }).dialog('open');
            }
            else{

              //CRIA A MASCARA DE FUNDO
              $('<div></div>')
                .attr('id', '_mask')
                .css('position', 'fixed')
                .css('top', 0)
                .css('z-index', 11000)
                .css('background-color','#000')
                .css('display', 'none')
                .addClass('_JanelaModalPrintAberta')
                .height($(document).height())
                .width($(window).width())
                .appendTo($(document.body))
                .fadeTo("fast", 0.8)
                .click(function(){
                  $('._JanelaModalPrintAberta').remove();
                });

              //alert($(window).height());


              //var height = opts["extraHeight"];


              var height = $(element).outerHeight(true) + opts["extraHeight"];
              if(height > $(window).height()){
                  height = $(window).height();
              }

              $printDiv
                .css('position', 'absolute')
                .css('z-index', 11001)
                .width($(element).width() + 100)
                .height(height);

              var top = $(window).height() / 2 - $printDiv.outerHeight(true) / 2;
              if(top < 0) top = 0;

              var left = $(window).width() / 2 - $printDiv.outerWidth(true) / 2;
              if(left < 0) left = 0;

              //centraliza na tela a janela popup
              $printDiv
                .css('top', top)
                .css('left', left)
                .fadeIn(500);
            }

            
        }
//        $('#'+printElementID).html(html);
        //_callPrint(popupOrIframe);

        
    }

    function _callPrint(element) {
        if (element && element["printPage"])
            element["printPage"]();
        else
            setTimeout(function () {
                _callPrint(element);
            }, 50);
    }

    function _getElementHTMLIncludingFormElements(element) {
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function () {
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function () {
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function () {
            var $select = $(this);
            $("option", $select).each(function () {
                if ($select.val() == $(this).val())
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function () {
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
            if ($.browser.mozilla && this.firstChild)
                this.firstChild.textContent = value;
            else
                this.innerHTML = value;
        });
        //http://dbj.org/dbj/?p=91
        var elementHtml = $('<div></div>').append($element.clone()).html();
        return elementHtml;
    }

    function _getBaseHref() {
        var port = (window.location.port) ? ':' + window.location.port : '';
        return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
    }

    function _getMarkup(element, opts) {
        var $element = $(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
        html.push('<html><head><title>' + opts["pageTitle"] + '</title>\n');
        if (opts["overrideElementCSS"]) {
            if (opts["overrideElementCSS"].length > 0) {
                for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
                    var current = opts["overrideElementCSS"][x];
                    if (typeof (current) == 'string')
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >\n');
                    else
                        html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >\n');
                }
            }
        }
        else {
            $("link", document).filter(function () {
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function () {
                //BORDIM
                if($(this).attr('media') != 'print'){
                  html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
                }
                else{
                  html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '"  />\n');
                }
            });
        }
        var htmScript = '\n';

        htmScript += 'function closePage(){\n';
        htmScript += '  parent.closePrintElement();\n';
        htmScript += '}\n';

        htmScript += 'function printPage(){\n';
        htmScript += '  focus();\n';
        htmScript += '  print();\n';
        htmScript += '  ' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'closePage();' : '') + '\n';
        htmScript += '  return false;\n';
        htmScript += '}\n';

        htmScript += 'function MM_swapImgRestore() { //v3.0\n';
        //htmScript += '    alert("1");\n';
        htmScript += '  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;\n';
        htmScript += '}\n';

        htmScript += 'function MM_swapImage() { //v3.0\n';
        //htmScript += '    alert("2");\n';
        htmScript += '  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)\n';
        htmScript += '   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}\n';
        htmScript += '}\n';

        htmScript += 'function MM_findObj(n, d) { //v4.01\n';
        htmScript += '  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {\n';
        htmScript += '    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}\n';
        htmScript += '  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];\n';
        htmScript += '  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);\n';
        htmScript += '  if(!x && d.getElementById) x=d.getElementById(n); return x;\n';
        htmScript += '}\n';

        html.push('\n<script type="text/javascript">'+htmScript+'</script>');
        //html.push('<script type="text/javascript">function closePage(){focus();close();}</script>');

        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');

        html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
        html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
        html.push('</body></html>');

        return html.join('');
    }

})(window);

function closePrintElement(){
  $("._JanelaModalPrintAberta").remove();
}
