// JavaScript Document
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.1a
*
* 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
*
*  Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
*  Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.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"];
    jQuery.fn["printElement"] = function (options) {
        var mainOptions = jQuery.extend({}, jQuery.fn["printElement"]["defaults"], options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        if (mainOptions["printMode"] == 'iframe') {
            if (jQuery.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) {
                mainOptions["printMode"] = 'popup';
			}
        }
		//Remove previously printed iframe if exists
        jQuery("[id^='printElement_']").remove();

        return this.each(function () {
            //Support Metadata Plug-in if available
            var opts = jQuery.meta ? jQuery.extend({}, mainOptions, jQuery(this).data()) : mainOptions;
//alert("Here3"+jQuery(this));

//debug.log( this, 'that', { the: 'other' } );
//debug.log( 'This: ', this);
//console.log('This'+jQuery(this));
            MAApopup = _printElement(jQuery(this), opts);

			switch(opts["pgCall"]) {
				case 'Mth-Scores':	
					var foo = jQuery("[id^=printElement]").contents().find(".PArea").find('[id^=gbox_match]');
					var tots = new Number(0);
					var mtch_num = 0;
					var i = 0;
					var fl = foo.length;
					var pxDiv = 0;
					var emValue = 0;
					var pixelValue = 0;

					pixelValue = jQuery("[id^=printElement]").contents().find(".PArea").find('h2').height();
					var scopeElement = jQuery("[id^=printElement]").contents().find(".PArea").find('h2');
					emValue = jQuery(pixelValue).toEm({'scope': scopeElement});
					tots = parseFloat(emValue);

					if (opts["browse"] == 'Firefox') {
//						jQuery("[id^=printElement]").contents().find(".PArea").find('h2').before('<p style="line-height: 1.5056em;"></p>');
//						jQuery("[id^=printElement]").contents().find(".PArea").find('h2').before('<p style="line-height: .5056em;"></p>');
						tots = parseFloat(emValue) + 1.5056;
					} else {
						tots = parseFloat(emValue);
					}
					for(i = 0; i < fl; i++) {
						pixelValue = foo[i].offsetHeight; 
						emValue = $(pixelValue).toEm();
						tots += parseFloat(emValue);
						if (tots >= 40) {
							i=1000;
						} else {
							mtch_num++;
						}
					}
					var mtch = '#gbox_match'+mtch_num;
//	alert("Size is: "+tots.toFixed(2)+"  Grid: "+mtch_num+" I is: " +i+"  Box: "+mtch);

//					jQuery("[id^=printElement]").contents().find(".PArea").find(mtch).css("page-break-after", "always");
					
					if (opts["browse"] == 'Firefox') {
						jQuery("[id^=printElement]").contents().find("[id*=match]").css("font-size",".7em");
						jQuery("[id^=printElement]").contents().find(".ui-jqgrid-labels").css("font-size",".7em");
					} else if (opts["browse"] == 'Explorer') {
//						jQuery("[id^=printElement]").contents().find("[id*=match]").css("font-size",".875em");
//						jQuery("[id^=printElement]").contents().find("[id*=match]").css("line-height","1em");
						jQuery("[id^=printElement]").contents().find(".ui-jqgrid-labels").css("font-size",".6em");
					} else {
						jQuery("[id^=printElement]").contents().find("[id*=match]").css("font-size",".7em");
						jQuery("[id^=printElement]").contents().find(".ui-jqgrid-labels").css("font-size",".7em");
					}					
					
					jQuery("[id^=printElement]").contents().find("[id*=match]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});
					break;
					
				case 'LR-Scores':
					if (opts["browse"] == 'Firefox') {
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").css("font-size",".7em");					
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("font-size",".7em");
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("height","1.5em");
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});
					} else if (opts["browse"] == 'Explorer') {
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").css("font-size","1em");					
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("font-size",".7em");
						jQuery("[id^=printElement]").contents().find("[id^=bcol]").width(125);
//						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("height","1.5em");
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("height","1.5em");
						jQuery("[id^=printElement]").contents().find("[id$=t_lrange]").height(70);
						jQuery("[id^=printElement]").contents().find("[id$=t_lrange]").css("height","6.5em");
						jQuery("[id^=printElement]").contents().find("#tlehdr2").find("#cat").parent().width(84);
//						jQuery("[id^=printElement]").contents().find("[id^=bcol]").width(115);
//						jQuery("[id^=printElement]").contents().find("#tlehdr1").css("line-height","1.35em");
//						jQuery("[id^=printElement]").contents().find("#tlehdr2").css("line-height","8em");
//						jQuery("[id^=printElement]").contents().find(".ui-jqgrid-labels").css("font-size",".6em");
						
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});

//						jQuery("[id^=printElement]").contents().find('.ui-jqgrid-btable').find('tr').css("font-size","2em");
					} else {
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").css("font-size",".7em");					
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("font-size",".7em");
						jQuery("[id^=printElement]").contents().find("[id^=tlehdr]").css("height","1.5em");
						jQuery("[id^=printElement]").contents().find("[id$=lrange]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});
					}

					break;
				case '3DLR-Scores':
					pURL = location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
					break;
				case '3D-Scores':
					jQuery("[id^=printElement]").contents().find(".ui-jqgrid-labels").css("font-size",".7em");
					
					jQuery("[id^=printElement]").contents().find("table[id^=match]").find(".gry").css("background-color","#CCCCCC");
					jQuery("[id^=printElement]").contents().find("table[id^=match]").find("#gry").css("background-color","#CCCCCC");

					jQuery("[id^=printElement]").contents().find("[id$=match]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});	
			
					break;
				case '3D-Carn':
					jQuery("[id^=printElement]").contents().find("[id$=match]").jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});	
					break;					
				default:
					pURL = location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
			}

//alert("Here10");

	        if (jQuery("[id^=printElement]").contents().find('.ui-jqgrid-btable:visible')) {
           		gridParentWidth = jQuery("[id^=printElement]").contents().find('.ui-jqgrid-btable:visible').parent().width();
				grid = jQuery("[id^=printElement]").contents().find('.ui-jqgrid-btable:visible');

/*
jQuery("[id^=printElement]").contents().find("#match1").attr("id", "#match5");
jQuery("[id^=printElement]").contents().find("#match1").attr("id", "#match5");
jQuery("[id^=printElement]").contents().find("#gview_match1").attr("id", "#gview_match5");
jQuery("[id^=printElement]").contents().find("#load_match1").attr("id", "#load_match5");
jQuery("[id^=printElement]").contents().find("#lui_match1").attr("id", "#lui_match5");
jQuery("[id^=printElement]").contents().find("#gbox_match1").attr("id", "#gbox_match5");	*/		


				if (opts["browse"] == 'Firefox') {
				} else {
           		gridParentWidth = jQuery("[id^=printElement]").contents().find('.ui-jqgrid-btable:visible').parent().width(900);

//alert("gridParentWidth:"+gridParentWidth);
				}
	            grid.each(function(index) {
       		        gridId = jQuery(this).attr('id');
					grid2 = jQuery("[id^=printElement]").contents().find('#' + gridId).width();
					
					if (opts["browse"] == 'Firefox') {
	        	        jQuery('#match5').setGridWidth(500);
					} else {
        	        	jQuery('#' + gridId).setGridWidth(gridParentWidth);
//alert("gridId:"+gridId);						
//alert("index:"+index);
					}
        	        jQuery('#' + gridId).setGridWidth(gridParentWidth);
//					jQuery("[id^=printElement]").contents().find('#' + gridId).setGridWidth(gridParentWidth);
//        	        jQuery("[id^=printElement]").contents().find('#gbox_' + gridId).setGridWidth(gridParentWidth);
	            });
//alert("gridId:"+gridId);						
	        }						
			
	        _callPrint(MAApopup);
//jQuery("[id^=printElement]").width(1950);
//jQuery("[id^=printElement]").height(500);

        });
    };
    jQuery.fn["printElement"]["defaults"] = {
        "printMode": 'iframe', //Usage : iframe / popup
        "pageTitle": '', //Print Page Title
        "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:.625em;margin:.625em;', //style attributes to add to the body of print document
            "classNameToAdd": 'maaPtr' //css class to add to the body of print document
        },
        "leaveOpen": true, // in case of popup, leave the print page open or not
        "pgCall": '', //Page Calling printElement
		"browse": 'Explorer',	// IE = Explorer, FF = Firefox
        "iframeElementOptions": {
//            "styleToAdd": 'border:none;position:absolute;width:0em;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            styleToAdd: 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element

            "classNameToAdd": '' //css class to add to the iframe element
        }
    };
    jQuery.fn["printElement"]["cssElement"] = {
        "href": '',
        "media": ''
    };
    function _printElement(element, opts) {
        //Create markup to be printed
        var html = _getMarkup(element, opts);

        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 printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            jQuery(iframe).attr({
                style: opts["iframeElementOptions"]["styleToAdd"],
                id: printElementID,
                className: opts["iframeElementOptions"]["classNameToAdd"],
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            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();
		return popupOrIframe;
    }

    function _callPrint(element) {
        if (element && element["printPage"]) {
            element["printPage"]();
		}
        else {
            setTimeout(function () {
                _callPrint(element);
            }, 50);
		}
//		jQuery("[id^=printElement]").css("display","none");
		jQuery("[id^=printElement]").css("width","0px");
		jQuery("[id^=printElement]").css("height","0px");
//		border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;
    }

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

        var elementHtml = jQuery('<div></div>').append($element.clone()).html();
//alert("Here8");
        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 = jQuery(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
        html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
		switch(opts["pgCall"]) {
			case 'Mth-Scores':
				if (opts["browse"] == 'Firefox') {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-ff.css';
				} else if (opts["browse"] == 'Explorer') {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-ie.css';
				} else {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
				}
				break;
			case 'LR-Scores':
				if (opts["browse"] == 'Firefox') {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-ff.css';
				} else if (opts["browse"] == 'Explorer') {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-ie.css';
				} else {
					pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
				}
				break;
			case '3DLR-Scores':
				pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
				break;
			case '3D-Scores':
				pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-3D-Scores.css';
				break;
			case '3D-Carn':
				pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr-3D-Scores.css';
				break;
			default:
				pURL = 'http://' + location.hostname + '/wordpress/wp-content/plugins/VileBunch/vb-ptr.css';
		}
		html.push('<link type="text/css" rel="stylesheet" href="' + pURL + '" >');
		
        //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('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');

        return html.join('');
    };
})(window);
