if(document.body.getAttribute('pf-init') == null) {

document.body.setAttribute('pf-init',true);

var cdnDomain = ''
var pfDomain = ''
var start = new Date().getTime();

if(typeof(local_dev) != "undefined" || typeof(local_ie_dev) != "undefined") {
  cdnDomain = 'http://10.0.0.100:3000';
  pfDomain = 'http://10.0.0.100:3000';
} else {
  cdnDomain = 'http://cdn.printfriendly.com';
  pfDomain = 'http://www.printfriendly.com';
}

var Browser = {
  Version: function() {
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
  }
}

var pf = {
  jquerySrc: cdnDomain + '/javascripts/v2/jquery-plugins.js?x=' + (Math.random()),
  readabilitySrc: cdnDomain + '/javascripts/v2/readability.js?x=' + (Math.random()) ,
  pageCssSrc: cdnDomain + '/stylesheets/v2/printfriendly.css?x=' + (Math.random()) ,
  pdfSrc: pfDomain + '/print/new_get_pdf',
  bodyCache: null,
  headCache: null,
  deletedNodes: [],
  deletedNodesCss: [],
  iDoc: null,
  height: 400,
  removeads: false,
  domainCssSrc: null,
  domainJsSrc: null,

  setPrintSrc: function(domain) {
    pf.domainCssSrc =  cdnDomain + '/stylesheets/v2/custom/' + domain + '.css?x=' + (Math.random());
    pf.domainJsSrc = cdnDomain + '/javascripts/v2/custom/' + domain + '.js?x=' + (Math.random());
  },


  // more or less stolen form jquery core and adapted by paul irish
  getScript: function(url,success){
    var script=document.createElement('script');
    script.src=url;
    var head=document.getElementsByTagName('head')[0],
        done=false;
    // Attach handlers for all browsers
    script.onload=script.onreadystatechange = function(){
      if ( !done && (!this.readyState
           || this.readyState == 'loaded'
           || this.readyState == 'complete') ) {
        done=true;
        success();
        script.onload = script.onreadystatechange = null;
        //head.removeChild(script);
      }
    };
    head.appendChild(script);
  },

  iframeContent: function() {
    return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head></head><body onload="window.parent.pf.setIframeContent()">&nbsp;</body></html>';
  },

  setIframeContent: function() {
        $('#pfiframe').contents().find('body').append(pf.bodyCache);

        pf.iDoc =  $('#pfiframe')[0].contentWindow.document;
        var head = pf.iDoc.getElementsByTagName('head')[0];
        pf.iDoc.body.style.visibility = 'hidden';

        if($('head').length > 0) {
          if(Browser.Version() >= 8) {
            $('meta').each(function(){
              $(head).append($(this).clone());
            });
          }
          try {
            var title = pf.iDoc.createElement('title');
            head.appendChild(title);
            pf.iDoc.title = $('h1.entry-title').html();
          } catch(e) {}
        }

        $('head',pf.iDoc).append('<link rel="stylesheet" href="'+  pf.pageCssSrc +'" type="text/css" media="screen,print" />');

        if(pf.domainCssSrc == null ) {
          pf.insertJs(pf.iDoc, pf.readabilitySrc);
        } else {
          $('head',pf.iDoc).append('<link rel="stylesheet" href="'+  pf.domainCssSrc +'" type="text/css" media="screen,print" />');
          // to fix pdf, we need the styles in body
          $('body',pf.iDoc).append('<link rel="stylesheet" href="'+  pf.domainCssSrc +'" type="text/css" media="screen,print" />');
          pf.insertJs(pf.iDoc, pf.jquerySrc);
          pf.insertJs(pf.iDoc, pf.domainJsSrc);
        }

  },

  start: function() {
      var host = (typeof on_pf_site == "undefined") ? top.location.host : requestDomain;
      var domain = host.split(':')[0].split('www.').pop();
      var noads_domains = ['pf.smackaho.st','ndcrc.org', 'media.chelseagreen.com', 'eaglecounty.us', 'us.reachout.com', 'workt.nl', 'neastsolar.com', 'sustainablepractice.org', 'socialmediaexaminer.com', 'doxim.com', 'icadvinc.org'];
      var special_domains = ['hubpages.com', 'skinnytaste.com'];
      if($.inArray(domain,noads_domains) != -1) {
        pf.removeads = true;
      }
      if($.inArray(domain,special_domains) != -1 && typeof on_pf_site == "undefined") {
        pf.setPrintSrc(domain);
      }

      var sx =new RegExp("<script[^>]*>(.*?)</script>","i");
      var lx =new RegExp("<link[^>]*>","i");
      pf.bodyCache = document.body.innerHTML.replace(sx,'').replace(lx,'');
      if(typeof on_pf_site == "undefined") {
        $('body').html('<p></p>'); // Blank the document. Fixes some issues with IE
      }

      $('body').append('<div style="z-index: 10; position: fixed; top: 0pt; left: 0pt; background-color: rgb(0, 0, 0); opacity: 0.85; height: 100%; width: 100%;" id="pf-mask"></div>');
      if(typeof on_pf_site == "undefined") {
        pf.removeNodes(document.getElementsByTagName('style'));
        pf.removeNodes(document.getElementsByTagName('link'));
      }
      $('body').css({'overflow': 'hidden'});

      pf.height = $(window).height() - (typeof on_pf_site == 'undefined' ? 60 : 160);

      $(document).ready(function () {

      $('body').append([
          '<form id="pf-pdf-form" method="post" action="' + pf.pdfSrc + '">',
            '<input type="hidden" name="code" value="" >',
            '<input type="hidden" name="hostname" value="' + top.location.host + '">',
            '<input type="hidden" name="url" value="' + top.location.href + '" >',
            '<input type="hidden" name="title" value="" >',
            '<input type="hidden" name="version" value="2" >',
          '</form>',
            '<div id="pf-content">',
              '<div id="pnLightbox" class="yui-panel">',
			          '<a href="#" class="container-close" id="pf-lightbox-close">Close</a>',
                '<div class="hd" id="pn-hdr" style="cursor: auto;">',
                  '<ul>',
                    '<li id="w-print"><a href="#"></a></li>',
                    '<li id="w-pdf"><a href="#"></a></li>',
                    '<li id="w-email"><a href="#"></a></li>',
					          '<li id="w-txtsize"><label>text</label><select name="txtsize" id="textsize"><option value="x-small">x-small</option><option value="small">small</option><option value="medium" selected="selected">medium</option><option value="large">large</option><option value="x-large">x-large</option></select></li>',
                    '<li id="w-remove-images"><label>no images</label><input type="checkbox" id="wri"></li>',
					'<li id="w-undo"><a href="#">undo</a></li>',
                  '</ul>',
                '</div>',
                '<div id="pf-print-popup">',
                  '<div class="dialog">',
                    '<a href="#" id="pf-close" class="close">close</a>',
                    '<div class="header pf-print"><span id="printSpan" style="display: none;"><img id="printImg" src="http://cdn.printfriendly.com/icon-print-32.gif" alt="Print Icon">Printing Your Page</span><span id="pdfSpan" style="display: none;"><img id="pdfImg" src="http://cdn.printfriendly.com/icon-pdf-32.gif" alt="Print Icon">Generating Your PDF</span></div>',
                    '<p id="printText" style="display:none;">We\'ve sent your page to your printer <a onclick="frames.pfiframe.focus();frames.pfiframe.print();return false;" href="#">re-send</a></p>',
                    '<p id="pdfText" style="display: none;">Just a sec... a window will appear prompting you to open or save your PDF. This usually takes around 5 seconds.</p>',
                    '<div id="pf-ads">',
                      '<iframe width="350px" scrolling="no" height="280px" frameborder="0"  name="gaiframe" id="gaiframe" src="http://www.printfriendly.com/googads" style="overflow: hidden;"></iframe>',
                      '<iframe width="350px" scrolling="no" height="280px" frameborder="0" name="aaiframe" id="aaiframe" src="http://www.printfriendly.com/amznads" style="overflow: hidden;"></iframe>',
                      '<br style="clear:both">',
                    '</div>',
                  '</div>',
                '</div>',
              '</div>',
				      '<div class="ft" id="pf-ft"><a href="http://www.printfriendly.com" title="PrintFriendly - Save paper and ink, print nicer documents" class="f-logo">taylor</a></div>',
            '</div>'].join("\n"));

      $('#pf-lightbox-close').click(function(){
        try{
          document.body.innerHTML = '<div id="closePFLightbox"><h2>Refreshing Your Page</h2></div>' } catch(err) {}
        window.location.href = window.location.href.replace("pfstyle=wp",'').replace(/#(.*)$/,'');
      });

      $('#textsize').change(function() {
          $('#readOverlay', pf.iDoc).css('font-size',$(this).attr('value'));
      });

      $('#w-print').click(function(){
        $("#pf-print-popup").css({'display': 'block'});
        $("#pdfSpan, #pdfText").hide();
        $("#printSpan, #printText").show();
        if(!pf.removeads) {
          $('#pf-ads').show();
        }
        frames.pfiframe.focus();
        frames.pfiframe.print();
        return false;
      });

      $('#w-pdf').click(function(){
        var title = '';
        $("#pf-print-popup").css({'position':'absolute', 'display': 'block'});
        $("#printSpan, #printText").hide();
        $("#pdfSpan, #pdfText").show();
        if(!pf.removeads) {
          $('#pf-ads').show();
        }
        try {
          title = $('h1', pf.iDoc)[0].innerHTML;
        }catch(e) {}
        $("#pf-pdf-form input[name=title]").val(title);
        $("#pf-pdf-form input[name=code]").val(pf.iDoc.body.innerHTML);
        $("#pf-pdf-form").submit();
        frames.pfiframe.focus();
        return false;
      });

      $('#w-email').click(function(){
        var url = (typeof on_pf_site == "undefined") ? top.location.href : requestUrl;
        var title = (typeof on_pf_site == "undefined") ? top.document.title : retrieved_title;
        location.href = 'mailto:?subject=Interesting link (via PrintFriendly.com)&body=Hi, %0A%0AThought you would like this print-friendly version of "' + encodeURIComponent(title) + '": ' + 'http://www.printfriendly.com/print?url='+ url + '%0A%0A--%0ABrought to you by PrintFriendly.com';
      });

      $('#pf-close').click(function() {
           $("#pf-print-popup").hide();
      });

      $("#w-undo").click(function(){
          try {
            pf.deletedNodes.pop().css({'display': pf.deletedNodesCss.pop() });
          } catch(e) {}
      });

      $('#w-remove-images').click(function(){
        $('img', pf.iDoc).toggleClass('hidden');
        $('#wri').attr('checked', !$('#wri').attr('checked'));
        return false;
      });

      $('#wri').click(function(e){
        $('img', pf.iDoc).toggleClass('hidden');
        e.stopPropagation();
      });

      $('<iframe id="pfiframe" src="javascript:parent.pf.iframeContent()" name="pfiframe" height="' + (pf.height - 77) + 'px" width="898px" frameBorder="0" margin="0" padding="0"/>').insertBefore('#pf-ft');
    pf.showLightbox();
    });
  },
  startIO: function () {
    pf.connObj.io(pf.pdfSrc + '.json', {
      xdr: {use: 'flash'},
      data: jQuery("#pf-pdf-form").serialize(),
      headers: {'Accept': 'text/javascript'},
      on: {success: function(id,response,args) {
                      var data = jQuery.parseJSON(response.responseText);
                      jQuery('#pdf-download-form input[name=print_id]').val(data.print_id);
                      pf.printId=data.print_id;
                      pf.poll(); },
          failure:  function(id,response,args) {  }
      },
      method: 'post'
    });
  },
  insertJs:  function(doc,src) {
    var script = doc.createElement('script');
    script.src = src;
    var head = doc.getElementsByTagName('head')[0];
    head.appendChild(script);
  },

  showLightbox: function() {
    $(window).scrollTop(0);
    $('#pf-content').css({'height': pf.height,
                          'width' : '900px',
                          'position' : 'absolute',
                          'top': '30px',
                          'left':  parseInt(($(window).width() - 900) / 2),
                          'background-color': '#ffffff',
                          'z-index': 10001});
  },

  removeNodes: function(nodes) {
    for(i=nodes.length-1; i >= 0; i--) {
      var node = nodes[i];
      var url = node.href || node.src;
      // Don't remove scripts and styles introduced by us
      if(url == null || typeof url == "undefined" ||  (url.lastIndexOf('localhost') == -1 && url.lastIndexOf('printfriendly') == -1)){
        // Being lazy because stupid IE does not have hasAttribute and jquery hasn't loaded
        // at this point. So using multiple try/catch blocks
        try {
          node.nodeValue="";
        } catch(e) {}
        try {
          node.removeAttribute('src');
        } catch(e) {}
        try {
          node.removeAttribute('href');
        } catch(e) {}
        if (node.parentNode) {
          node.parentNode.removeChild(node);
        }
      }
    }
  },

  init: function() {
    if(typeof on_pf_site == "undefined") {
      // sanitize html. framebusters etc need to be removed
      pf.removeNodes(document.getElementsByTagName('script'));
      pf.removeNodes(document.getElementsByTagName('noscript'));
      pf.removeNodes(document.getElementsByTagName('ins'));
      pf.removeNodes(document.getElementsByTagName('iframe'));
      pf.removeNodes(document.getElementsByTagName('object'));
      pf.removeNodes(document.getElementsByTagName('embed'));

      pf.getScript(pf.jquerySrc,function() {
        pf.start();
      });
    } else {
      pf.start();
    }
  },
  complete: function() {
    pf.iDoc =  $('#pfiframe')[0].contentWindow.document;
    // This function is called by readability after it complete
    try {
       $([
           '<a href="' + document.location.href +'" id="pf_source">',
              typeof on_pf_site != "undefined" ?  unescape(document.location.href.split("=")[1]) : document.location.href ,
            '</a>',
            '<div id="pf_date">', jQuery.format.date(new Date(),'MMMM dd, yyyy'), '</div>',
            '<div style="clear:both"></div>'
       ].join('')).insertBefore($('#readability-content', pf.iDoc));
    } catch(e) {}
    $('body', pf.iDoc).append('<br style="clear:both">');

    // remove default click event
    $("a",pf.iDoc).click(function(e){
        return false;
    });

    if(Browser.Version() >= 8) {
      $("p, img, blockquote, h1, h2, h3, h4, li, a, tr",pf.iDoc).hover(function () {
          $(this).addClass("hilight");
          return false;
        }, function () {
          $(this).removeClass("hilight");
      });

     $("p, img, blockquote, h1, h2, h3, h4, li, a, tr",pf.iDoc).click(function () {
        pf.deletedNodes.push($(this));
        pf.deletedNodesCss.push($(this).css('display'));
        $(this).css({'display':'none'});
        // stops event propagation and default event.
        // Otherwise event propagtes to parent/child
        // and it becomes a mess
        return false;
      });
    }
    if(typeof on_pf_site != 'undefined') {
      $('h1',pf.iDoc)[0].innerHTML = retrieved_title;
    }
    pf.iDoc.body.style.visibility = 'visible';
    var end = new Date().getTime();
    var time = end - start;
  }
}



function onDOMLoad(callback) {
  if (document.body.getAttribute('pf-onload-attached')) {
      return;
  }
  if ( document.readyState === "complete" ) {
    callback();
  }
  var onReady, onComplete, done, ie_interval,
  d = window.document;
  // For awesome browsers
  if (window.addEventListener) {
      onComplete = function () {
          window.removeEventListener('DOMContentLoaded', onComplete, false);
          window.removeEventListener('load', onComplete, false)
          if (!done) {
              done = true;
              callback();
          }
      };
      window.addEventListener('DOMContentLoaded', onComplete, false);
      window.addEventListener('load', onComplete, false)
  } else {
      if (window.attachEvent) {
          onComplete = function () {
              window.detachEvent('onreadystatechange', onReady);
              window.detachEvent('onload', onComplete);
              if (!done) {
                  done = true;
                  callback();
              }
          };
          onReady = function () {
              if (d.readyState === 'complete') {
                  onComplete();
              }
          };
          // You can only scroll when the document is ready - ugly hack
          //doScrollCheck(onReady);
          window.attachEvent('onreadystatechange', onReady);
          window.attachEvent('onload', onComplete);
      }
  }
  document.body.setAttribute('pf-onload-attached', true);
}

function doScrollCheck(onReady) {
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch(e) {
		setTimeout( function() {doScrollCheck(onReady)}, 20 );
		return;
	}
  onReady();
}

var _page_css=document.createElement('link');
_page_css.rel='stylesheet';
_page_css.type='text/css';
_page_css.media='screen';
_page_css.href= pf.pageCssSrc;

try {
  document.getElementsByTagName("head")[0].appendChild(_page_css);
} catch(e) {
  document.createElement('head');
  document.getElementsByTagName("head")[0].appendChild(_page_css);
}


window.print = function() {onDOMLoad(pf.init)};
if (typeof pfstyle != "undefined" || top.location.href.indexOf('pfstyle=wp') != -1) {
  window.print();
}

}

