var isDenver = false;
if(window.location.pathname.match(/denver/) != null){
  isDenver = true; 
}

jQuery(function($){
  var $images = $("#store_image img");
  if($images.length){
    
    $images.each(function(idx){
      $(this).attr('rel', idx);
      $('<a class="offer_print" rel="'+idx+'">Print</a>').insertAfter(this);
    });
    
    if(isDenver){
      var ts = +new Date();
      $('body').append('<img src="https://ads.undertone.com/t?trackerid=1040&cb='+ ts +'" style="display: none;" width="0" height="0" alt="" />');
    }
    
    $(".offer_print").attr('target', '_blank').bind('click keypress', function(event) {
      var idx = $(this).attr('rel') || 0;
      
      var code=event.charCode || event.keyCode;

      if(!code || (code && code == 13)) {
        if(_gaq){
          var fixedLink = window.location.href;
          fixedLink = fixedLink.replace(/https?:\/\/(.*)/,"$1");
          fixedLink = '/offer_print/' + fixedLink + idx;
          _gaq.push(['_trackPageview', fixedLink])
        };

      };    
      printIt($('<div>').append($images.eq(idx).clone()).remove().html(), idx);
    });   
  }
});

// Print function
var win=null;
function printIt(printThis, idx)
{
  win = window.open();
  self.focus();
  win.document.open();
  win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
  win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
  win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
  win.document.write(printThis);
  if(isDenver){
    var ts = +new Date();
    if(idx == 0){
      win.document.write('<img src="https://network.realmedia.com/RealMedia/ads/adstream_nx.ads/1?XE&epmAccountKey=1100&epmXTransKey=991&epmXtransStep=0&ProductCategory=&ItemDescription=&XE">');
      win.document.write('<img src="https://ads.undertone.com/t?trackerid=1041&cb='+ ts +'" style="display: none;" width="0" height="0" alt="" />');
    }
    if(idx == 1){
      win.document.write('<img src="https://network.realmedia.com/RealMedia/ads/adstream_nx.ads/1?XE&epmAccountKey=1100&epmXTransKey=991&epmXtransStep=999&epmXtransCategory=&epmXtransItem=&epmXtransQuantity=&epmXTransRevenue=&XE">');
      win.document.write('<img src="https://ads.undertone.com/t?trackerid=1044&cb='+ ts +'" style="display: none;" width="0" height="0" alt="" />');
    }
  }
  win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
  win.document.close();
  win.print();
  win.close();
}
