function ClickHereToPrint(data_to_print,title){
    try{ 
        var oIframe = document.getElementById('ifrmPrint');
        var oContent = data_to_print;
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;

		oDoc.write("<html><head><title>"+title+"</title>");
		oDoc.write("<link media='all' rel='stylesheet' href='css/all_print.css' type='text/css' />");
		oDoc.write("</head><body onload='this.focus(); this.print();'>");
		oDoc.write(oContent + "</body></html>");	    
		oDoc.close(); 	    
    }
    catch(e){
	    self.print();
    }
}

$(document).ready(function(){
//This is not production quality, its just demo code.
var cookieList = function(cookieName) {
//When the cookie is saved the items will be a comma seperated string
//So we will split the cookie by comma to get the original array
var cookie = $.cookie(cookieName);
//Load the items or a new array if null.
//var items = cookie ? cookie.split(/,/) : new Array();
var items = cookie ? cookie.split(/,/) : new Array();

//Return a object that we can use to access the array.
//while hiding direct access to the declared items array
//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html
return {
    "add": function(val) {
        //Add to the items.
        items.push(val);
        //Save the items to a cookie.
        $.cookie(cookieName, items);
    },
    "clear": function() {
        //clear the cookie.
        $.cookie(cookieName, null);
    },
    "items": function() {
        //Get all the items.
        return items;
    },
    "removeByIndex" : function(index) {
      items.splice(index, 1);
      //Save the items to a cookie.
        $.cookie(cookieName, items);
        
        var list = new cookieList("BriefCaseItems");         
        var count = list.items().length;
        $("li#briefcase a").text('Pokaż Schowek ('+count+')');
                
    }
  }
}

var ileStron=0;
var PageContent="";

var list = new cookieList("BriefCaseItems"); 
var count = list.items().length;
//pokaz schowek + ilosc w schowku
var tmp = $("li#briefcase a").text();
$("li#briefcase a").text(tmp+' ('+count+')');


$("#briefcaseadd a").click(function() {
  var list = new cookieList("BriefCaseItems");
  var title = $("div.heading h2").text().replace(",", "::");
  var url = this.href;
  var data = title+';'+url;
  list.add(data);
  ShowBriefCase();
  
  var list = new cookieList("BriefCaseItems"); 
  var count = list.items().length;
  //pokaz schowek + ilosc w schowku
  $("li#briefcase a").text('Pokaż Schowek ('+count+')');

  return false;  
});

function ShowBriefCaseGenItem(title,link,index) {
  var template="<tr>"+
  "  <td><a href=\""+link+"\">"+title+"</a></td>"+
  "  <td width=\"55\" class=\"center\"><a class=\"print\" href=\"#\" title=\""+title+"\" rel=\""+link+"\">Drukuj</a></td>"+
  "  <td width=\"55\" class=\"center\"><a class=\"briefcasedel\" pos=\""+index+"\" href=\"#\">Usuń</a></td>"+
  "</tr>";
  
  return template;
}

function ShowBriefCase() {
  
  var list = new cookieList("BriefCaseItems"); 
  var content = '';
  
  var count = list.items().length;
  var lists = list.items();
  for (var i=0;i<count;i++) {
    var wpis=lists[i].split(';');    
    content+=ShowBriefCaseGenItem(wpis[0].replace('::',','),wpis[1],i)      
  }
  ileStron=i;
    
  return content;
}

    $("#briefcase a").click(function() {               
        //event.preventDefault();
        var rel = $(this).attr('rel');
        $.fancybox(
        rel,
    		{
          'autoDimensions'	: false,
    			'width'         		: 500,
          'height'        		: 500,
          'overlayShow'	: true,//false,
          'transitionIn'	: 'elastic',
          'transitionOut'	: 'elastic',
          'type'	: 'inline',
          onComplete:function(){          
          
            $('table.schowek > tbody:last').append(ShowBriefCase());
            $('#licznik').html(ileStron);

            $("a.briefcasedel").click(function() {
                var idx=$(this).attr('pos');
                var list = new cookieList("BriefCaseItems");
                list.removeByIndex(idx);
                
                $(this).parent().parent().remove();                
                var i=0;
                $("table#schowek tr:gt(0)").each(function() {
                  $this = $(this);
                  var value = $this.find(".briefcasedel").attr('pos',i++);
                });
                
                $('#licznik').html(list.items().length);    
                return false; 
            })
            
            $(".print").click(function(){            
            		var rel=jQuery(this).attr('rel');
            		var title=jQuery(this).attr('title');
            		jQuery.ajax({
              		method: "POST",
                      url: rel,
              		success: function(dane2){
               		     ClickHereToPrint(dane2,title);
              			}
                });
            		return false;
            });
            
            function Loader(i) {
              if (i==0) PageContent="";
              var list = new cookieList("BriefCaseItems");
              var count = list.items().length;
              var lists = list.items();              
              var wpis=lists[i].split(';');                
              var rel=wpis[1];
              $("div#dialogbox").html("Wczytywanie pozycji nr "+(i+1));
              jQuery.ajax({
                method: "POST",
                url: rel,
                success: function(dane2){                
                  PageContent+=dane2;
                  i++;                  
                  if (i<count) { return Loader(i);} 
                  else {
                    $("div#dialogbox").html("Koniec wczytywania");                    
                    ClickHereToPrint(PageContent,"Raport");
                    return false;
                  }
                  
                }
              });
            }
            
            $(".printall").click(function(){
                Loader(0);            
            		return false;
            });

           return false; 
          } 
    		});
        return false; 
    })

});
