/*
Copyright (c) 2009, jasuca.com
Code licensed under the BSD Licence
version: 1.0.0
*/

YAHOO.namespace ("jasuca");

var Dom = YAHOO.util.Dom; //, menu, projects, design, photo, contact, lang;
var menuArray = new Array();

YAHOO.jasuca.DDRegion = function(id, sGroup, config) {
	this.posArray = menuArray.length
	menuArray.push(this);

	this.cont = config.cont;
	this.startPos = Dom.getXY(id);
	this.lastXY = null;
	this.lastPosXY = null;
	this.region = Dom.getRegion(this.getEl());
	YAHOO.jasuca.DDRegion.superclass.constructor.apply(this, arguments);
};

YAHOO.extend(YAHOO.jasuca.DDRegion, YAHOO.util.DD, {
	cont: null,
	init: function() {
		//Call the parent's init method
		YAHOO.jasuca.DDRegion.superclass.init.apply(this, arguments);
		this.initConstraints();

		Event.on(window, 'resize', function() {
			this.initConstraints();
			}, this, true);
	},
	computeConstrains: function() {
		//Get the top, right, bottom and left positions
		var region = Dom.getRegion(this.cont);

		//Get the element we are working on
		var el = this.getEl();

		//Get the xy position of it
		var xy = Dom.getXY(el);

		//Get the width and height
		var width = parseInt(Dom.getStyle(el, 'width'), 10);
		var height = parseInt(Dom.getStyle(el, 'height'), 10);

		//Set left to x minus left
		var left = xy[0] - region.left;

		//Set right to right minus x minus width
		var right = region.right - xy[0] - width;

		//Set top to y minus top
		var top = xy[1] - region.top;

		//Set bottom to bottom minus y minus height
		var bottom = region.bottom - xy[1] - height;
	
	
		//Check the element right
		var parentTop = top, parentBottom = bottom, childTop = top, childBottom = bottom;
	
		if (this.posArray != 0){
			parentTop = Dom.getXY(menuArray[this.posArray-1].id)[1];
			var parentH = parseInt(Dom.getStyle(menuArray[this.posArray-1].id, 'height'), 10);
			parentBottom = parentTop+parentH;
		
			parentTop = Math.abs(parentTop-(xy[1]+height));
			parentBottom = Math.abs(parentBottom-xy[1]);
			//console.debug("Parent", parentTop, parentBottom);
		
		}
		if (this.posArray != menuArray.length-1){
			childTop = Dom.getXY(menuArray[this.posArray+1].id)[1];
			var childH = parseInt(Dom.getStyle(menuArray[this.posArray+1].id, 'height'), 10);
			childBottom = childTop+childH;
		
			childTop = Math.abs(childTop-(xy[1]+height));
			childBottom = Math.abs(childBottom-xy[1]);
			//console.debug("Child", childTop, childBottom);

		}
	
	
		//Max top
		/*
		top = Math.min(parentTop, childTop);
		bottom = Math.min(parentBottom, childBottom);
		top -=30
		bottom -= 30
		console.debug("TP", top, bottom);
		*/
		return new Array(left, right, top, bottom);
	},
	      initConstraints: function() {
          
		var constrains = this.computeConstrains();
		var left = constrains[0];
		var right = constrains[1];
		var top = constrains[2];
		var bottom = constrains[3];
	
	          //Set the constraints based on the above calculations
		this.resetConstraints();
	          this.setXConstraint(left, right);//to only move a bit up or down
	          this.setYConstraint(top, bottom);
	      },
	constrainMove: function(xy){
		var constrains = this.computeConstrains();
		var left = constrains[0];
		var right = constrains[1];
		var top = constrains[2];
		var bottom = constrains[3];
	
		//xy[0] = Math.min(Math.max(xy[0], left),right);
		//xy[1] = Math.min(Math.max(xy[1], top),bottom);
	
		return xy;
	},
	propagateMove: function(xy, shouldMove){
		//xy[0] = xy[0]*0.95;
		//xy[1] = xy[1]*0.95;
		//Move
		if (shouldMove == 1){
			var el = this.getEl();
			var newPos =  Dom.getXY(el);
			newPos[0] += xy[0];
			newPos[1] += xy[1];
		
			Dom.setXY(el, newPos);
			//console.log(this.region,Dom.getRegion(el));
			this.region = Dom.getRegion(el);
		}
	
		//Propagate
		if (this.posArray != menuArray.length-1) {
			child = menuArray[this.posArray+1];
		
			//Check if this move is necesary
			var regionCh = Dom.getRegion(child.getEl());
			var	regionPa = this.region
		
			//console.log("PA",regionPa);
		
			if (!(regionPa.top>regionCh.bottom-30 || regionPa.bottom<regionCh.top+30)){xy[1] = 0;}
		
			//Propagate
			child.propagateMove(xy,1);
		}
	},
	onDrag: function(e) {
	
		//Update the position
		this.region = Dom.getRegion(this.getEl());
	
		// Keep track of the direction of the drag for use during onDragOver 
		var xy = new Array(Event.getPageX(e),Event.getPageY(e));
	
		if (this.lastXY == null){
			incXY = new Array(0,0);
		}
		else {
			incXY = new Array(xy[0]-this.lastXY[0],xy[1]-this.lastXY[1]);
		}
		//Check if it is moved
		var posXY =  Dom.getXY(this.getEl());
		if (this.lastPosXY[0] == this.region.x){
			incXY[0] = 0;
		}
		if (this.lastPosXY[1] == this.region.y){
			incXY[1] = 0;
		}
	
		//Reset vals
		this.lastXY = xy;
		this.lastPosXY =  new Array(this.region.x,this.region.y);
	
		this.propagateMove(incXY, 0);
	
	},
	startDrag: function(x,y) {
		this.wantToClick = 0;
		this.initConstraints();
		this.lastPosXY =  Dom.getXY(this.getEl());
		var clickEl = this.getEl();
		Dom.setStyle(clickEl, "opacity", 0.5);
		Dom.setStyle(clickEl, "cursor", "move"); 
	},
	endDrag: function(e) {
		this.lastXY = null;
		this.returnParenAll();
		var clickEl = this.getEl();
		Dom.setStyle(clickEl, "opacity", 1.0);
		Dom.setStyle(clickEl, "cursor", "pointer");
	},
	onMouseDown: function(e) {
		this.wantToClick = 1;
	},
	onMouseUp: function(e) {
		if (this.wantToClick == 1)
		{	
			//Is the lang?
			if (this.id == "b_lang") {
				//change the language of all
			
				var acumulateMove = 0;
				var lastW = 0;
			
			
				menuLangPointer=(menuLangPointer+1)%3;
				
				for (elemPos in menuArray)
				{
					elementExt = menuArray[elemPos].getEl();
					element = document.getElementById(menuArray[elemPos].id+"_t");
					elementPos = Dom.getXY(elementExt);
					region = Dom.getRegion(elementExt);
					if (elemPos != 0) {
						acumulateMove+=region.width/2 + lastW/2;
						elementPos[0]-=acumulateMove;
					}
					lastW = region.width;
				
				
					//move to rigth
					var anim = new YAHOO.util.Motion(elementExt, {
						points: { to: elementPos},
						element: {name: element, newText: menuLang[menuLangPointer][elemPos]}
						}, 0.3, YAHOO.util.Easing.easeOut);

					animComp = function(){
						menuArray[0].returnParenAll();
						newText = this.attributes.element.newText;
						this.attributes.element.name.innerHTML = new String(newText);
						
						
						}
					anim.onComplete.subscribe(animComp);
					anim.animate();
					
				}
				
				this.changeContainer(menuPointer, menuLangPointer);
			
			}
			else{
				//Undisplay all the elements
				$(".b_click").css('display', 'none');
				//Display the cliked one
				id_element = "#"+this.id+" > * > .b_click";
				$(id_element).css('display', 'block');

				this.changeContainer(this.posArray, menuLangPointer);
			
				menuPointer = this.posArray;
				
			}
		}
	},
	changeContainer: function(menu_id, lang_id){
		//Get request
		var lang_name = "l_eng";
		if (lang_id == 0){
			lang_name = "l_eng"
		}
		else if (lang_id == 1){
			lang_name = "l_cat"
		}
		else if(lang_id == 2){
			lang_name = "l_esp"
		}
		
		$.get("return_menu.php", { id: menu_id, lang: lang_name },
		  function(data){
			var div = document.getElementById('body_container');
			div.innerHTML = data;
			pageTracker._trackPageview("/?id="+menu_id+"&lang="+lang_name );
		  });
		
	},
	changeContainer2: function(menu_id, lang_id){
		//Get request
		var lang_name = "l_eng";
		if (lang_id == 0){
			lang_name = "l_eng"
		}
		else if (lang_id == 1){
			lang_name = "l_cat"
		}
		else if(lang_id == 2){
			lang_name = "l_esp"
		}
		
		var sUrl = "return_menu.php?id="+menu_id+"&lang="+lang_name;
		
		
		var div = document.getElementById('body_container');
		var handleSuccess = function(o){
			if(o.responseText !== undefined){
				div.innerHTML = o.responseText;
			}
		}

		var handleFailure = function(o){
			if(o.responseText !== undefined){
				div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
				div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
				div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
			}
		}

		var callback =
		{
		  success:handleSuccess,
		  failure: handleFailure,
		  argument: { }
		};
	
		var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
	},
	obtainBoxPositions: function(){
		positions = new Array();
		for (elem in menuArray)
		{
			xy = Dom.getXY(menuArray[elem].getEl());
			positions.push(xy);
		}
		console.log(positions);
		return positions;
	},
	returnParentOne: function(futureParentPos, duration){
		if (this.posArray != 0) {
		
			parent = menuArray[this.posArray-1].id;
			var x = 0;
			var y = 0;
		
			if (futureParentPos != null) {
				x = futureParentPos[0];
				y = futureParentPos[1];
			}
			else{
				x = Dom.getXY(parent)[0];
				y = Dom.getXY(parent)[1];
			}
		
			//The X
			var width = parseInt(Dom.getStyle(parent, 'width'), 10);
			x+=width;
		
			//The Y
			var  height= parseInt(Dom.getStyle(parent, 'height'), 10);
			var top = y+30;
			var bottom = y+height-30;
		
			var el = this.getEl();
			newPos = Dom.getXY(el);
			newPos[0] = x;
		
			var heightEl = parseInt(Dom.getStyle(el, 'height'), 10);
			newPos[1] = Math.min(Math.max(newPos[1], top-heightEl), bottom);
		
			new YAHOO.util.Motion(
				el, { 
						points: { 
							to: newPos
						}
					}, 
					duration, 
					YAHOO.util.Easing.easeOut 
				).animate();
		}
		else{
			parent = menuArray[this.posArray].id;
			newPos = Dom.getXY(parent);
		
		}
		return newPos;
	},

	returnParenAll: function (){
		addToX = null;
		var duration = 0.3;
		for (firstChild=this.posArray;firstChild<menuArray.length;firstChild+=1)
		{
			addToX = menuArray[firstChild].returnParentOne(addToX, duration);
			duration += 0.1;
		}
	}
});
