var $ = YAHOO.util.Dom.get;
var Dom = YAHOO.util.Dom;
var CustomEvent = YAHOO.util.CustomEvent;
var Event = YAHOO.util.Event;
var Connect = YAHOO.util.Connect;

var Profile = function(config){
	this.config = config;
}

Profile.prototype = {
	
	widgets: [],
	
	init: function(){
		
		this.mainPic = new Profile.MainPicture(this.config);
		this.treat = new Profile.Treat(this.config.treatBoxId, treatData, this.mainPic);
		this.gifts = new Profile.GiftBoxList(giftData, this.mainPic);
		
		Event.addListener('pikadateHeart', 'mouseover', this.zoomInPikadate, this, true);
		Event.addListener('pikadateBigPic', 'mouseout', this.zoomOutPikadate, this, true);
		
		for(var i=0; i < this.widgets.length; i++){
			this.widgets[i].init();
		}
		
	},
	
	registerWidget: function(widget){
		this.widgets[this.widgets.length] = widget;
	},
	
	zoomInPikadate: function(){
		$('zoomedDate').style.display = "";
	},
	
	zoomOutPikadate: function(){
		$('zoomedDate').style.display = "none";
	}
	
}


Profile.MainPicture = function(config){
	
	this.img = $(config.mainPictureId);
	this.loadedEvent = new CustomEvent('loadedEvent');
	this.caption = new Profile.MainCaption(config);
	
	setTimeout(this._waitLoad.createDelegate(this), 50);
	
}

Profile.MainPicture.prototype = {

	loadedEvent: null,
	pos:[],
	width:0,
	height:0,
	imageLoaded:false,
	
	_setupProperties: function(){
		this.width = this.img.offsetWidth;
		this.height = this.img.offsetHeight;
		this.pos = Dom.getXY(this.img);
		this.imageLoaded = true;
		Event.addListener(this.img, 'mouseover', this._onMouseOver, this, true);
		Event.addListener(this.img, 'mouseout', this._onMouseOut, this, true);
	},
	
	_waitLoad: function(){
		
		if(this.img.complete){
			this._setupProperties();
			this.loadedEvent.fire(this);
			return;
		}
		
		this.imageLoaded = false;
		setTimeout(this._waitLoad.createDelegate(this), 50);
		
	},
	
	_onMouseOver: function(){
		if(!this.imageLoaded) 
			return;
			
		this.caption.show(this.pos, this.width);
	},
	
	_onMouseOut: function(){
		if(!this.imageLoaded) 
			return;
			
		this.caption.hide();
	},
	
	showMessage: function(text){
		this.caption.setText(text);
		this.caption.show(this.pos, this.width);
	},
	
	hideMessage: function(){
		this.caption.hide();
	},
	
	change: function(newSrc){
		var img = new Image();
		img.src = domain + "resources/uploads/" + newSrc;
		this.img.parentNode.replaceChild(img, this.img);
		img.id = "mainPicture"
		img.className = "petProfilePic";
		this.img = img;
		this._waitLoad();
	}
	
}

Profile.MainCaption = function(config){
	this.dom = $(config.mainCaptionId);
	this.body = $(config.mainCaptionBodyId);
}

Profile.MainCaption.prototype = {
	
	show: function(imgPos, imgWidth){
		this._positionate(imgPos, imgWidth);
		this.dom.style.visibility = "visible";
	},
	
	hide: function(){
		this.dom.style.visibility = "hidden";
	},
	
	setText: function(text){
		if(text === undefined || text === null){
			text = ". . .";
		}
		this.body.innerHTML = text;
	},
	
	_positionate: function(imgPos, imgWidth){
		var pos = [imgPos[0] + (imgWidth-this.dom.offsetWidth)/2, 
				   imgPos[1] - this.dom.offsetHeight];
		Dom.setXY(this.dom, pos);
	}
	
}

