// 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.com/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;
            MAApopup = _printElement(jQuery(this), opts);

			if (opts["browse"] == 'Explorer') {
				jQuery("[id^=printElement]").contents().find('.content').css('width','76%');	//Works				
				jQuery("[id^=printElement]").contents().find('.content').css('float','left');
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').slice(2).find('.content').css('width','100%');
//				jQuery("[id^=printElement]").contents().find('.content').css('border','thin dashed #7FFF00');	//Green
				
//				jQuery("[id^=printElement]").contents().find('#sideR').css('width','23%');		//Works
//				jQuery("[id^=printElement]").contents().find('#sideR').css('float','right');
//				jQuery("[id^=printElement]").contents().find('.news_pg1').find('#sideR').css('background','#DEDEDE');
//				jQuery("[id^=printElement]").contents().find('.news_pg1').find('#sideR').css('border','thin solid #999999');
//				jQuery("[id^=printElement]").contents().find('.news_pg2').find('#sideR').css('border','thin solid #999999');

//				jQuery("[id^=printElement]").contents().find('.news_pg2').find('#sideR').css('background','#DEDEDE');
//				jQuery("[id^=printElement]").contents().find('#sideR').css('background','#DEDEDE');
//				jQuery("[id^=printElement]").contents().find('#sideR').css('border','thin dotted #00008B');	//	Blue
//				jQuery("[id^=printElement]").contents().find('#sideR').css('border','thin solid #999999');
jQuery("[id^=printElement]").contents().find('#sideR').find('h3').after("<div id='sideEvt' class='sideEvt'></div>");
jQuery("[id^=printElement]").contents().find('#sideEvt').append(jQuery("[id^=printElement]").contents().find('.ec3_events'));

				jQuery("[id^=printElement]").contents().find("#lr-pist").css('width','75%');
				jQuery("[id^=printElement]").contents().find("#lr-vb").css('width','75%');
				jQuery("[id^=printElement]").contents().find('#lr-vb').css('padding-top','.5em');

//				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find('.ec3_events').css('padding-left','.5em');
//				jQuery("[id^=printElement]").contents().find('.news_pg1').find(".ec3_list").find("ul").css('padding-left','.1em');
//jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("ul").css('padding-left','2em');

				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find('.ec3_events').css('padding-left','0em');
				jQuery("[id^=printElement]").contents().find('.news_pg1').find(".ec3_list").find("ul").css('padding-left','0em');
				
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("li").find("span").css("font-family","serif");
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("li").find("span").css("font-size",".75em");
jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("ul").css('padding-left','0em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('margin-top','0em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('margin-bottom','0em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('padding-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('font-size','2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vhead').css("font-size","2em");
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vhead').css('margin-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vhead').css('padding-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile').css('margin-bottom','.2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('padding-bottom','.2em');

				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('margin-top','.2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('margin-bottom','.2em');

				jQuery("[id^=printElement]").contents().find('.post').find('h1').css('font-size','1.5em');
				jQuery("[id^=printElement]").contents().find('#ptr-maa').find('.post').css('padding',".5em");
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').css('border-right',"thin solid #999999");	//	Gray
//								jQuery("[id^=printElement]").contents().find('#ptr-maa').css('display','block');
				jQuery("[id^=printElement]").contents().find('#prt-title').css('background-color','#CCCCCC');
				jQuery("[id^=printElement]").contents().find('#prt-title').css('border','thin solid #999999');		//	Gray
				jQuery("[id^=printElement]").contents().find('#sideR').css('width','23%');		//Works

			} else if (opts["browse"] == 'Firefox') {
				jQuery("[id^=printElement]").contents().find("#lr-pist").css('width','75%');
				jQuery("[id^=printElement]").contents().find("#lr-vb").css('width','75%');
				jQuery("[id^=printElement]").contents().find('.post').find('h1').css('font-size','1.5em');
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find('.ec3_events').css('padding-left','1em');
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("li").find("span").css("font-family","serif");
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("li").find("span").css("font-size",".5em");
//				jQuery("[id^=printElement]").contents().find('.content').css('width','76%');	//Works
//				jQuery("[id^=printElement]").contents().find('#sideR').css('width','23%');		//Works
//				jQuery("[id^=printElement]").contents().find('#sideR').css('border','thin dotted #00008B');	//	Blue
				
//				jQuery("[id^=printElement]").contents().find('.content').css('border','thin dashed #7FFF00');// Green
				jQuery("[id^=printElement]").contents().find('#ptr-maa').find('.post').css('padding',".5em");
jQuery("[id^=printElement]").contents().find('[class^=news_pg]').css('border-right',"thin solid #999999");	//	Gray
//	LAST border
				jQuery("[id^=printElement]").contents().find('.news_pg1').find(".ec3_list").find("ul").css('padding-left','1em');
				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find(".sidebar_ammo").find(".entry").find("ul").css('padding-left','2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('margin-top','0em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('margin-bottom','0em');
				jQuery("[id^=printElement]").contents().find('.sidebar_ammo').find('.post').find('h2').css('padding-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('#lr-vb').css('padding-top','.5em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vhead').css('margin-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vhead').css('padding-bottom','.1em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile').css('margin-bottom','.2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('margin-top','.2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('margin-bottom','.2em');
				jQuery("[id^=printElement]").contents().find('.sidebar_vile').find('.vile_mail').css('padding-bottom','.2em');
				jQuery("[id^=printElement]").contents().find('#ptr-maa').find('div.last').css('border-right','none');

//				jQuery("[id^=printElement]").contents().find('#ptr-maa').find('div.last').css('border','thin dotted #00008B');	//	Blue
//				jQuery("[id^=printElement]").contents().find('#ptr-maa').find('div.first').css('border','thin dotted #FFD700');	//	Yellow
				
//				jQuery("[id^=printElement]").contents().find('[class^=news_pg]').slice(2).find('.content').css('width','100%');
			} else {		//	Browser
			}		
//			jQuery("[id^=printElement]").contents().find('[class^=news_pg]').find('#sideR').after(jQuery("<br style='clear:both;'>"));
				jQuery("[id^=printElement]").contents().find('#ptr-maa').css('display','block');						
						
	        _callPrint(MAApopup);
//			jQuery("[id^=printElement]").width(1200);
//			jQuery("[id^=printElement]").height(5000);
			jQuery("[id^=printElement]").width(0);
			jQuery("[id^=printElement]").height(0);

		});
	};
	
    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:.25em;margin:.25em;', //style attributes to add to the body of print document
//            "styleToAdd": 'margin:.1em;', //style attributes to add to the body of print document
            "styleToAdd": '', //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
        "sidebar": '', //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
            "classNameToAdd": 'maaNewsStg' //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);
		}
    }

    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
        var elementHtml = jQuery('<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 = jQuery(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
//        html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
 		      html.push('<html><head><title>' + 'The Long Riders News' + '</title>');
				if (opts["browse"] == 'Firefox') {
					pURL = templateDir + '/css/vb-news-stgs-ff.css';
					
				} else if (opts["browse"] == 'Explorer') {
					pURL = templateDir + '/css/vb-news-stgs-ie.css';
				} else {
					pURL = templateDir + '/css/vb-news-stgs-ff.css';
				}

//alert('Browser:'+opts["browse"]+':XX');		
//alert('pURL:'+pURL+':XX');		
		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"] + '">');
		if ($element.attr('class') == '') {
	        html.push('<div class="stgnews" style="width:95%; height:95%;">' + elementHtml + '</div>');
//debug.log( 'NewsC: ', $element);
		} else {
	        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);
