/*
 * U3DObject JavaScript Library v2.0
 * <aquiris-u3dobject> Unity3D Browser and Flash Integration System
 * Copyright (C) 2009 Felipe de Souza Lahti, Raphael Lopes Baldi, Eduardo Pons Dias da Costa, Aquiris Realidade Virtual
 *
 * http://code.google.com/p/aquiris-u3dobject/
 * http://www.aquiris.com.br
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Date: 2009-02-29 20:30:21
 *
 *
 * Important:
 * - This library require jQuery 1.2 or greater
 *
 * If you have any question, send me to my e-mail felipe@aquiris.com.br
 */
(function($) {

$.u3dobject = function(){return $.u3dobject.version;};

/* Version of the u3dobject */
$.u3dobject.version = "2.0";

var UNITY_MIME_TYPE = "application/vnd.unity";
var UNITY_OBJECT_ID_INITIAL = "u3dobj";
var UNITY_IFRAME_ID_INITIAL = "u3dframe";

/*Games embed*/
$.u3dobject.games = new Array();

/*
 * Embed Unity Game
 *
 * Arguments:
 * id_div -> specifies the id of the HTML element you would like to have replaced by your Unity content
 * game_unity -> specifies the URL of your game.unity3d
 * options -> A set of key/value pairs that configure the unity embed. All options are optional.
 * 		The default object is this. You can change any argument.
 * 		{
 *	 		backgroundcolor: "FFFFFF", //The background color of your unity loader
 *			bordercolor: "FFFFFF", //The border color of your unity loader
 *			textcolor: "000000", //The text color of your unity loader
 *			logoimage: "", //The url of your logo image of your unity loader
 *			progressbarimage: "", //The url of your progressbar image of your unity loader. 
 *			progressframeimage: "", //The url of your progress frame image of your unity loader
 *			disableContextMenu: "false", //Enable or disable the disableContextMenu
 *			disableExternalCall: "false", //Enable or disable the disableExternalCall
 *			disableFullscreen: "false", //Enable or disable the disableFullscreen
 *			allowScriptAccess: "true" //Enable or disable the allowScriptAccess
 *	 	}
 *
 * Important:
 * - The image file must have the extension png.
 * - The color must have the number in hex. Ex: 00FF00
 *
 * Example:
 * var options = {
 *	 				logoimage: 'imgs/loader/logo.png',
 *					progressbarimage: 'imgs/loader/progressbar.png',
 *					progressframeimage: 'imgs/loader/progressframe.png',
 *					width:900,
 * 					height:506,
 *					backgroundcolor: 'FFFFFF',
 *					textcolor: '000000',
 *					bordercolor: 'FFFFFF'
 *				};
 *
 *$.u3dobject.embed('theGame', 'unity/game.unity3d', options);
 * //Or using selector jQuery
 * $("#id_div").embedUnity('unity/game.unity3d', options);
 */
$.u3dobject.embed = function(id_div, game_unity, options)
{	
	var settings = $.extend({
							allowScriptAccess: "always",
							width: 900,
							height:500
						  }, options || {});
	
	if($.u3dobject.installed)
	{
		//Creating the object
		var embedObject = '<object id="' + UNITY_OBJECT_ID_INITIAL + 'msie' + id_div + '" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="' + settings.width +'" height="' + settings.height + '" >';
		
		//Entering parameters
		embedObject += "<param name=\"src\" value=\"" + game_unity + "\" />";
		for(var i in settings)
		{
			if(i != "width" && i != "height")
			{
				embedObject += '<param name="' + i + '" value="' + settings[i] + '" />';
			}			
		}
		
		embedObject += '<embed id="' + UNITY_OBJECT_ID_INITIAL + 'other' + id_div + '" src="' + game_unity + '" type="application/vnd.unity" pluginspage="http://www.unity3d.com/unity-web-player-2.x" ';		
		for(var i in settings)
		{	
				embedObject += ' ' + i + '="' + settings[i] + '"';			
		}
		embedObject += "/> </object>";
				
		//Embeding the object
		$("#" + id_div).html("");
		$("#" + id_div).append(embedObject);
		
		//Saving some settings of the game
		$.u3dobject.games[id_div] = 
		{
			width:settings.width,
			height: settings.height
		};
		
		//Saving the unity object
		if($.u3dobject.platform.win && $.browser.msie)
		{
			$.u3dobject.games[id_div].object = $("#" + UNITY_OBJECT_ID_INITIAL + "msie" + id_div)[0];
		}
		else
		{
			$.u3dobject.games[id_div].object = $("#" + UNITY_OBJECT_ID_INITIAL + "other" + id_div)[0];
		}		
	}
	else
	{
	  alert("Not installed!");
	}
};

$.fn.embedUnity = function(game_unity, options) 
{
  return this.each(function()
  {
    	$.u3dobject.embed(this.id,game_unity, options);
  });
};

/*
 * Hide the unity
 * Example:
 * $.u3dobject.hide("id_div_game");
 */ 
$.u3dobject.hide = function(id_div)
{
  $($.u3dobject.games[id_div].object).attr('width', 1).attr('height', 1);
  $($.u3dobject.games[id_div].object).css("width", 1).css("height", 1);
};

/*
 * Show the unity
 * Example:
 * $.u3dobject.show("id_div_game");
 */ 
 $.u3dobject.show = function(id_div)
{
  $($.u3dobject.games[id_div].object).attr('width', $.u3dobject.games[id_div].width).attr('height', $.u3dobject.games[id_div].height);
  $($.u3dobject.games[id_div].object).css("width", $.u3dobject.games[id_div].width).css("height",  $.u3dobject.games[id_div].height);
};

/*
 * Check if the Unity Web Player is installed.
 * Return true if is installed or false if isn't installed.
 *
 * Example:
 * if($.u3dobject.installed())
 *{
 *	$.u3dobject.embed("game_unity", "unity/game.unity3d", options);	 
 *}
 */
$.u3dobject.installed = function()
{
	var tInstalled = false;
	if (navigator.appVersion.indexOf("MSIE") != -1 &&
		navigator.appVersion.toLowerCase().indexOf("win") != -1)
	{
		tInstalled = detectUnityWebPlayerActiveX();
	}
	else if (navigator.mimeTypes && navigator.mimeTypes["application/vnd.unity"])
	{
		if (navigator.mimeTypes["application/vnd.unity"].enabledPlugin &&
			navigator.plugins && navigator.plugins["Unity Player"])
		{
			tInstalled = true;	
		}
	}
	return tInstalled;
};

/*
 * Platform
 * Return boolean 
 *
 * Example:
 * $.u3dobject.platform.win; // true
 * $.u3dobject.platform.mac; // false
 */ 
var OS = navigator.userAgent.toLowerCase();

$.u3dobject.platform = {	
	mac: /mac/i.test(OS),
	win: /win/i.test(OS),
    linux: /linux/i.test(OS)
};

$.u3dobject.platform.mac.intel = /intel/i.test(OS);

$.u3dobject.platform.mac.ppc = /ppc/i.test(OS);

/*
 * Return de plugin path to download Unity Web Player
 * Example:
 * window.open($.u3dobject.pluginPath(),'blank');
 */ 
$.u3dobject.pluginPath = function ()
{
	if($.u3dobject.platform.win)
	{
		return "http://webplayer.unity3d.com/download_webplayer-3.x/UnityWebPlayer.exe";
	}
	
	if($.u3dobject.platform.mac)
	{
		if($.u3dobject.platform.mac.ppc)
		{
			return "http://webplayer.unity3d.com/download_webplayer-3.x/webplayer-ppc.dmg";
		}
		else 
		{
			return "http://webplayer.unity3d.com/download_webplayer-3.x/webplayer-i386.dmg";
		}
	}
	
	return "http://unity3d.com/unity-web-player-3.x";
};

/*
 * Call the Unity
 * Arguments:
 * id_div -> The id of the div that contain unity game. 
 * my_object -> The object to call in the Unity
 * my_function -> The function to call in your object
 * params -> The params of the function
 */
$.u3dobject.callUnity = function (id_div, my_object, my_function , params)
{
	$.u3dobject.games[id_div].object.SendMessage(my_object, my_function, params);
};

/*
 * Dispatch Event to Unity
 * Arguments:
 * id_div -> The id of the div that contain unity game. 
 * event_name -> The event to call
 * data -> The data to send in string JSON.
 *
 * Example:
 * $.u3dobject.dispatchUnityEvent("id_div", "StartGame", "param1,param2");
 */ 
$.u3dobject.dispatchUnityEvent = function (id_div, event_name, data)
{		
	$.u3dobject.callUnity(id_div, "ExternalInterface", "OnExternalEvent", event_name + '(' + data + ")" );
};

/*
 * Call the Unity function
 * Arguments:
 * id_div -> The id of the div that contain unity game. 
 * target -> Object to send
 * function -> the function to call
 */
$.u3dobject.callUnityFunction = function(p_div_name, p_target, p_function)
{
	var function_name = p_function.split("(")[0];
											  
	var params = p_function.substring(p_function.indexOf("(") + 1, p_function.indexOf(")"));

	$.u3dobject.games[id_div].object.SendMessage(p_target, function_name, params);
};

 /*
 * Call the Flash function
 * Arguments:
 * id_div -> The id of the swf
 * function -> the function to call
 */
$.u3dobject.callFlashFunction = function(id_swf, p_function)
{
	var swf_obj = (navigator.appName.indexOf('Microsoft') >=0) ? window[id_swf] : document[id_swf];	
	swf_obj.callFlashInterface(p_function);
};

$.u3dobject.callLoadProgress = function(id_swf, p_progress)
{
	var swf_obj = (navigator.appName.indexOf('Microsoft') >=0) ? window[id_swf] : document[id_swf];
	swf_obj.callProgressEvent(p_progress);
};

$.u3dobject.callCompleted = function (id_swf)
{
	var swf_obj = (navigator.appName.indexOf('Microsoft') >=0) ? window[id_swf] : document[id_swf];
	swf_obj.callCompleteEvent();
};

/*
 * Refreshing plugins...
 */
$.u3dobject.autoReload = function()
{
	navigator.plugins.refresh();
	if($.u3dobject.installed())
	{
		window.location.reload();
	}
	else
	{
		setTimeout('$.u3dobject.autoReload();', 1000);
	}
};
if(!$.u3dobject.installed)
{
	$.u3dobject.autoReload();
}

})(jQuery);
	