Profile.Treat = function(id, data, picture){
	this.dom = $(id);
	this.picture = picture;
	this.picture.loadedEvent.subscribe(this.onImageLoaded, this, true);
	this.data = data;
	this.treatImg = $('boneGift');
	this.treatLink = $('giveBoneLink');
	this.deliveredEvent = new CustomEvent('treatDeliveredEvent');
}

Profile.Treat.prototype = {

	targetXY:null,
	enabled: false,
	thanksMsg: "",
	messagesEnabled: true,
	
	onImageLoaded: function(){
		
		var picture = this.picture;	
		this.targetXY = [picture.pos[0] + picture.width/2 - 25, 
					     picture.pos[1] + picture.height/2 - 25];
					     
		this.enable();

	},
	
	enable: function(){
		Event.addListener(this.dom, 'click', this.onClick, this, true);	
		Event.addListener(this.treatLink, 'click', this.onClick, this, true);
		this.enabled = true;
	},
	
	onClick: function(){
		
		if(!this.enabled || !this.targetXY)
			return;
		
		this.enabled = false;
		
		Connect.asyncRequest('POST',  domain + 'pet/givebone/',
			 {success: this.receiveThanksMsg, scope:this}, 
			 "pet="+this.data.petId);
		
		Event.removeListener(this.dom, 'click');	
		
		var newTreatQty = ++this.data.treat_count;
		
		$('boneCount').innerHTML = newTreatQty;
		$('treatOnly').innerHTML = newTreatQty != 1 ? this.data.name_plural : this.data.short_name;
		
		var controlX = this.picture.pos[0] + 3*this.picture.width/4;
		var controlY = this.targetXY[1] - 180;
		
		var attributes = {
			points: {
				to: this.targetXY,
				control: [[controlX, controlY]]				
			}
		};
		
		var myAnim = new YAHOO.util.Motion(this.treatImg, attributes, 0.7, YAHOO.util.Easing.easeIn  );
		myAnim.onComplete.subscribe(this.treatReceived, this, true); 
		myAnim.animate();
		
	},
	
	receiveThanksMsg: function(o){
		this.thanksMsg = o.responseText;
	},
	
	treatReceived: function(){
		
		this.treatImg.style.visibility = "hidden";
		this.treatImg.style.left = this.treatImg.style.top = 0;
		setTimeout(this._reappear.createDelegate(this), 50);
		
		var myAnim = new YAHOO.util.Anim(this.treatImg, {opacity: {from:0, to:1}}, 0.5 );
		myAnim.onComplete.subscribe(this.enable, this, true); 
		myAnim.animate();
		
		this.deliveredEvent.fire();
		
		if(this.messagesEnabled){
			this._waitThanksMsg();
		}
		
	},
	
	_waitThanksMsg: function(){
		if(this.thanksMsg){
			this.picture.showMessage(this.thanksMsg);
			return;
		}

		setTimeout(this._waitThanksMsg.createDelegate(this), 50);
		
	},
	
	_reappear: function(){
		this.treatImg.style.visibility = "visible";
	}
	
}


Profile.GiftBoxList = function(data, picture){
	this.data = data;
	this.picture = picture;
	this.picture.loadedEvent.subscribe(this.showGifts, this, true);
	this.list = [];
}

