//function to handle javascript printing
//alert('Printer');
Printers = new Array();
var Printer = function(obj){
	this.Def = "TaquaLB/Printer/def.html";
	obj = (!IsSet(obj) || IsNull(obj))?{}:obj; //make sure that obj contain an object (if not set set it to an empty object)
	this.url = "";
	this.printstatus = 'off'; //the state of the printer (default: on)
	var id = Math.random().toString(); //randomly generate a number, convert to string to set as the printer iframe id
	while(!IsNull(_(id)) || IsSet(Printers[id])){ //makes sure the id is a unueqe one
		id = Math.random().toString();
	}
	this.frameID = id; //set the objects frame id property
	//sets the print template, if not supplied set it to none
	this.templ = (!IsSet(obj.Template) || IsNull(obj.Template))?null:obj.Template;
	//set the content area elements id(s) in the teplate, if not supplied set it to null
	this.templid = (!IsSet(obj.EditableArea) || IsNull(obj.EditableArea))?null:obj.EditableArea;
	//set the EndAction function to execute when print is executed, if not set set it to null
	this.endfunc = (!IsSet(obj.EndAction) || IsNull(obj.EndAction))?null:obj.EndAction;
	this.derivedType = null; // the detrmined type, which may be template, url or id
	this.content = null; // hold the content to print, if template, holds array of ids of editable areas; if url print holds null; if direct print hold innerHTML string to print in the def page
	//Method open to user to start printing
	this.Print = function(url,endfunc,preview){
		 preview = typeof preview == _UND?false:true; 
		//Note - url naming used does not mean the value it takes is only url, it can be array , string content to print, html content, id of an element to print its innercontent
		if(this.printstatus == 'on')return;//if currently in use return back
		if(!IsSet(url) || IsNull(url)){ //if url is not set or is null print the uaer current page
		//alert('aaa');
		  if(!preview){
			window.print() ;
			return;
		  }
		}
		
		if(this.printstatus == 'off'){
			
			this.printstatus = 'on'; //set the printer status to off
			//if an iframe is alredey created remove before creating
			this.url = url; //set the supplied url data (print data) to the global object property
			if(this.closePrint()){
				if(typeof endfunc != "undefined"){ //if user supply an end function during print call, reset the end function to newly supplied
					this.endfunc = endfunc;
				}
			   setTimeout("Printers['"+this.frameID+"'].InitPrint("+preview+")",2000); //solution to browser displaying multiple page dialog
			
			}
		}
		
	}
	
	//function to Initialize print
	this.InitPrint = function(preview){
		if(preview){
			var iframe = _("fr"+this.frameID);
		}else{
		var iframe = document.createElement('iframe');
		}
			//iframe.src = (IsNull(this.templ))?url:this.templ;//if template is not set(i.e a direct page is set), set the iframe src to the page specified in url, but if template is set, set the src to the template path
			//alert(_(this.url).join(";"));
			var src = "" //hold the iframe src
			var brkdwn = this.url.split(":");
			//alert(this.url);
			var itemm = "";
			if(brkdwn.length > 1){
			  itemm = brkdwn[0].Trim();
			  this.url = brkdwn[1];
			}
			
			if(!IsNull(this.templ)){ //if a template is set, use as iframe src
				src = this.templ;
				this.derivedType = 0;//"Template";
			}else if(itemm.toLowerCase() == "id" || itemm.toLowerCase() == "text" ){ //if to print content use the default html page designed in the libray
			//}else if(IsString(this.url) && IsNull(_(this.url)) && this.url.indexOf(".") > -1){ // else if url is set and is a string and not id of any element and contains a dot char, that is caller specified a specific page, print the page
			//alert('enetr');
			this.derivedType = 2;//"Direct";
				src = this.Def;
			
			}else{ // else take it as a url 
			//alert('enetd');
			    	src = this.url;
					//alert(src);
				this.derivedType = 1;//"URL";
			}
			iframe.src = src;
			if(this.derivedType != 1){ //if template specified set print contents
			  if(IsString(this.url)){ //if url is a string
				  var cont = _(this.url);
				  //try get an object out of it(By id or name), if no object is exist set url as the content else set the innerHTML content of the object as the content.
				  //Note- if an array of object is returned use the first one
				  this.content = (IsNull(cont))?url:(IsArray(cont))?cont[0].innerHTML:cont.innerHTML;
			  }else if(IsArray(this.url)){ //if ther parameter (url) send is an array, meaning there are arrays of themplate Ids to fill with values
			   //alert(url.length);
				  if(HasItem(this.url)){ //check if it even contain items
				  
				  this.content = this.url;	//if it contains set the content to the array(url)
				  //Note - Array of content sent must use the ediatble area id as key.
				  }else{ //else if an empty array is sent return without doin any thing
					  return;
				  }
			  }else if(IsObject(this.url)){ //if an object is sent, set the innerHTML of the object as the content
			  
				  this.content = (IsSet(this.url.innerHTML))?this.url.innerHTML:this.url.toString();
			  }else{ //else if invalid parameter is supplied return
				  return;
			  }
			  
			}
		if(!preview){
			iframe.id = this.frameID; //set the id of the newly created iframe to the randomly generated value in the Printer object frameID property
			
			iframe.name = this.frameID; //set the name as the id as well
			iframe.owner = this; //create a new property owner to the iframe element object which will hold the printer object that create it
			iframe.style.position = "absolute"; //make it a css absolute value so that it stands on it own, and it does not disarrange the layout of the html element already designed
			//iframe.style.left = "-3000px";//set the left css property to -3000px to make it not visible to the user
			iframe.style.display = "none";
			/*iframe.style.width = "500px";
			iframe.style.height = "500px";
			iframe.style.zIndex = "5";*/
			iframe.onload = function(){//this function will be triggered when the iframe complets it loading operation
			   this.owner.PerformPrint(this); //call the PerformPrint method of the iframe owner(creator) Printer object
			}
			//iframe.onstalled = function(){alert('start')}
		/*	for(var s in iframe){
			   alert(s + " = " + iframe[s]);	
			}*/
			document.body.appendChild(iframe);	//add the iframe object to the body of the page
		
		}
	}
	
	//perform the print- which is triggered when iframe completly loads the source of file to print or template
	this.PerformPrint = function(ifr){
		
		if(!IsNull(this.templ)){//if template is set
			if(!IsNull(this.templid)){ //if template ids is also set
			//if both the contents supplied and the template id is a string (one template editable area one value)
			//set the the editable area in the template loaded in/by the iframe (giten by the template id supplied) to the content supplied
				if(IsString(this.content) && IsString(this.templid)){
					ifr.contentDocument.getElementById(this.templid).innerHTML = this.content;
				}else if(IsArray(this.content) && IsArray(this.templid)){//if both is an array(i.e-many editable area and many value)
				//loop thruogh the template ids and use it as key to get the corresponding content and set in the template as required
						
						for(var s=0; s<this.templid.length; s++){
							ifr.contentDocument.getElementById(this.templid[s]).innerHTML = this.content[this.templid[s]];
						}
				}else if(IsString(this.content) && IsArray(this.templid)){
					//if content is a string(i.e one) and there are many editable area. set all the editable area to contain the content
					for(var s=0; s<this.templid.length; s++){
							ifr.contentDocument.getElementById(this.templid[s]).innerHTML = this.content;
						}
				}else{//else if one template editable area but many content set the template editable erray to the first item of the array
					ifr.contentDocument.getElementById(this.templid).innerHTML = this.content[0];
				}
			}else{// if no editable area specified and content exist, insert it in the body of the loaded template
				ifr.contentDocument.body.innerHTML = this.content;
			}
		}else if(!IsNull(this.content)){ //if content is set, meaning is a direct print
			ifr.contentDocument.body.innerHTML = this.content;
		}
		
		//make the iframes document window to receive the focus
		//ifr.contentWindow.focus(); 
		//then print it
		ifr.contentWindow.print();
		//alert(ss);
		//run the function that finalizes other operation 
		this.FinishPrint()
	}
	
	//close print - unset the src and remove the iframe
	this.closePrint = function(){
		if(IsSet(this.frameID) && !IsNull(_(this.frameID))){
		//_(this.frameID).src = "";
		document.body.removeChild(_(this.frameID));
		}
		return true;
	}
	
	//finis print
	//finish Printing
	this.FinishPrint = function(){
		//if the end action function is set run it
			if(IsSet(this.endfunc) && !IsNull(this.endfunc)){
				this.endfunc();
			}
		this.printstatus = 'off'; //set Printer status to off
		/*//remove the iframe
		if(IsSet(this.frameID) && !IsNull(_(this.frameID))){
				this.closePrint();
			}*/
	}
	
	//preview option
	this.IsPreview = false;
	this.PreviewObject = null
	this.Preview = function(title,url,endfunc){
		this.IsPreview = true;
		//create the preview page
		this.PreviewObject = document.createElement("div");
		this.PreviewObject.id = "printpreview";
		this.PreviewObject.innerHTML = '<div id="closebx" title="Close" onclick="Printers[\''+this.frameID+'\'].PreviewClose()">'+"times".Icon()+'</div><div id="optionbx"><div id="preview">'+"file-text".Icon()+' PRINT PREVIEW</div><p id="printinfo">'+title+'</p><div class="printdiv longbtn" title="Print" onclick="Printers[\''+this.frameID+'\'].PreviewPrint()">'+"print".Icon()+' PRINT</div><div id="saveasheader">'+"save".Icon()+' SAVE AS</div><div class="printdiv redbtn"  title="Save as PDF" onclick="Printers[\''+this.frameID+'\'].PreviewSave(\'pdf\')">'+"file-pdf-o".Icon()+' PDF</div><div class="printdiv redbtn"  title="Save as Word" onclick="Printers[\''+this.frameID+'\'].PreviewSave(\'word\')">'+"file-word-o".Icon()+' WORD</div><div class="printdiv redbtn"  title="Save as Image" onclick="Printers[\''+this.frameID+'\'].PreviewSave(\'image\')">'+"file-image-o".Icon()+' IMAGE</div><div class="printdiv redbtn"  title="Save as Text" onclick="Printers[\''+this.frameID+'\'].PreviewSave(\'text\')">'+"file-text-o".Icon()+' TEXT</div><div style="clear:both"></div></div><div id="pagebx"><div id="prloading_'+this.frameID+'">'+"cog fa-spin".Icon()+'</div><iframe align="middle" frameborder="0" id="fr_'+this.frameID+'" name="fr'+this.frameID+'" onload="Printers[\''+this.frameID+'\'].PageLoaded(\''+this.frameID+'\')" src=""></iframe></div>';
		document.body.appendChild(this.PreviewObject);
		this.url = url; //set the supplied url data (print data) to the global object property file-text-o
		endfunc();
		this.endfunc = this.PreviewClose;
		this.InitPrint(true); //initialize the ifram object  (url,endfunc,preview)
		//alert(this.frameID)
	}
	
	this.PreviewClose = function(){
		this.PreviewObject.Animate({CSSRule:"opacity:0",Time:600,DoAt:1.0,EndAction:"document.body.removeChild(_('"+this.PreviewObject.id+"'));"});
		this.PreviewObject = null;
	}
	
	this.PreviewPrint = function(){
		if(this.IsPreview){
			this.PerformPrint(_("fr_"+this.frameID))
		}
		
	}
	
	this.PageLoaded = function(id){
		('prloading_'+id).Hide();
	}
	
	this.PreviewSave = function(){
		//MessageBox.ShowText("Currently not available","")
	}
	
	//off the printing operation
	Printers[this.frameID] = this; //add the Printer object to the Currently created printer Objects array
}