'use strict';

/**
 *@author Felipe Vargas South RIC
 *A module representing a control that join with a line two divs
 *@Module sgJoinLine
 *@Version 2.0 supporting IPAD
 */
define(['jquery', 'jquery-connectingLine','sgSound'], function($,jqConect,sgSound) {
	var app = {};
	app.init = function() {

		var element = $("[data-sg-id='elem-join-line']");

		element.each(function(){
			var $me=$(this);

			$me.css({
				width: $me.attr('data-sg-width')?  $me.attr('data-sg-width'): '100%',
				height: $me.attr('data-sg-height')?  $me.attr('data-sg-height'): '586px',//584
				position: 'relative'
			}); 

			var nodes1 = $me.find("[data-sg-id='item-line-init']").addClass('node1');
			var nodes2 = $me.find("[data-sg-id='item-line-target']").addClass('node2');

			nodes1.css({position: 'absolute'}); 
			nodes2.css({position: 'absolute'}); 

			var sgFunctionIncorrect = $me.attr("data-sg-incorrect");
			var sgFunctionCorrect = $me.attr("data-sg-correct");


			var mySVG = $me.connectSVG();

			/*that boolean is used for knowing in the mouse events if the node1 was pressed before and keep pressed */
			var pressDownBefore = false;

			//that boolean is used for knowing if the node2 has the mouse over
			var isOverNode2 = false;

			$me.find(".node1").bind("mousedown touchbegin touchstart", function(e) {
				restarSelection();
				$(this).addClass("active1");
				pressDownBefore = true;
				mySVG.setSelectDivInit($(this));
			});

			

			$me.find(".node1").bind(" mousemove", function(e) {
				return false;
			});
			$me.find(".node2").bind("mouseover", function() {
				if (pressDownBefore) {
					$(this).addClass("active2");
				}
			});

			var contador = 0;

			mySVG.bind("mousedown touchbegin touchstart", function(e) {
				var widthTarget = e.target.offsetWidth/2;
				var heightTarget = e.target.offsetHeight/2;

				mySVG.positionX = e.target.offsetLeft + widthTarget;
				mySVG.positionY = e.target.offsetTop + heightTarget;

			}).bind("mouseup touchend", function(e) {


				var offsetCanvParent = mySVG.offsetParent().offset();
				var xpos = getOffsetX(e);
				var ypos = getOffsetY(e);

				var targetItem = isBetweenSomeTarget(xpos, ypos, e);

				// if the mouse or touch is over a target item do this
				if (targetItem) {
					validateTargetInit(targetItem);
				}

				if (mySVG.selected) {
					// console.log("canvas  mouseup borrar ");
					restarSelection();
				}
				mySVG.selected = false;

			}).bind("mousemove touchmove", function(e) {

				e.preventDefault();

				//$(".rightItem1").append($(e.target).attr("data-sg-id"));
				if ($(e.target).attr("data-sg-id") == "item-line-target") {
					return;
				}

				if (mySVG.selected) {

					/*optimize the call for the canvas drawing lines, will prevent that the event is trigger always*/
					if (contador < 10) {
						contador++;
						return;
					}
					contador = 0;
					contador++;
					$("#stage").attr("style", "");
					mySVG.redrawLines();
					$(window).resize();

					
					var xpos = getOffsetX(e);
					var ypos = getOffsetY(e);

					
					mySVG.mousePositionLine(mySVG.positionX, mySVG.positionY, xpos, ypos);
				}
			}).bind("mouseleave",function(){
				restarSelection();
			});
			/*
				do the space in there initial stated
			*/
			function restarSelection() {
				$me.find(".node1").removeClass("active1");
				$me.find(".node2").removeClass("active2");
				drawCanvasLinesOnly();
			}

			/*
				that function draw all the line and erase the line lunched by the mouse
			*/
			function drawCanvasLinesOnly() {
				pressDownBefore = false;
				mySVG.removeSelectDivInit();
				$("#stage").attr("style", "");
				mySVG.redrawLines();
				$(window).resize();
			}
			/*
				prevent the drag from the items in the div 
			*/
			window.ondragstart = function() {
				return false;
			}
			/*
				clear all the events mouse from the object	
			*/
			function clearEvents(object) {
				object.unbind("mousedown touchbegin  mouseover mouseleave mouseup touchend ");
			}
			// get the correct y mouse position in according relative to the canvas 
			function getOffsetX(e) {
					var rect = mySVG.get(0).getBoundingClientRect();
					return (e.pageX- rect.left)*scaleRectDiv();
			}
			// get the correct y mouse position in according relative to the canvas 
			function getOffsetY(e) {
				
					var rect = mySVG.get(0).getBoundingClientRect();
					return (e.pageY- rect.top)*scaleRectDiv();
				// }
			}

			function scaleRectDiv(){
				var stageI = $("#stage");
	        	var rect = stageI.get(0).getBoundingClientRect();
	        	var scalation= stageI.width()/rect.width;
	        	return scalation;
			}

			// search if there are some target element inside the position mouse
			function isBetweenSomeTarget(xpos, ypos, e) {


				if (!pressDownBefore) {
					return undefined;
				}

				if ($(e.target).attr("data-sg-id") == "item-line-target") {
					return e.target;
				}
				for (var i = 0; i < nodes2.length; i++) {
					var nod = nodes2.get(i);
					var x = nod.offsetLeft;
					var y = nod.offsetTop;

					if (xpos > x && xpos < x + 50 && ypos > y && ypos < y + 50) {
						return nod;
					}
				}
				return undefined;
			}


			// validate is the init element join with the target element
			function validateTargetInit(nod) {

				
				mySVG.removeSelectDivInit();
				$me.find(".node2").removeClass("active2");
				

				var nodeInit=$me.find(".active1");
				var nodeEnd=$me.find(nod).addClass("active2");


				var keyInit = nodeInit.attr('data-sg-target-key');
				var keyEnd = nodeEnd.attr('data-sg-key');
				
				if (keyInit == keyEnd) {
					clearEvents($me.find(".active1"));
					clearEvents($me.find(nod));

					$("#stage").attr("style", "");
					mySVG.drawLine({
						left_node: '.active1',
						right_node: '.active2',
						horizantal_gap: 20,
						error: true,
						width: 3,
						color: '#' + Math.floor(Math.random() * 16777215).toString(16)
					});
					mySVG.redrawLines();


					$me.find(".node1").removeClass("active1");
					$me.find(".node2").removeClass("active2");
					$(window).resize();

					pressDownBefore = false;

					sgSound.sg_sound("success");

					// eval(sgFunctionCorrect);

					var fn=window[sgFunctionCorrect];

					if(typeof fn=='function'){
						fn.apply(null, [nodeInit, nodeEnd]);
					}else{
						if(sgFunctionCorrect == ""){
							sgSound.sg_sound("success");
						}else{
							eval(sgFunctionCorrect);
						}
					}

				} else {
					
					var fn=window[sgFunctionIncorrect];
					
					if(typeof fn=='function'){
						
						fn.apply(null, [nodeInit, nodeEnd]);
					}else{
						eval(sgFunctionIncorrect);
					}
					restarSelection();
				}
			}
		});
	}



	return app;

});