Profile.GiftBoxList.prototype = {
	
	list: null,
	
	showGifts: function(){
		
		var div = document.createElement('div');
		div.style.textAlign = "right";
		div.style.position = "absolute";
		div.style.left = this.picture.pos[0] -this.picture.width + "px";
		div.style.top = this.picture.pos[1] + this.picture.height - 75 - 6 + "px";
		div.style.width = this.picture.width*2+ "px";
		div.style.height = "77px";
		div.style.paddingRight = "5px";
		//div.style.overflow = "hidden";
		div.style.zIndex = 10;
		
		this.div = div;
		
		$('mainPictureContainer').appendChild(div);
		
		for(var i=0; i < this.data.gifts.length; i++){
			var box = new Profile.GiftBox(this.data.gifts[i], div, this.data.for_current_user, this.data.pet_name);
			this.list.push(box);
		}
		
		//this.createGiftTree();
		
		this.picture.loadedEvent.unsubscribe(this.showGifts, this, true);
		
		if(this.data.gifts.length>0){
			this.picture.loadedEvent.subscribe(this.moveGifts, this, true);
		}
		
	},
	
	createGiftTree: function(){
				
		var img = new Image();
		img.style.position = "absolute";
		img.style.left = this.picture.pos[0] + this.picture.width - 86 -6 + "px";
		img.style.top = this.picture.pos[1] + this.picture.height - 250 - 6 + "px";
		img.src = domain + "resources/images/icons/xmastree.gif";
		img.style.zIndex = 0;
		
		$('mainPictureContainer').appendChild(img);
	},
	
	moveGifts: function(){
		this.div.style.top = this.picture.pos[1] + this.picture.height - 75 - 6 + "px";
	}
	
}

Profile.GiftBox = function(data, div, forUser, petName){
	
	this.data = data;
	this.forUser = forUser;
	this.petName = petName;
	
	var img = new Image();
	img.style.cursor = "pointer";
	img.style.zIndex = 10;
	img.style.width = "77px";
	img.src = domain + "resources/images/icons/giftred.gif";
	div.appendChild(img);
	
	this.card = this.createCard(false);
	$('mainPictureContainer').appendChild(this.card);
	
	Event.addListener(img, 'mousemove', this.showCard, this, true);
	Event.addListener(img, 'mouseout', this.hideCard, this, true);
	Event.addListener(img, 'click', this.onClick, this, true);
	
	this.img = img;
	
}

Profile.GiftBox.prototype = {
	
	showCard: function(e){
		var pos = Event.getXY(e);
		this.card.style.left = pos[0] + 7 + "px";
		this.card.style.top = pos[1] + 10 + "px";
		this.card.style.visibility = "visible";
	},
	
	hideCard: function(){
		this.card.style.visibility = "hidden";
	},
	
	onClick: function(){
		
		if(!this.forUser){
			alert("Sorry! Only " + this.petName + " can open this gift! If you are " + this.petName+ " please sign in first.");
			return;			
		}
		
		Event.removeListener(this.img, 'mousemove');
		this.hideCard();
		this.createOpenedGift();
		this.requestGift();
			
	},
	
	requestGift: function(){
		Connect.asyncRequest(
			'POST',  domain + 'gift/open/',
			{success: this.receiveGift.createDelegate(this)}, 
			"gift="+this.data.gift_pet_id
		);
	},
	
	receiveGift: function(o){
		
		eval("var data = " + o.responseText + ";");
		
		this.gift = data[0];

		var img = new Image();
		img.src = domain + "resources/images/store/" + this.gift.image + ".gif";
		img.style.position = "absolute";
		img.style.zIndex = 9;
		img.style.left = this.img.offsetLeft + 15 + "px";
		img.style.top = "25px";
		img.style.visibility = "hidden";
		
		this.giftImg = img;
		this._waitGiftLoad();
		
	},
	
	_waitGiftLoad: function(){

		if(this.giftImg.complete){
		
			var pos = YAHOO.util.Dom.getXY(this.img);
			
			this.giftImg.style.visibility = "";
			this.img.parentNode.appendChild(this.giftImg);
			
			var anim = new YAHOO.util.Motion(this.giftImg, {points: {to: [pos[0] + 15, pos[1] - 100]}}, 0.7, YAHOO.util.Easing.easeOut);
			anim.onComplete.subscribe(this.openComplete.createDelegate(this));
			anim.animate();
			
			return;
			
		}
		
		setTimeout(this._waitGiftLoad.createDelegate(this), 50);
		
	},
	
	openComplete: function(){
		
		
		
	},
	
	createOpenedGift: function(){
		
		var div = document.createElement('div');
		div.style.position = "relative";
		div.style.width = "77px";
		div.style.height = "76px";
		div.innerHTML = "&nbsp;";
		div.style.border = "solid red 1px";
		
		var fondo = new Image();
		fondo.style.position = "absolute";
		fondo.style.zIndex = 8;
		fondo.style.top = this.img.offsetTop + "px";
		fondo.style.left = this.img.offsetLeft + "px";
		fondo.src = domain + "resources/images/icons/giftopenback.gif";
		
		var front = new Image();
		front.style.zIndex = 11;
		front.src = domain + "resources/images/icons/giftopenfront.gif";
		front.style.position = "relative";
		
		var wrap = this.img.parentNode;
		wrap.appendChild(fondo);
		wrap.replaceChild(front, this.img);
		
		this.img = front;
		
	},
	
	createCard: function(opened){
		
		var card = document.createElement('div');
		card.className = "giftCard";
		
		if(opened){
			var text = this.data.name;
		}
		else{
			var text = "Click on the box to see the gift";
		}
		
		card.innerHTML = "<div style='height:100%;width:100%'>"+
							"<div style='margin:10px;padding-left:0px;padding-right:0px;width:230px;color:purple'>"+
								"<table width='100%;'>"+
									"<tr><td valign='top' style='width:90px' align='center'>"+
										"<img src='"+domain + "resources/uploads/"+this.data.picture+"' style='height:60px;padding: 3px;border: 1px solid #D9E0E6;margin-top: 5px;margin-bottom: 5px;'>"+
									"</td>"+
									"<td align='left' valign='top'>"+
										"<b>From: " + this.data.from_name + "</b>"+
										"<div style='font-style:italic;align:center'>" + this.data.message + "</div>"+
									"</td></tr>"+
									"<tr><td colspan='2' align='center'>"+
										"<span class='note'>"+text+"</span>"+
									"</td></tr>"+
								"</table>"+
								
							"</div>" +
						"</div>";
			
		return card;
		
	}
	
}

