(function($) {
	// Verificar suporte Touch
	var hasTouchSupport = (function(){
		if("createTouch" in document){
			return true;
		}
		try{
			var event = document.createEvent("TouchEvent");
			return !!event.initTouchEvent;
		}catch(error){
			return false;
		}
	}());
	
	// Capturar posições
	function getMatrixFromEvent(event, dX, dY){
		if(event.originalEvent.touches && event.originalEvent.touches.length) event = event.originalEvent.touches[0];

		return {x: event.pageX - dX, y: event.pageY - dY};
	};

	// Verificar eventos
	function handleEvent(event){
		
		if(element) {
			switch(event.type) {
				case 'touchstart':
				case 'mousedown':
					onTouchStart(event);
				break;
				case 'touchmove':
				case 'mousemove':
					onTouchMove(event);
				break;
				case 'mouseup':
				case 'touchend':
				case 'touchcancel':
					onTouchEnd(event);
				break;
			}
		}
	};
	
	// Elemento sendo usado
	var element = null;
	
	// Setar a posição inicial do evento
	var position = null;
	
	// Posicao X,Y movido
	var positionCSS = {x: 0, y: 0};
	
	// Variaveis Customizadas
	var posicaoMoveu = {x: 0, y: 0};
	var travado = new Array(null, 0);
	var posicaoMove = {e: 0, d: 0, t: 0, b: 0};
	var videoClicado = null;
	
	// Funcao de Add Touch
	$.fn.touch = function() {
		
		// Verificar se é Touch
		if(hasTouchSupport) {
			// Adicionar eventos ao item a ser movido
			$(this).bind('touchstart', onTouchStart);
			$(this).bind('touchmove', handleEvent);
			$(this).bind('touchend', handleEvent);
			$(this).bind('touchcancel', handleEvent);
		} else {
			$(this).bind('mousedown', onTouchStart);
			$(document).bind('mousemove', handleEvent);
			$(document).bind('mouseup', handleEvent);
			$(document).bind('touchcancel', handleEvent);
		}
	};
	
	/////////////////////////////// Tratar tipos de Eventos
	// Evento START
	function onTouchStart(event){
		// Verificar se o Objeto já esta sendo movido
		if(element != null) return;
		
		// Setar item a ser movido
		element = this;
		
		// Setar posição inicial do movimento
		position = getMatrixFromEvent(event, 0, 0);
		
		// Capturar Posição CSS da tela
		positionCSS.x = $(this).css('margin-left').split('px').join('') - 1 + 1;
		positionCSS.y = $(this).css('margin-top').split('px').join('') - 1 + 1;
		if(positionCSS.x != 0 && !(positionCSS.x > 0) && !(positionCSS.x < 0)) positionCSS.x = 0;
		if(positionCSS.y != 0 && !(positionCSS.y > 0) && !(positionCSS.y < 0)) positionCSS.y = 0;
		
		// Prevenir erro no Ipad
		if($(this).attr('class') != 'resultado') event.preventDefault();
		
		// Verificar clica anterior
		videoClicado =  (event.target == '[object HTMLImageElement]')? event.target : null;
		
		// Customizado
		posicaoMoveu = {x: 0, y: 0};
		travado = new Array(null, 0);
		posicaoMove = {e: 0, d: 0, t: 0, b: 0};
		
		// Verificar em quais angulos não move
		posicaoMove.e = (( (typeof sitePages[paginaAtual][matrixPage.i]) == 'object'
						&& (typeof sitePages[paginaAtual][matrixPage.i][matrixPage.j - 1] == 'object') ) || (
						   (typeof sitePages[paginaAtual][matrixPage.i - 1]) == 'object'
						&& (typeof sitePages[paginaAtual][matrixPage.i - 1][sitePages[paginaAtual][matrixPage.i - 1].length - 1] == 'object')));
		posicaoMove.d = (( (typeof sitePages[paginaAtual][matrixPage.i]) == 'object'
						&& (typeof sitePages[paginaAtual][matrixPage.i][matrixPage.j + 1] == 'object') ) || (
						   (typeof sitePages[paginaAtual][matrixPage.i + 1]) == 'object'
						&& (typeof sitePages[paginaAtual][matrixPage.i + 1][0] == 'object')));
		posicaoMove.t = ((typeof sitePages[paginaAtual][matrixPage.i - 1]) == 'object');
		posicaoMove.b = ((typeof sitePages[paginaAtual][matrixPage.i + 1]) == 'object');
		
		// Verificar se é resultado
		if($(this).attr('class') == 'resultado') {
			travado[0] = 'h';
			posicaoMove.e = true;
			posicaoMove.d = true;
			posicaoMove.t = false;
			posicaoMove.b = false;
		}
	};
	
	// Evento MOVE
	function onTouchMove(event){
		
		// Nova Posicao Gerada
		var newPosicao = getMatrixFromEvent(event, position.x, position.y);
		
		// Customizado
		// Verificar se pode mover pra posição
		if(!posicaoMove.e && newPosicao.x > 0) newPosicao.x = 0;
		if(!posicaoMove.d && newPosicao.x < 0) newPosicao.x = 0;
		if(!posicaoMove.t && newPosicao.y > 0) newPosicao.y = 0;
		if(!posicaoMove.b && newPosicao.y < 0) newPosicao.y = 0;
		
		// Verificar se tem que travar o angulo
		if(travado[0] == null && (newPosicao.x < -10 || newPosicao.x > 10)) {
			travado[1] = 0;
			travado[0] = 'h';
		}
		if(travado[0] == null && (newPosicao.y > 10 || newPosicao.y < -10)) {
			travado[1] = 0;
			travado[0] = 'v';
		}
		
		// Mover!!!!!!!!!!!!!!!!
		if(travado[0] != null) {
			if(travado[0] == 'v')
				newPosicao.x = travado[1];
			else
				newPosicao.y = travado[1];
				
			$(element).css({'margin-left': newPosicao.x, 'margin-top': newPosicao.y});
		}
		
		// Salvar quanto moveu
		posicaoMoveu.x = newPosicao.x;
		posicaoMoveu.y = newPosicao.y;
	};
	
	// Evento FIM
	function onTouchEnd(event){
		// Verificar se é resultado
		if($(element).attr('class') == 'resultado') {
			if(posicaoMoveu.x > 100 || posicaoMoveu.x < -100) {
				if(posicaoMoveu.x > 100) {
					$('.resultado').animate({'margin-left': '+=100px', 'opacity': 0}, 200, function() {
						$('.resultado').css({'margin-left': 0, 'opacity': 1});
						$('.voltar').trigger('click');
					});
				} else {
					$('.resultado').animate({'margin-left': '-=100px', 'opacity': 0}, 200, function() {
						$('.resultado').css({'margin-left': 0, 'opacity': 1});
						$('.voltar').trigger('click');
					});
				}
			} else $('.resultado').animate({'margin-left': '0px'}, 100);
			
			// Setar item a ser movido
			element = null;
			
			return;
		}
			
		// Capturar quanto moveu
		if(posicaoMoveu.x < -100 || posicaoMoveu.x > 100 || posicaoMoveu.y < -100 || posicaoMoveu.y > 100) {
			if(posicaoMoveu.x < -100)
				efeitoTroca('d');
			else if(posicaoMoveu.x > 100)
				efeitoTroca('e');
			else if(posicaoMoveu.y < -100)
				efeitoTroca('b');
			else if(posicaoMoveu.y > 100)
				efeitoTroca('t');
		
			// Eveitar Abrir Video
			$(event.target).attr('onclick', 'return false;');
		} else {
			// Zerar Posição
			$(element).animate({'margin-left': '0px', 'margin-top': '0px'}, 'fast');
			
			$(event.target).trigger('click');
		}
		
		// Setar item a ser movido
		element = null;
	};
})(jQuery);
