// JavaScript Document
//set the size of the text box and reload all the draggables to fit the text
//use the name attribute to set the text size - add this to the Overlay object
//group into classes


document.observe('dom:loaded', domLoaded);
var arrayOverlay = new Array();

var Overlay = Class.create({
  initialize: function(name, x, y) {
    this.name = name;	//name attribute
	this.x = x;
	this.y = y;
	this.isTextImage = false;
	this.text = null;
	this.textSize = null;
  },		//make a set text that when used automatically set istextImage to true
  setText: function(text, size)
  {
	this.isTextImage = true;
	this.text = text;
	this.textSize = size;
  },
  toJSON: function()
  {
	
	if( !this.isTextImage )
	{
		var serialized = "{\"name\": \"" + this.name + "\", \"x\": " + this.x + ", \"y\": ";
		serialized += "" + this.y + "}";
		return serialized;
	}
	else
	{
		
		var serialized = "{\"name\": \"" + this.name + "\", \"x\": " + this.x + ", \"y\": ";
		serialized += "" + this.y + ", \"isText\": \"true\", \"size\": " + this.textSize + ", \"text\": \"" + this.text + "\"}";
		return serialized;
	}
	return "JSON object";
  }
});

/*
var myArray = new Array();

var pirateHat = new Overlay("pirate_hat", 10, 20);
var pirateShip = new Overlay("pirate_ship", 10, 20);
myArray.push(pirateHat);
//myArray.push(pirateShip);
pirateHat.setText("some sample text");

var text = "";
for(var i = 0; i < myArray.length; i++)
	text += myArray[i].toJSON();
	*/
//alert(text);

function domLoaded()
{
	//$("submitButton").observe("click", ajaxTest);
	//new Draggable('box1');
	//note in loading scriptaculous - it needs all its files to load properly else ohter scripts dont load
	$("submitButton").observe("click", textAjax);
	$("clearButton").observe("click", clearFlag);	
	var loading_box = $("loading_box");
	var viewWidth = document.viewport.getWidth();
	var viewHeight = document.viewport.getHeight();
	var boxWidth = loading_box.getWidth();
	var boxHeight = loading_box.getHeight();
	
	var x = viewWidth/2 - boxWidth/2;
	var y = viewHeight/2 - boxHeight/2;
	
//	alert( "" + viewWidth + " " + viewHeight);
//	alert( "" + x + " " + y);
	loading_box.setStyle({ top : y +'px' });
	loading_box.setStyle({ left : x +'px' });
	
	loadInteractives();

}

function clearFlag()
{
	//alert("clear flag");
	arrayOverlay = new Array();
	new Ajax.Request('http://thepiratesource.com/pirate/generate_image.html',
	{
	 method:'post',
	 onSuccess: updateImage,
	 onFailure: function(){ alert('Something went wrong...') }
	});
	
}

function success(transport)
{
   var response = transport.responseText || "no response text";
   //alert("Success! \n\n" + response);
   //signify failure if it occurs, if not just continue no alert
   $('generated_image').update(response);
}
function ajaxTest()
{
//alert("start ajax");
new Ajax.Request('http://thepiratesource.com/pirate/generate_text_image.html',
{
 method:'post',
 parameters : $('text_gen_form').serialize(), 
 onSuccess: success,		//i guess parameter passing happens automatically - this works
 onFailure: function(){ alert('Something went wrong...') }
});
}

//use Element.readAttribute to get an attribute like name
//currently everything works -
//do svn of all this stuff

function receiveDrop(draggable, droppable, event)
{
	//? validate input
	var dragPos = Element.cumulativeOffset(draggable);
	var dropPos = Element.cumulativeOffset(droppable);
	var x = dragPos[0] - dropPos[0];
	var y = dragPos[1] - dropPos[1];
	//alert( " x: " + x + " y: " + y);
	//var draggableName = Element.readAttribute(draggable, "name");
	flagMaker(x, y, draggable);
}