//Thank to ExtJS for this

Function.prototype.createDelegate = function(C,B,A){
	var D=this;
	return function(){
		var F=B||arguments;
		if(A===true){
			F=Array.prototype.slice.call(arguments,0);
			F=F.concat(B)
		}
		else{
			if(typeof A=="number"){
				F=Array.prototype.slice.call(arguments,0);
				var E=[A,0].concat(B);
				Array.prototype.splice.apply(F,E)
			}
		}
		return D.apply(C||window,F)
	}
}

var colorsExplain = null;
	
	function showColorsExplain(link, def){
		
		var pos = YAHOO.util.Dom.getXY(link);
		
		var div = document.createElement('div');
		div.className = "colorsExplain";
		document.body.appendChild(div);
		div.innerHTML = def? "View Default Colors" : "View Custom Colors";
		
		div.style.left = pos[0] - div.offsetWidth/2 + 10 + "px";
		div.style.top = pos[1] + 23 + "px";
				
		colorsExplain = div;
		
	}
	
	function removeColorsExplain(){
		
		if(!colorsExplain){
			return;
		}
		
		document.body.removeChild(colorsExplain);
		
	}
	
	var prizeExplain = null;
	
	function showExplain(link, html){
		
		var pos = YAHOO.util.Dom.getXY(link);
		
		var div = document.createElement('div');
		div.className = "colorsExplain";
		
		div.innerHTML = html;
		
		div.style.left = pos[0] - div.offsetWidth/2 - 10 + "px";
		div.style.top = pos[1] + 45 + "px";
		div.style.textAlign = "center";
		
		prizeExplain = div;
		$('explainPlace').appendChild(div);
		
	}
	
	function removeExplain(){
		
		if(!prizeExplain){
			return;
		}
		try{
			$('explainPlace').removeChild(prizeExplain);
		}
		catch(e){
		}
	}
	
		function changePalPage(pet, page){
		
		YAHOO.util.Connect.asyncRequest(
						'GET',  
						domain + 'pals/profile/'+pet + "?page="+page,
						{success: function(o){$('palsDiv').innerHTML = o.responseText}});
		
	}

	function changePicture(file, pic){
		
		$('mainPicture').src = domain + "resources/uploads/"+ file;		
		
		if(!picMessages[pic]){
			$('mainPicture').onmouseover = null;
			$('mainPicture').onmouseout = null;
			$('mainPicture').onmousemove = null; 
		}
		else{
			$('encourage_box').innerHTML = picMessages[pic];
			$('mainPicture').onmouseover = showTooltip;
			$('mainPicture').onmouseout = hideTooltip;
			$('mainPicture').onmousemove = showTooltip;
		}		

	}
	
	function changePicturePage(pet, page){
		
		YAHOO.util.Connect.asyncRequest(
						'GET',  
						domain + 'pals/petpic/'+pet + "?page="+page,
						{success: function(o){$('allpicsDiv').innerHTML = o.responseText}});
	
	}
	
		
	function toggleLoading(){
		if($('loading').style.visibility == "hidden")
			$('loading').style.visibility = "";
		else
			$('loading').style.visibility = "hidden";
	}

	var seeingPrevious = false;
	function seePrevious(){
		
		if(seeingPrevious){
			Effect.BlindUp('previousContainer', {duration:0.2});
			$('previousLink').innerHTML = "See my previous contests";
			seeingPrevious = 0;
			return;
		}
		seeingPrevious = true;
		new Ajax.Updater($('previousContainer'), domain + 'pet/seeprevious/' + picture, {onSuccess: function(){setTimeout(blindDownPrevious, 100)}});
		toggleLoading();

	}
	
	
	
	function blindDownPrevious(link){
		//toggleLoading();
		
		if(!seeingPrevious){
			$('previousContainer').style.display = "";
			//$('previousLink').innerHTML = "Hide my previous contests";
			seeingPrevious = true;
			link.innerHTML = "Hide previous contests";
		}
		else{
			$('previousContainer').style.display = "none";
			seeingPrevious = false;
			link.innerHTML = "See previous contests";
		}
	}
	
		var fansClicked = false;
	
	function becomeFan(pet){
		
		if(fansClicked){
			return;
		}
		fansClicked = true;
		
		$('fanWrapper').innerHTML = "One sec...";
		fansClicked = true;
		
		YAHOO.util.Connect.asyncRequest(
						'POST',  
						domain + 'favorite/add/' + pet,
						{success: fanSuccess, argument: pet}, null);
	}
	
	
	function changeCommentsPage(pet, page){
		YAHOO.util.Connect.asyncRequest(
						'GET',  
						domain + 'pet/showcomments/'+pet + "?page="+page,
						{success: function(o){$('petCommentsDiv').innerHTML = o.responseText}});
		
	}
	
	
	function seeAllCards(link){
		YAHOO.util.Connect.asyncRequest(
						'POST',  
						domain + 'gift/seeallcards/' + pet + "?offset=10",
						{success: receiveRemainingCards});
		
		toggleLoading();
		
		link.style.display = "none";
	}
	
	
	function receiveRemainingCards(o){
		$('ecardsZone').innerHTML = o.responseText;
		toggleLoading();
	}	
	
	
	function becomeFan(pet){
		
		if(fansClicked){
			return;
		}
		fansClicked = true;
		
		$('fanWrapper').innerHTML = "One sec...";
		fansClicked = true;
		
		YAHOO.util.Connect.asyncRequest(
						'POST',  
						domain + 'favorite/add/' + pet,
						{success: fanSuccess, argument: pet}, null);
	}
	
	function fanSuccess(o){
		
		$('fanWrapper').className= "selectedAccountTab";
		$('fanWrapper').innerHTML = o.responseText;
		seeFans(o.argument);
		
	}
	
	function seeFans(pet){
		
		YAHOO.util.Connect.asyncRequest(
						'POST',  
						domain + 'favorite/update/' + pet,
						{success: blindDownFans});

		toggleLoading();
	}
	
	function blindDownFans(o){
		$('fansDiv').innerHTML = o.responseText;
		toggleLoading();
		$('fansDiv').style.display = "";
	}