
var currentMouseX = 0;
var currentMouseY = 0;

/*
 * Called onLoad - sets up all the javascripty goodness.
 */
function initialSetup() {

	YAHOO.util.Event.addListener(document, "mousemove", recordMousePosition);

	YAHOO.util.Event.addListener("cname", "click", clearSearchField);
	YAHOO.util.Event.addListener("cname", "blur", hideAutocomplete);
	YAHOO.util.Event.addListener("cname", "focus", showAutocomplete);
	
	YAHOO.util.Event.addListener("searchform", "submit", checkLength);
	
	YAHOO.util.Event.onAvailable("set_pictures", attachDragDrop);
	YAHOO.util.Event.addListener("set_header", "click", showSetNameInput);
	
	YAHOO.util.Event.addListener("set_description", "mouseover", setDescriptionHighlight);
	YAHOO.util.Event.addListener("set_description", "mouseout", setDescriptionDull);
	YAHOO.util.Event.addListener("set_description", "click", setDescriptionEditMode);
	YAHOO.util.Event.addListener("new_description", "blur", setDescriptionUpdate);
	
	YAHOO.util.Event.addListener("chat", "click", showChatWindow);
}

/*
 * Displays the chat window
 */
function showChatWindow(event) {

	window.open('/chat/', 'chat', 'width=460,height=350,toolbar=0,location=0,status=0');
	YAHOO.util.Event.preventDefault(event);
}

/*
 * Highlights the set description on the view set page to show it is editable.
 */
function setDescriptionHighlight(event) {
	YAHOO.util.Dom.addClass("set_description", "highlight");
}

/*
 * Removes the highlight from the set description on the view set page.
 */
function setDescriptionDull(event) {
	YAHOO.util.Dom.removeClass("set_description", "highlight");
}

function setDescriptionEditMode(event) {
	YAHOO.util.Dom.addClass("set_description", "hide");
	YAHOO.util.Dom.removeClass("set_description_edit", "hide");

	document.getElementById("new_description").focus();
}

function setDescriptionViewMode(newDescription) {

	var cleanDesc = newDescription.replace(/>/g, "&gt;").replace(/</g, "&lt;");
	var newDescHTML = "<p>"+ cleanDesc.replace(/\n/g, "<br/>") +"</p>";

	document.getElementById("set_description").innerHTML = newDescHTML;

	YAHOO.util.Dom.removeClass("set_description", "hide");
	YAHOO.util.Dom.addClass("set_description_edit", "hide");
}

function setDescriptionUpdate(event) {

	console.log("setDescriptionUpdate");

	setId = document.getElementById("set_id").value;
	setDesc = document.getElementById("new_description").value;

	var callback = {
		success: function(arg) {
			setDescriptionViewMode(setDesc);
		},
		failure: function(arg) { 
			/*
			alert('failure: '+ arg.status +' '+ arg.statusText); 
			document.body.innerHTML = arg.responseText;
			*/
		},
		argument: []
	}

	var arguments = "set_id="+ setId +"&set_description="+ escape(setDesc);

	transaction = YAHOO.util.Connect.asyncRequest('POST', "/set/updatedescription/", callback, arguments);
}

/*
 * Records where the mouse is at all times, so that when something happens we know where it happened.
  */
function recordMousePosition(event) {

	currentMouseX = YAHOO.util.Event.getPageX(event);
	currentMouseY = YAHOO.util.Event.getPageY(event);
}

function attachNewSet() {
	YAHOO.util.Event.addListener("new_set", "click", newSet);
}

/*
 * Hide the auto complete popup of the search box, if we clicked the mouse outside of that box.
 */
function hideAutocomplete(event) {

	var mousePosition = new YAHOO.util.Point( currentMouseX, currentMouseY );
	var popupRegion = YAHOO.util.Region.getRegion( document.getElementById("celebcontainer") );
		
	if ( ! popupRegion.contains(mousePosition) ) {
		YAHOO.util.Dom.setStyle("celebcontainer", "display", "none");
	}
}
function showAutocomplete() {
	YAHOO.util.Dom.setStyle("celebcontainer", "display", "block");
}

function checkLength(event) {
	if ( this.cname.value.length < 3 ) {
		alert("Please enter at least 3 characters to search");
		YAHOO.util.Event.stopEvent(event);
	}
}