//Depreceated

//Iframe!
/*
var $iframe = $('<iframe id="' + UNITY_IFRAME_ID_INITIAL + id_div + '" name="' + UNITY_OBJECT_ID_INITIAL + id_div + '" src="about:blank" width="' + settings.width + '"  height="' + settings.height + '" scrolling="no" style="overflow:hidden; border:0px;" />');
var u3diframe = $iframe[0];

$("#" + id_div).html("");
$("#" + id_div).append(u3diframe);

var doc = null;

if(u3diframe.contentDocument)
{
	doc = u3diframe.contentDocument;
}
else if(u3diframe.contendWindow)
{
	doc = u3diframe.contentWindow;
}
else if(u3diframe.document)
{
	doc = u3diframe.document;
}

var scriptEmbed = "<script type='text/javascript'>";
scriptEmbed += "function $.u3dobject.callFlashFunction(p_swf, p_function)\n";
scriptEmbed += "{";
scriptEmbed += "parent.$.u3dobject.callFlashFunction(p_swf, p_function);";
scriptEmbed += "};\n";

scriptEmbed += '$.u3dobject.hide = function(p_div)';
scriptEmbed += '{';
scriptEmbed += 'parent.$.u3dobject.hide(p_div);';
scriptEmbed += '};\n';

scriptEmbed += '$.u3dobject.show = function(p_div)';
scriptEmbed += '{';
scriptEmbed += 'parent.$.u3dobject.show(p_div);';
scriptEmbed += '};\n';

scriptEmbed += '$.u3dobject.callLoadProgress = function(p_swf, p_progress)';
scriptEmbed += '{';
scriptEmbed += 'parent.$.u3dobject.callLoadProgress(p_swf, p_progress);';
scriptEmbed += '};\n';

scriptEmbed += '$.u3dobject.callCompleted = function(p_swf)';
scriptEmbed += '{';
scriptEmbed += 'parent.$.u3dobject.callCompleted(p_swf);';
scriptEmbed += '};\n';
scriptEmbed += "</script>";

doc.write(scriptEmbed);
doc.write(embedObject);
$(doc.body).css("margin", 0).css("padding", 0);
*/
