(function($, window, document, undefined) {
	var plugin = {
		name: 'semcadVisor'
	};
    
	function SemcadVisor(element, options) {
		this.context = element;
		this.$context = $(element);
		this.options = $.extend({}, $[plugin.name].defaults, options);
		this.init();
	}
    
	SemcadVisor.prototype = {
		init: function() {
			this.scrollPane = this.$context.jScrollPane({
				maintainPosition: true,
				autoReinitialise: true,
				hijackInternalLinks: true,
				showArrows: true,
				verticalDragMinHeight: 35,
				verticalDragMaxHeight: 35,
				horizontalDragMinWidth: 35,
				horizontalDragMaxWidth: 35,
				contentWidth: '0px'
			});

		// SELECTION
			$this = this;
			this.selectionStatus = 'none';
			this.selectionColor = $this.options.colors[0]; // TODO: Colors without css
			rangy.init();
			$this.highlighter = rangy.createHighlighter();
	        
	        // RESIZE CONTENT
			$this.originalContentHeight = $(window).height() - 160;
	        
			var resizeContent = function() {
	        		var sideHeight = $('#sidebar').height();

				if (sideHeight > $this.originalContentHeight) {
					$('#content').height(sideHeight);
					$('#content-scroll').height(sideHeight);
				} else {
					$('#content').height($this.originalContentHeight);
					$('#content-scroll').height($this.originalContentHeight);
				}
				
				var api = $this.scrollPane.data('jsp');
				api.reinitialise();
			}
		
			$('.panel-collapse').on('shown.bs.collapse hidden.bs.collapse', function() {
				resizeContent();
			});

			resizeContent();
			
			$(window).resize(function(){
				$this.originalContentHeight = $(window).height() - 160;
				resizeContent();
			});
			
	
			for (var i = 0; i < $this.options.colors.length; i++) {
				var color = $this.options.colors[i];
$this.highlighter.addClassApplier(rangy.createClassApplier("highlight" + color, {
					ignoreWhiteSpace: true,
					tagNames: ["span", "a"]
		        	}));
			}
			
			$this.$context.bind('mouseup', function() {
				if ($this.selectionStatus == 'select') {
//$this.highlighter.highlightSelection("highlight" + $this.selectionColor, null, 'content-scroll');
$this.highlighter.highlightSelection("highlight" + $this.selectionColor, {containerElementId: rangy.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.id});
					rangy.getSelection().removeAllRanges();
					if($this.options.updateOnEvents) $this.sendStatusUpdate();
				}
			});
			
//			$('.highlight').live('mousedown', function() {
			$("span[class^='highlight']").live('mousedown', function() {
				$(this).removeClass('removeHighlight');
				$this.removeHighlight(this);
				if($this.options.updateOnEvents) $this.sendStatusUpdate()
			});
			
			// COLLAPSABLES 
			$('.collapser').live('click', function() {
				if ($this.selectionStatus == 'none') {
					$(this).next('.collapsable').toggle();	
					$(this).toggleClass('icon-mini-flecha-up');
					$(this).toggleClass('icon-mini-flecha-down');
					if($this.options.updateOnEvents) $this.sendStatusUpdate();
				}
			});
			
			// STATUS
			$this.setStatus();

			if ($this.options.timeOutUpdate) {
				window.setInterval(function() {if($this.options.updateOnEvents) $this.sendStatusUpdate();}, $this.options.timeOutUpdate);
			}
			
			$( window ).unload(function() {
			        if($this.options.updateOnEvents) $this.sendStatusUpdate();
			});
		},
 
        	collapseAllImages: function() {
        		$('.ImgBorder.collapsable').hide();
        		$('.Image').children('.collapser').removeClass('icon-mini-flecha-down').addClass('icon-mini-flecha-up');
			if(this.options.updateOnEvents) this.sendStatusUpdate()
		},
        
		expandAllImages: function() {
        		$('.ImgBorder.collapsable').show();
        		$('.Image').children('.collapser').removeClass('icon-mini-flecha-up').addClass('icon-mini-flecha-down');
			if(this.options.updateOnEvents) this.sendStatusUpdate()
        	},
        
		collapseAllCharts: function() {
        		$('table.collapsable').hide();
        		$('.table').children('.collapser').removeClass('icon-mini-flecha-down').addClass('icon-mini-flecha-up');
			if(this.options.updateOnEvents) this.sendStatusUpdate()
        	},
        
		expandAllCharts: function() {
        		$('table.collapsable').show();
        		$('.table').children('.collapser').removeClass('icon-mini-flecha-up').addClass('icon-mini-flecha-down');
			if(this.options.updateOnEvents) this.sendStatusUpdate()
        	},
        
        removeHighlight: function(element) {
        	if ($this.selectionStatus == 'remove'){
			var highlight = this.highlighter.getHighlightForElement(element);
			this.highlighter.removeHighlights( [highlight] );
	            	if(this.options.updateOnEvents) this.sendStatusUpdate()
	            	return false;
		}
        },
        
        setHighlightColor: function(i) {
        	this.selectionColor = this.options.colors[i];
        },
        
        setHighlightColorByName: function(color) {// TODO: validate colors
        	this.selectionColor = color;
        },
        
        getAvailableColors: function() {
        	return this.options.colors;
        },
        
        setHighlightStatus: function(status) {
        	this.selectionStatus = status;
        },
        
        setStatusHighlight: function() {
//			$('.highlight').removeClass('removeHighlight');
$("#"+parentContainerId).unbind("mouseup",CurrentSelection.Selector.mouseup); 
document.getElementById("reader-content").style.cursor='default';

$("span[class^='highlight']").removeClass('removeHighlight');
        	this.selectionStatus = 'select';
        },
        
        setStatusRemove: function() {
//			$('.highlight').addClass('removeHighlight');
$("#"+parentContainerId).unbind("mouseup",CurrentSelection.Selector.mouseup); 
document.getElementById("reader-content").style.cursor='default';

$("span[class^='highlight']").addClass('removeHighlight');
        	this.selectionStatus = 'remove';
        },
        
        setStatusNone: function() {
//			$('.highlight').removeClass('removeHighlight');
$("span[class^='highlight']").removeClass('removeHighlight');
        	this.selectionStatus = 'none';

		$("#"+parentContainerId).unbind("mouseup",CurrentSelection.Selector.mouseup); 
        },
        
        getHighlightStatus: function() {
        	return this.selectionStatus;
        },
        
        getCollapsedItems: function () {
        	var items = [];
        	$('.collapsable').each(function () {
        		var that = $(this);
        		if (!that.is(':visible')) {
        			items.push(that.attr('id'));
        		}
        	});
        	return items;
        },
        
        getCurrentStatus: function () {
			var api = this.scrollPane.data('jsp');
			var status;
			if (this.options.startStatus) {
				status = this.options.startStatus;
				this.options.startStatus = null;
			} else {
				status = {
					highlights: this.highlighter.serialize(),
					currentPosition: api.getContentPositionY(),
					collapsedItems: this.getCollapsedItems()
				}
			}
			return status;
	},

	getCurrentPosition: function () {
			var api = this.scrollPane.data('jsp');
			verticalpos = api.getContentPositionY();
			return;
	},

	setCurrentPosition: function () {
			var api = this.scrollPane.data('jsp');
			api.scrollToY(verticalpos);
	},
		
	setStatus: function() {
			var status = this.getCurrentStatus();
			var api = this.scrollPane.data('jsp');
			if (this.options.startAtBookmark) {
				$('#index-link-' + this.options.startAtBookmark).click();
			} else if (status.currentPosition) {
				api.scrollToY(status.currentPosition);
			}
			if (status.highlights) {
				this.highlighter.deserialize(status.highlights);
			}
			
			if (status.collapsedItems && status.collapsedItems.length > 0) {
				for(var i = 0; i < status.collapsedItems.length; i++) {
					var collapsableItem = $('#' + status.collapsedItems[i]);
					collapsableItem.hide();
					collapsableItem.prev().removeClass("icon-mini-flecha-down").addClass("icon-mini-flecha-up");
				}
			}
	},
		
	sendStatusUpdate: function() {
//alert("HOLA");
			$this = this;
			if ($this.options.updaterUrl) {
				var estado=$.ajax({
					url: $this.options.updaterUrl,
					data: {
						'article': $this.options.article,
//						'version': 0,
						'version': $this.options.version,
						'status': JSON.stringify($this.getCurrentStatus())
					},
					type: 'POST',
timeout: 300000,
					success: function(data, textStatus) {
//alert("Exito");
					}
				})

				.fail(function(jqXHR, textStatus) {
					if (!$this.options.silent) {
						alert( "Request failed: " + textStatus );
					}
					if (console && console.debug) console.debug(jqXHR);
				});
/*				estado.done(function() {
					alert( "Done");
				});
*/
/*
				estado.fail(function() {
					alert( "FAILED");
				});
*/
/*				estado.always(function() {
					alert( "SIEMPRE");
				});
*/
			}
//alert(JSON.stringify($this.getCurrentStatus()));
	}
}
    
$.fn.getSemcadVisor = function() {
	return this.data(plugin.name);
};

$.fn[plugin.name] = function(options) {
	return this.each(function() {
		if (!$.data(this, plugin.name)) {
        		$.data(this, plugin.name, new SemcadVisor(this, options));
		}
	});
};
    
    

$.semcadVisor = {
	defaults: {
		colors: ['Yellow'],
		startStatus: undefined,
		startAtBookmark: undefined,
		updaterUrl: undefined,
		article: undefined,
		version: undefined,
		silent: false,
	updateOnEvents: true
	}
};

})(jQuery, window, document);