/*
 * Clears the search input box.
 */
function clearSearchField() {
	this.value = "";
	YAHOO.util.Event.removeListener(this, "click", clearSearchField);	
}

/*
 * Hides the set header and displays the set name input box in its place.
 */
function showSetNameInput() {
	YAHOO.util.Dom.setStyle("set_header", "display", "none");
	YAHOO.util.Dom.setStyle("set_input", "display", "block");

	var setTitleObj = document.getElementById('set_title');
	YAHOO.util.Event.addListener(setTitleObj, "blur", saveSetTitle);
	setTitleObj.focus();
	setTitleObj.select();
}

/*
 * Reverse of showSetNameInput
 */
function showSetNameHeader(newTitle) {

	// Set the new title into the header. Really we should make it a YUI thingy
	var setHeaderDiv = document.getElementById('set_header');
	while(setHeaderDiv.firstChild) setHeaderDiv.removeChild(setHeaderDiv.firstChild);
	setHeaderDiv.appendChild( document.createTextNode(newTitle) );

	YAHOO.util.Dom.setStyle("set_input", "display", "none");
	YAHOO.util.Dom.setStyle("set_header", "display", "block");
}

/*
 * Saves the set title
 */
function saveSetTitle() {

	setId = document.getElementById("set_id").value;
	setTitle = document.getElementById("set_title").value;

	var callback = {
		success: function(arg) {
			showSetNameHeader(setTitle);
			highlightSetBody();
		},
		failure: function(arg) { 
			/*
			alert('failure: '+ arg.status +' '+ arg.statusText); 
			document.body.innerHTML = arg.responseText;
			*/
		},
		argument: []
	}

	var arguments = "set_id="+ setId +"&set_title="+ escape(setTitle);

	transaction = YAHOO.util.Connect.asyncRequest('POST', "/set/update/", callback, arguments);	
}

/*
 * Highlight the picture area of sets to encourage users to drop pictures into it.
 */
function highlightSetBody() {

	if ( ! hasImageChildren('set_pictures') ) {
		Fat.fade_element('set_pictures');
	}
	
}

/*
 * Highlight the set title to encourage users to set a title.
 */
function highlightSetTitle() {

	var headerDiv = document.getElementById('set_header')
	var currentTitle = headerDiv.innerHTML;

	if ( currentTitle.indexOf('set_') != -1 || currentTitle.indexOf('Click here to name') != -1 ) {
		headerDiv.innerHTML = "Now click here to name your set";	
		Fat.fade_element('set_header');
	}
}

/*
 * Does that container contain any images ?
 */
function hasImageChildren(containerId) {

	var allInternalElements = document.getElementById(containerId).childNodes;
	for ( var i=0; i < allInternalElements.length; i++ ) {
	
		var child = allInternalElements[i];

		if ( child.nodeType == 1 && child.nodeName.toLowerCase() == "img" ) {
			return true;
		}
	}

	return false;
}


var draggables = new Array();
var setsTarget = null;
function attachDragDrop() {
	
	/* Make the thumbnails draggable */
	
	draggables = new Array();
	var allPics = YAHOO.util.Dom.getElementsByClassName("picture", "img", "images");
	for ( index in allPics ) {
		var pic = allPics[index]
		
		var dd = new DraggableImage(pic.id);
		draggables.push(dd);
	}

	setsTarget = new YAHOO.util.DDTarget("set_pictures");
	
	/* Make any mini pictures already in a set draggable */
	
	var setsDiv = document.getElementById("set_pictures");
	var allInternalElements = setsDiv.childNodes
	for ( var i=0; i < allInternalElements.length; i++ ) {
	
		var child = allInternalElements[i];

		if ( child.nodeType == 1 && child.nodeName.toLowerCase() == "img" ) {
		
			var miniDraggableImage = new MiniDraggableImage(child.id);
			miniDraggables.push(miniDraggableImage);	
		}
	}
	
}

/*
 * Clears the given object of its content if it needs to be cleared.
 * Used to remove help text from the sets box on first drop.
 */