function flagMaker( x, y, draggable )
{
	var draggableName = Element.readAttribute(draggable, "name");
	// have text iamge have class name of text: use in if
	//if text do something extra
	var tempOverlay;
	if( Element.hasClassName(draggable, "text") )
	{
		var textImageNode = $('generated_text_image');
		tempOverlay = new Overlay(draggableName, x, y);
		tempOverlay.setText(textImageNode.readAttribute('title'), textImageNode.readAttribute('name') );
	}
	else
	{
		tempOverlay = new Overlay(draggableName, x, y);
	}
	arrayOverlay.push(tempOverlay);
	//need to add & if it isn't the first string
	var postText = "[ ";
	for(var i = 0; i < arrayOverlay.length; i++)
	{
		if( i < arrayOverlay.length - 1)
		{
			postText += arrayOverlay[i].toJSON() + ", ";
		}
		else
		{
			postText += arrayOverlay[i].toJSON() + "]";
		}
	}
	//make ajax calls 
	//have the call make a loading thing
	//alert("sending" + postText);
	new Ajax.Request('http://thepiratesource.com/pirate/generate_image.html',
	{
	 method:'post',
	 parameters: postText,
	 onSuccess: updateImage,
	 onFailure: function(){ alert('Something went wrong...') }
	});

}

function updateImage( received )
{
	//image update with new tag
	var response = received.responseText || "no response text";
    //alert("Success! \n\n" + response);
   $('droppable_demo').update(response);
}

function loadInteractives()
{
	if( Element.hasClassName($('generated_text_image'), "containsImage") )
		new Draggable($('generated_text_image'), { revert: true });
		
	new Draggable("draggable_demo_1", { revert: true, scroll: window });
	new Draggable("draggable_demo_2", { revert: true, scroll: window });	
	new Draggable("draggable_demo_3", { revert: true, scroll: window });
	new Draggable("draggable_demo_4", { revert: true, scroll: window });
	new Draggable("draggable_demo_5", { revert: true, scroll: window });
	new Draggable("draggable_demo_6", { revert: true, scroll: window });
	Droppables.add('droppable_demo', { 
		accept: 'draggable',
		hoverclass: 'hover',
		onDrop: receiveDrop
	});
	
}

function textSuccess(transport)
{
//resize box for text
   var response = transport.responseText || "no response text";
   //alert("Success! \n\n" + response);
   //signify failure if it occurs, if not just continue no alert
   var form = $('text_gen_form');
   var textBox = form['text_value'];
   var sizeDropDown = form['text_size'];
   var textValue = $F(textBox);
   var sizeDropDownValue = $F(sizeDropDown);
   
   $('generated_text_image').update(response);
   $('generated_text_image').writeAttribute("title", textValue);
   $('generated_text_image').writeAttribute("name", sizeDropDownValue);
   
   if( !Element.hasClassName( $('generated_text_image'), "containsImage") )
		Element.addClassName( $('generated_text_image'), "containsImage");
   
   loadInteractives();
   resizeText();
}

function textAjax()
{
//alert("start text ajax");
new Ajax.Request('http://thepiratesource.com/pirate/generate_text_image.html',
{
 method:'post',
 parameters : $('text_gen_form').serialize(), 
 onSuccess: textSuccess,		//i guess parameter passing happens automatically - this works
 onFailure: function(){ alert('Something went wrong...') }
});
}

//register loading box
Ajax.Responders.register({
    onCreate: startLoad,
    onComplete: stopLoad
});

function resizeText()
{
	var text_div = $('generated_text_image');
	var image_text = text_div.firstDescendant();	
	var dimensions = image_text.getDimensions();
	text_div.setStyle({
					  width: dimensions.width,
					  height: dimensions.height
					  });
	
	//alert("" + dimensions);
}
function startLoad()
{
	  var count = Ajax.activeRequestCount++;
      var container = $('loading_box');
      container.toggleClassName('hidden');
}

function stopLoad()
{
      var count =  Ajax.activeRequestCount--;
      var container = $('loading_box');
      container.toggleClassName('hidden');
}

/*// doesnt like this for some reason
for( var i in adraggable)
{
	new Draggable(adraggable[i],{ revert: true });
}
*/
