/**
 *	dynamicDiv.js
 *
 *	This jQuery libray performs the following basic operations on div.
 *
 * createDiv(id, x, y, width, height): Creates a div
 * moveDivTo(id, x, y): Moves a div to x,y
 * moveDivBy(id, x, y): Moves a div by x,y
 * resizeDiv(id, width, height): Resizes a div to final size of width x height
 * hideDiv(id): Hides the div
 * showDiv(id): Shows the div
 * loadDiv(id, url): Loads the div with specified
 * setZIndex(id, zindex): sets the z-index of the div
 * sendToBack(id): sets the z-index to the bottom most level
 * sendToFront(id): sets the z-index to the top most level
 * removeDiv(id): Removes the div
 *
 */
$(document).ready(function()
{
	var arrZIndexes = [];
	var counter = 0;
	arrZIndexes['flashObject'] = 0;

	/**
	 * Browser enums
	 */ 
	var IE = 0;
	var SAFARI = 1;
	var FIREFOX = 2;
	
	/**
	 * Gets the current browser
	 */
	function getBrowser()
	{
		// Browser check
		if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
			return IE;
		else if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
			return SAFARI;
		else
			return FIREFOX;
	}
	 
	/**
	 * createDiv: Creates the div and attaches that to the body
	 */
	$(document).bind('createDiv', function(event, msg)
	{
		++counter;
		
		// Allignment adjustment for Firefox
		if(getBrowser() == FIREFOX)
		{
			msg.x = msg.x - 2;
		}
		
		var css = {
					'overflow'					: 'auto',
					'left'						: msg.x,
					'top'						: msg.y,
					'position'					: 'absolute',
					'height'                    : msg.height,
					'width'                     : msg.width,
					'z-index'					: counter,
					'padding-left'				:	'0px',
					'padding-top'				:	'0px'
					
		};

		var attributes = {
							'id' : msg.id
							
		};


		// Prepare the div
		var div = jQuery('<div align="center" valign="middle"></div>');

		// Set div atrributs and CSS
		// Append the div to the body
		div.css(css)					// Set div CSS
			.attr(attributes)			// Set div atrributs
			.appendTo(document.body);	// Appending div to the Document Body

		
		//if (DetectUnityWebPlayer())
		//{
			var strModelFilePath = 'content/en_US/' 
			+ '3d_mod_'	+ msg.id + '.unity3d'; 
		
			var unityObject = jQuery('<object id="UnityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="800" height="446" codebase="http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.cab#version=2,0,0,0">'
										+ ' <param name="src" value="' + strModelFilePath + '" />'
										+ ' <embed id="UnityEmbed" src="' + strModelFilePath + '" width="800" height="446" type="application/vnd.unity" pluginspage="http://www.unity3d.com/unity-web-player-2.x"/ wmode="transparent">'
										+ ' <\/embed>'
										+ ' <\/object>');

			// Set unityObject atrributs and CSS
			// Append the unityObject to the div
			unityObject.appendTo(div);				// Appending unityObject to the div
		//}
		
		//arrZIndexes[counter] = msg.id;
		arrZIndexes[msg.id] = counter;

	});

	/**
	 * callFunction: Calls a unity3D function
	 */
	$(document).bind('callFunction', function(event, msg)
	{
		// Calling function for getting the Div Object.
		//var div = getDivObject(msg.id);
		var target = msg.target;
		var fName = msg.fName;
		var param = msg.param;
		var obj; 
		
		// Browser check
		if(getBrowser() != IE)
		{
			obj = $("#UnityEmbed");
		}
		else
		{
			obj = $("#UnityObject");
		}
		
		
		/*
		if (navigator.appVersion.indexOf("MSIE") != -1)
			obj = $("#UnityObject");
		else
			obj = $("#UnityEmbed");
		*/
		
		/*
		if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
			obj = $("#UnityObject");
		else if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
			obj = $("#UnityObject");
		else
			obj = $("#UnityEmbed");
		*/
				
		// Call the unity3d method		
		document.getElementById(obj.selector.substring(1)).SendMessage(target, fName, param);
	});
	
	/**
	 * removeDiv: Removes the div - to be completed
	 */
	$(document).bind('removeDiv', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		var iZIndex = div.css('z-index');

		//Set the parameters
		div.fadeOut('slow')
			.remove();

		delete arrZIndexes[iZIndex];
	});

	/**
	 * removeAllDiv: Removes all divs
	 */
	$(document).bind('removeAllDiv', function(event, msg)
	{
		// Parse through all the divs and delete them
		for( var key in arrTempZIndexes )
		{
			if (key != 'flashObject') 
			{
				// Calling function for getting the Div Object.
				var div = getDivObject(key);
				var iZIndex = div.css('z-index');
		
				//Set the parameters
				div.fadeOut('slow')
					.remove();
		
				delete arrZIndexes[iZIndex];
			}
		}
	});

	/**
	 * moveDivTo: Moves div to specified x,y
	 */
	$(document).bind('moveDivTo', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		var css = {
					'left'	: msg.x,
					'top'	: msg.y
		};
		
		//Set the parameters
		div.css(css);
	});

	/**
	 * moveDivBy: Moves div by an amount specified by x,y
	 */
	$(document).bind('moveDivBy', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		// Recalculate the new position by removing the px suffix
		msg.x = parseInt(div.css('left'))+ parseInt(msg.x) + 'px';
		msg.y = parseInt(div.css('top'))+ parseInt(msg.y) + 'px';

		var css = {
					'left'	: msg.x,
					'top'	: msg.y
		};
		
		//Set the parameters
		div.css(css);
	});

	/**
	 * resizeDiv: Resizes div to width, height
	 */
	$(document).bind('resizeDiv', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		var css = {
					'width'		: msg.width,
					'height'	: msg.height
		};

		//Set the parameters
		div.css(css);
	});

	/**
	 * hideDiv: Hides div
	 */
	$(document).bind('hideDiv', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		//Hidding the Div.
		// ~ div.hide();
		div.fadeOut('slow');
	});

	/**
	 * hideDiv: Hides div
	 */
	$(document).bind('showDiv', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		//Showing the Div.
		// ~ div.show();
		div.fadeIn('slow');
	});

	/**
	 * loadDiv: Loads the div with specified url - not working
	 */
	$(document).bind('loadDiv', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		msg.url = msg.url + '?random=' + Math.random() * 99999;

		//Set the parameters
		div.load(msg.url);
	});

	/**
	 * setZIndex: Sets the z-index for the div
	 */
	$(document).bind('setZIndex', function(event, msg)
	{
		// Calling function for getting the Div Object.
		var div = getDivObject(msg.id);

		var css = {
					'z-index'	: msg.zIndex
		};
		
		//Set the parameters
		div.css(css);
	});

	/**
	 * sendToBack: Sends this div at the back of the nextmost downward div.
	 * TODO:-
	 * 1) Evaluate the position of the div selected as curKey. Current functionality is assuming it as 2.
	 */
	$(document).bind('sendToBack', function(event, msg)
	{
		var css = {};

		//var curKey = 2;
		var objDiv = $('#' + msg.id);
		var curKey = objDiv.css('z-index');

		var curVal	= arrZIndexes[parseInt(curKey) - 1];
		var downVal = arrZIndexes[curKey];

		// Shifting the selected div to the back of the nextmost downward div.
		arrZIndexes[curKey] = curVal;

		// Calling function for setting z-index of the current div.
		setZIndex(curVal, curKey);

		// Shifting the nextmost downward div to the front of the selected div.
		arrZIndexes[parseInt(curKey) - 1] = downVal;

		// Calling function for setting z-index of the current div.
		setZIndex(downVal, parseInt(curKey) - 1);
	});
	
	/**
	 * sendToLast: Sends this div at the back of all the divs
	 */
	$(document).bind('sendToLast', function(event, msg)
	{
		setZIndex(msg.id, -1);
		
		return;
/*
		var css = {};
		var arrTempZIndexes = [];

		// Getting a temp duplicate of the Z Index array.
		var arrTempZIndexes = arrZIndexes;

		// Getting the number of elements under the Z Index array.
		var iZIndexLen = arrZIndexes.length;

		// If there arer more than one divs to be worked on.
		if( iZIndexLen > 1) 
		{
			// Emptying the Z-Indexes Array.
			delete arrZIndexes;
			arrZIndexes = [];

			// Traversing through the Temporary Z-Index Array
			for( var key in arrTempZIndexes )
			{
				if( key == 0 )
				{
					// Shifting down the selected div to the back of all.
					arrZIndexes[key] = msg.id;

					// Calling function for setting z-index of the current div.
					setZIndex(msg.id, key);
				}
				else if( arrTempZIndexes[key] <= msg.id )
				{
					// Shifting up the divs upto the selected div by one level.
					arrZIndexes[key] = arrTempZIndexes[( parseInt(key) - 1 )];

					// Calling function for setting z-index of the current div.
					setZIndex(arrTempZIndexes[( parseInt(key) - 1 )], key);
				}
				else
				{
					arrZIndexes[key] = arrTempZIndexes[key];

					// Calling function for setting z-index of the current div.
					setZIndex(arrTempZIndexes[key], key);
				}
			}
			
			delete arrTempZIndexes;
		}
*/
	});

	/**
	 * sendToFront: Makes this div in front of all the divs
	 */
	$(document).bind('bringToFront', function(event, msg)
	{
		setZIndex(msg.id, arrZIndexes[msg.id]);
		
		return;
/*
		var css = {};

		// Getting a temp duplicate of the Z Index array.
		var arrTempZIndexes = arrZIndexes;

		// Getting the number of elements under the Z Index array.
		var iZIndexLen = arrZIndexes.length;

		// If there arer more than one divs to be worked on.
		if( iZIndexLen > 1) 
		{
			// Emptying the Z-Indexes Array.
			arrZIndexes = [];

			// Traversing through the Temporary Z-Index Array
			for( var key in arrTempZIndexes )
			{
				if( key == parseInt( iZIndexLen ) - 1 )
				{
					// Shifting the selected div to the top of all.
					arrZIndexes[key] = msg.id;

					// Calling function for setting z-index of the current div.
					setZIndex(msg.id, key);
				}
				else if( arrTempZIndexes[key] < msg.id )
				{
					arrZIndexes[key] = arrTempZIndexes[key];

					// Calling function for setting z-index of the current div.
					setZIndex(arrTempZIndexes[key], key);				
				}
				else
				{
					// Shifting down the divs upto the selected div by one level.
					arrZIndexes[key] = arrTempZIndexes[( parseInt(key) + 1 )];

					// Calling function for setting z-index of the current div.
					setZIndex(arrTempZIndexes[( parseInt(key) + 1 )], key);
				}
			}
		}
*/
	});

	function bindFunctionsOverDivs()
	{
		// Binding the Click Handler to be Called when the div containers are clicked
		$(".myObjects").bind("click", clickHandler);
	}

	function clickHandler(event)
	{
		var res = prompt('What do you want to do?\nValid option are: 1) Bring To Front 2) Send To Last', 'Bring To Front');

		switch(res)
		{
			case 'Bring To Front':

				// Calling function bringing the current div to the front of all.
				bringToFront(event.target.id);

				break;

			case 'Send To Back':

				// Calling function bringing the current div to the back.
				sendToBack(event.target.id);
				
				break;

			case 'Send To Last':

				// Calling function bringing the current div to the back of all.
				sendToLast(event.target.id);
				
				break;

			default:

				alert('Invalid option entered.');
		}
	}

	function getDivObject(id)
	{
		// Get the div and other params
		var strDiv = 'div#' + id;

		return jQuery(strDiv);
	}

	/**
	 * log: Shows the event data received from the msg in specified format
	 */
	function log(msg)
	{
		alert('createDiv: id = ' + msg.id + ",x = " + msg.x + ",y = " + msg.y + ",width = " + msg.width + ",height = " + msg.height);
	}
}
);
