/*
 * U3DObject JavaScript Library v2.0
 * <aquiris-u3dobject> Unity3D Browser and Flash Integration System
 * Copyright (C) 2009 Raphael Lopes Baldi, Eduardo Pons Dias da Costa, Felipe de Souza Lahti, 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
 *
 */
(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.removeDiv = function(id_div) {
	//$('#'+ id_div).remove();
	//$('#contentDiv').append('<div id="' + id_div + '" class="' + id_div + '"></div>');
	
	$('#'+ id_div).empty();
	setTimeout(function(){resizeDaDiv(id_div)}, 2000);
}

function resizeDaDiv(id_div) {
	$("#" + id_div).attr('width', 1).attr('height', 1).css("width", 1).css("height", 1);
}

$.u3dobject.resize = function(id_div, _width, _height) {
	//$($.u3dobject.games[id_div].object).attr('width', _width).attr('height', _height);
  	//$($.u3dobject.games[id_div].object).css("width", _width).css("height", _height);

	$("#" + id_div).attr('width', _width).attr('height', _height).css("width", _width).css("height", _height);
	
	

}

$.u3dobject.embed = function(id_div, game_unity, options)
{	
	//alert('embed unity');
	var settings = $.extend({
							allowScriptAccess: "always",
							backgroundcolor: "000000",
							bordercolor: "000000",
							textcolor: "FFFFFF",
							logoimage: "logo.png",
							progressbarimage: "fg.png",
							progressframeimage: "bg.png",
							width: '100%',
							height: '100%'
							
						  }, 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 += "<param name='backgroundcolor' value='000000' /> <param name='bordercolor' value='000000' /> <param name='textcolor' value='FFFFFF' /> <param name='logoimage' value='blank.png' />"
		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-3.x" backgroundcolor="000000" bordercolor="000000" textcolor="FFFFFF" logoimage="logo.png" progressbarimage="fg.png" progressframeimage="bg.png" ';		
		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)
{

  	$("#" + id_div).attr('width', 1).attr('height', 1);
  	$("#" + id_div).css("width", 1).css("height", 1);
	$("#" + id_div).css("min-width", 1).css("min-height", 1);
	
};

/*
 * Show the unity
 * Example:
 * $.u3dobject.show("id_div_game");
 */ 
 $.u3dobject.show = function(id_div)
{

	
  	$("#" + id_div).attr('width', '100%').attr('height', '100%');
  	$("#" + id_div).css("width", '100%').css("height",  '100%');
	$("#" + id_div).css("min-width", $.u3dobject.callFlashSize.width).css("min-height", $.u3dobject.callFlashSize.height);
	self.resizeTo(self.innerWidth,self.innerHeight)
	//$(window).width($(window).width() - 200).height($(window).width() - 200);
};

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


$.u3dobject.killUnity = function(id_div) {
	
}

/*
 * 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();

var gameIntroVidComplete = false;

$.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 ()
{
	
	//alert('Windows: ' + $.u3dobject.platform.win + ' \nMac: ' + $.u3dobject.platform.mac)
	
	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.
 *
 * 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);
};

/*
* Called by ExternalInterface inside unity to comunicate the current load progress of the game. 
* The value goes from 0 to 1 (floating point).
*/
$.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);
};

/*
* Called by ExternalInterface inside unity to comunicate the game is loaded and ready. 
* The value goes from 0 to 1 (floating point).
*/
$.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();
		clearTimeout(this.detectionTimeout);
		$.u3dobject.callFlashFunction("flash_content", "unityLoaded");
	}
	else {
		this.detectionTimeout = setTimeout(function() {
			$.u3dobject.callFlashFunction("flash_content", "unityNotLoaded");
            $.u3dobject.autoReload();
            navigator.plugins.refresh();
        },
        2000);


	}
};

$.u3dobject.getVidComplete  = function() {
	return gameIntroVidComplete;
};

$.u3dobject.setVidComplete = function(value) {
	gameIntroVidComplete = value;
	return gameIntroVidComplete;
};


$.u3dobject.getUnity = function() {
	//Alert('getUnity')
	$.u3dobject.callFlashFunction("flash_content", "getUnityCalled");
	$.u3dobject.autoReload();
	
};



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