$.operVisorTiff = function( options, visor ) {
	this.zoom = 100;
	this.x = 0;
	this.y = 0;
	this.settings = $.extend({}, $.fn.visorTIFF.defaults, options);
	this.total = 0;
	this.actual = visor;
	this.pagina = 0;
	this.canvas_actual = undefined;
	this.d_and_d = false;
	this.moviendo = false;
	
	this.init();
	
};


$.extend($.operVisorTiff, {
	prototype: {
		
		init: function() {
			
			this.inicializa();
			this.eventos();
		},
		inicializa: function(){
			
			
			var principal = this;
			this.canvas = document.createElement("canvas");
			this.canvas.width = $('.panel-body',this.actual).width();
			var windowHeight = $(window).height() - $('#header').height()-150;
			var posicion = $('.panel-body').position(); 
			var alto = windowHeight - posicion.top - 50;
			this.canvas.height = alto;
			
			$('.panel-body',this.actual).append(this.canvas);

			
			
			
			
			Tiff.initialize({TOTAL_MEMORY: 16777216 * 10});
			  var xhr = new XMLHttpRequest();
			  xhr.open('GET', this.settings.fichero);
			  xhr.responseType = 'arraybuffer';
			  xhr.onload = function (e) {
			    var buffer = xhr.response;
			    var tiff = new Tiff({buffer: buffer});
			    principal.paginas = tiff;
			    principal.total = tiff.countDirectory();
			    principal.actualizaPagina();
			    
			    
			  };
			  xhr.send();
			
			
		},
		actualizaPagina: function(){
			this.paginas.setDirectory(this.pagina);
			this.canvas_actual = this.paginas.toCanvas();
			this.botonesSiguienteAnterior();
			
			$('.info_vista',this.actual).text('Página '+(this.pagina+1) + " de "+ (this.total));
			
			this.dibuja();
		},
		eventos: function(){
			var principal = this
			$(this.actual).disableSelection();
			$('.siguiente',this.actual).click(function(){
				
				principal.siguiente();
				return false;
			});
			$('.anterior',this.actual).click(function(){
				principal.anterior();
				return false;
			});
			
			
			$('.ampliar',this.actual).click(function(){
				principal.ampliar();
			});
			
			$('.reducir',this.actual).click(function(){
				principal.reducir();
			});
			
			$('.imprimir',this.actual).click(function(){
				principal.imprimir();
				return false;
			});
			
			
			
			if(principal.d_and_d){
				
				$(this.canvas).mousemove(function(e){
					principal.x = e.pageX - $(this).offset().left;
			        principal.y = e.pageY - $(this).offset().top;
			        principal.dibuja();
					
				});
			}else{
				
				$(this.canvas).mousedown(function(event){
					principal.moviendo = true;
					principal.ini_x = event.pageX;
					principal.ini_y = event.pageY;
					principal.tmp_x = principal.x;
					principal.tmp_y = principal.y;
				});
				
				$('body').mousemove(function(event){
					if(principal.moviendo){
						principal.x = principal.tmp_x - (principal.ini_x - event.pageX);
						principal.y = principal.tmp_y - (principal.ini_y - event.pageY);
						
						principal.dibuja();
					}			});
				
				$('body').mouseup(function(event){
					if(principal.moviendo){
						principal.moviendo = false;
						principal.x = principal.tmp_x - (principal.ini_x - event.pageX);
						principal.y = principal.tmp_y - (principal.ini_y - event.pageY);
						
						principal.dibuja();
					}
				});	
			}
			
			
			 $(this.canvas).bind('DOMMouseScroll', function(e){
			     if(e.originalEvent.detail > 0) {
			    	 principal.ampliar();
			     }else {
			    	 principal.reducir();
			     }
			     return false;
			 });
			 
			 $(this.canvas).bind('mousewheel', function(e){
			     if(e.originalEvent.wheelDelta < 0) {
			    	 principal.ampliar();
			     }else {
			    	 principal.reducir();
			     }
			     return false;
			 });
			
			 
		},
		imprimir: function(){
			
			
			var canvas = this.canvas_actual;
			
			 var dataUrl = canvas.toDataURL(); //attempt to save base64 string to server using this var  
			    var windowContent = '<!DOCTYPE html>';
			    windowContent += '<html>'
			    windowContent += '<head><title>Print canvas</title></head>';
			    windowContent += '<body>'
			    windowContent += '<img style="width:100%" src="' + dataUrl + '">';
			    windowContent += '</body>';
			    windowContent += '</html>';
			    var printWin = window.open('','','width=680,height=0');
			    printWin.document.open();
			    printWin.document.write(windowContent);
			    printWin.document.close();
			    printWin.focus();
			    printWin.print();
			    printWin.close();
		},
		ampliar: function(){
			this.zoom += 10;
			this.dibuja();
		},
		reducir: function(){
			this.zoom -= 10;
			this.dibuja();
		},
		siguiente: function(){
			this.pagina++
			if(this.pagina >= this.total){
				this.pagina = this.total-1;
			}
			
			this.actualizaPagina();
				
		},
		anterior: function(){
			this.pagina -=1;
			if(this.pagina < 0){
				this.pagina = 0;
			}
			this.actualizaPagina();
		},
		botonesSiguienteAnterior: function(){
			
			if(this.pagina == 0){
				$('.anterior',this.actual).addClass('disabled');
			}else{
				$('.anterior',this.actual).removeClass('disabled');
			}
			
			if(this.pagina+1 == this.total){
				$('.siguiente',this.actual).addClass('disabled');
			}else{
				$('.siguiente',this.actual).removeClass('disabled');
			}
			
		},
		dibuja: function(){
			
			var context = this.canvas.getContext('2d');
			
			context.clearRect(0,0, this.canvas.width, this.canvas.height);
			
			
			
			var canvas = this.canvas_actual;
			

			var x = 0;
			var y = 0;
			
			var inicial_x = this.x;
			var inicial_y = this.y;
			
			
			var ancho = this.canvas.width;
			var alto = this.canvas.height
			
			var ancho_tif = canvas.width;
			var alto_tif = canvas.height;
			
			var ancho_render = ancho;
			var alto_render = alto;
			
			
			
			
			alto_render = ancho * alto_tif /  ancho_tif;
			
			
			ancho_render *= this.zoom /100;
			alto_render *= this.zoom /100;
			
			
			if((ancho_render < ancho) && (alto_render < alto)){
				ancho_render = ancho;
				alto_render = ancho * alto_tif /  ancho_tif;
				
				var zoomx =  ancho /ancho_render;
				var zoomy = alto/ alto_render;
				
				
				if(zoomx > zoomy){
					this.zoom = zoomy*100;
				}else{
					this.zoom = zoomx*100;
				}
				
				
				
				
				ancho_render = ancho * this.zoom /100;
				alto_render *= this.zoom /100;
				
				
			}
			
			
			
			
			if(this.d_and_d){
				
				y =  parseInt((alto - alto_render) * (inicial_y / alto ));
				
				
				if(this.zoom > 100){
					
					x =  parseInt((ancho - ancho_render) * (inicial_x / ancho ));
				}
				
				
			}else{
				x = this.x;
				y = this.y;
			}
			
			
			if(ancho > ancho_render){
				x = (ancho - ancho_render)/2;
			}else if(x >0){
				x = 0;
			}else if((ancho - ancho_render) > x){
				x = ancho - ancho_render			
			}
				
			if(alto > alto_render){
				y = (alto - alto_render)/2;
			}else if(y >0){
				y = 0;
			}else if((alto - alto_render) > y){
				
				y = alto - alto_render;			
			}else{
				
			}
			if(!this.moviendo){
				this.x = x;
				this.y = y;
			}
			
			
			
			
			//console.log(canvas.width);
			//console.log(canvas.height);
			
			context.drawImage(canvas, x, y, ancho_render, alto_render);
			
			
		}
	}
});



$.fn.visorTIFF = function(options){  
     if (!this.length) {
		options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
		return;
	}
    
    var visor = $.data(this[0], 'visor');
	if ( visor ) {
		return visor;
	}
    
	visor = new $.operVisorTiff( options, this[0] );
	$.data(this[0], 'visor', visor); 
	return visor;
    
}; 




$.fn.visorTIFF.defaults = {  
	    alto: 300,
	    titulo: 'Titulo del documento',
	    parametros : {}
	};  