function clearIfNeeded(container) {

	var allInternalElements = container.childNodes
	for ( var i=0; i < allInternalElements.length; i++ ) {
	
		var child = allInternalElements[i];

		if ( child.nodeType != 1 || child.nodeName.toLowerCase() != "img" ) {
			container.removeChild(child);
		}
	}

};

var DraggableImage = function(imageId) {
	this.init(imageId);
	this.initFrame();
	
	this.isTarget = false;
	this.startPos = YAHOO.util.Dom.getXY( this.getEl() );
};

DraggableImage.prototype = new YAHOO.util.DDProxy();

DraggableImage.prototype.onDragDrop = function(event, element) {

	pictureId = this.getEl().id;
	pic = document.getElementById(pictureId);
	
	newImage = document.createElement("img")
	newImage.setAttribute("id", pictureId +"-mini");
	newImage.setAttribute("src", pic.src);
	newImage.setAttribute("width", pic.width / 4);
	newImage.setAttribute("height", pic.height / 4);
	
	var setsDiv = document.getElementById("set_pictures");
	clearIfNeeded(setsDiv);
	setsDiv.appendChild(newImage);
	
	var miniDraggableImage = new MiniDraggableImage(newImage.id);
	miniDraggables.push(miniDraggableImage);	
	
	// Now tell the server to add the picture
	var callback = {
		success: function(arg) {
			// We created a new set, so put the new set id in the form
			if ( arg.responseText.indexOf("NEW") == 0 ) {
				var newSetId = arg.responseText.split('-')[1];
				var setIdElement = document.getElementById("set_id");
				setIdElement.value = newSetId;
			}
			highlightSetTitle();
		},
		failure: function(arg) { alert('failure: '+ arg.status +' '+ arg.statusText); },
		argument: []
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('POST', "/set/add_picture/", callback, "pic_id="+ pictureId);
};

DraggableImage.prototype.endDrag = function(event) {
	/*YAHOO.util.Dom.setXY(this.getEl(), this.startPos);*/
}

var miniDraggables = new Array();

var MiniDraggableImage = function(imageId) {
	this.init(imageId);
	this.initFrame();
	
	this.isTarget = false;
	this.startPos = YAHOO.util.Dom.getXY( this.getEl() );
};
MiniDraggableImage.prototype = new YAHOO.util.DDProxy();
MiniDraggableImage.prototype.onDragDrop = function(event, element) {
	// Do nothing
}
MiniDraggableImage.prototype.endDrag = function(event) {

	var setsDiv = document.getElementById("set_pictures");
	var setsDivRegion = YAHOO.util.Region.getRegion(setsDiv);
	
	var currentMousePosition = YAHOO.util.Dom.getRegion(this.getDragEl());
	if ( setsDivRegion.contains(currentMousePosition) ) {
		YAHOO.util.Dom.setXY(this.getEl(), this.startPos);
	}
	else {
		this.removePicture();
	}

};

MiniDraggableImage.prototype.removePicture = function() {

	var setsDiv = document.getElementById("set_pictures");
	setsDiv.removeChild( this.getEl() );

	pictureId = this.getEl().id.split('-')[0]
	
	// Now tell the server to remove the picture
	var callback = {
		success: function(arg) { },
		failure: function(arg) { alert('failure: '+ arg.status +' '+ arg.statusText); },
		argument: []
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('POST', "/set/remove_picture/", callback, "pic_id="+ pictureId);
}

YAHOO.util.Event.addListener(this,'load',initialSetup);

/* name-autocomplete.js */
function autoCompInit() {

    // Instantiate data source    
    oACDS = new YAHOO.widget.DS_JSArray(celeb_name_list);

    // Instantiate auto complete
    oAutoComp = new YAHOO.widget.AutoComplete('cname','celebcontainer', oACDS);
    oAutoComp.queryDelay = 0;
    oAutoComp.allowBrowserAutocomplete = false;
    
}
YAHOO.util.Event.addListener(this,'load',autoCompInit);


// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela

var Fat = {
	make_hex : function (r,g,b) 
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function ()
	{
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to) 
	{
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#FFFF33";
		if (!to) to = this.get_bgcolor(id);
		
		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;
		
		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);
		
		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);
		
		var r,g,b,h;
		while (frame < frames)
		{
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);
		
			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame; 
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}
