//
// HDView2.js    copyright 2007, Microsoft Corporation
//
// This script contains helper functions for initializing the HD View
// control.  Currently HD View is only supported on IE and Firefox under Windows.
// For many users you should be able to just directly link to this 
// script on the HD View web site:
//   <script type="text/javascript" src="http://research.microsoft.com/ivm/HDView/HDView2.js"></script>
// There are several advantages to this, including that bug fixes can
// be made in one common location and that if the control version changes
// this script will prompt users that an update is available.
// 
// For users who need to add functionality, you may modify this script and 
// use it on your own site.
// 
function hdvHelperFn()
{
	// variables that determine the platform
	var ua   = navigator.userAgent;
	var appv = navigator.appVersion;
	var isIE      = ( ua.indexOf( "MSIE" ) != -1 );
	var isFF      = ( ua.indexOf( "Firefox" ) != -1 );
	var isVista   = ( ua.indexOf("Windows NT 6") != -1 );
	var isXP_2003 = ( (ua.indexOf("Windows NT 5.1") != -1 || 
					   ua.indexOf("Windows NT 5.2") != -1) );
	var isWin64 = (appv.indexOf("WOW64") != -1 || appv.indexOf("Win64") != -1); 

	// public functions
	this.getMimeType = function() { return "application/x-hdview";} 
	this.getClsid    = function() { return "F81FB289-0FB6-4FE0-A488-101447EE1ED3"; }
	this.getCodepath = function() { return "http://research.microsoft.com/ivm/HDView/"; }
	this.getVersion  = function() { return "1,0,0,20";  }
	this.isPlatformSupported = function() { return((isIE || isFF) && (isXP_2003 || isVista)) } 
	this.isHDViewInstalled = function()
	{
		var installed = false;
		try
		{
			reqVersionArray = this.getVersion().split(',');
			if( isIE ) {
				var hdvCntrl = new ActiveXObject("HDView.HDViewControl");
				if( hdvCntrl ) {
					controlVersionArray = hdvCntrl.Version.split('.');
					installed = reqVersionArray[0] <= controlVersionArray[0] &&
								reqVersionArray[3] <= controlVersionArray[3];
				}
			}
			else {
				navigator.plugins.refresh(false);
				var hdvPlugin = navigator.plugins["HD View"];
				if( hdvPlugin ) {
					pluginVersionArray = hdvPlugin.description.split('.');
					installed = reqVersionArray[0] <= pluginVersionArray[0] &&
								reqVersionArray[3] <= pluginVersionArray[3];
				}
			}
		}
		catch (e) {}
		return installed;
	}
};
var hdvHelper = new hdvHelperFn();

function hdvHost(id, elementId, width, height, href, args)
{	
	// variables that determine the platform
	var ua   = navigator.userAgent;
	var isIE      = ( ua.indexOf( "MSIE" ) != -1 );
	var isFF      = ( ua.indexOf( "Firefox" ) != -1 );

	// public functions
	this.setArgs             = setArgs;
	this.setProperty         = setProperty;
	this.getProperty         = getProperty;
	this.permalinkPopUp      = permalinkPopUp;

	// store the constructor arguments
	var argId        = id;
	var argElementId = elementId;
	var argWidth     = width;
	var argHeight    = height;
	var argHref      = href; 
	var argArgs      = args;

	var hdvobj = "document." + argId;
	if ( isIE )
	    hdvobj += ".object";
	var curFilename = ""; 

	//
	// the "constructor"
	//
	// synopsis: If this is not a supported platform this function writes
	//           some html into the page to that effect.  Otherwise it 
	//           first detects if the control is installed on this machine.
	//           If it is not installed then some html is written into the
	//           page that offers users a link to the install page.  If it is 
	//           installed, then the control will be embedded in the supplied 
	//           'elementId'.
	// 
	constructor();

	function constructor()
	{
		if ( !hdvHelper.isPlatformSupported() ) {
		    document.getElementById(argElementId).innerHTML = 
				buildHTMLForNotSupported();
		}
		else {
			if ( !hdvHelper.isHDViewInstalled() ) {
				document.getElementById(argElementId).innerHTML = 
					buildHTMLForInstall();
			}
			else {
				document.getElementById(argElementId).innerHTML =
					isFF? buildHTMLForControlFF(argId, argWidth, argHeight):
					      buildHTMLForControlIE(argId, argWidth, argHeight);
				setArgs(argArgs);
			}
        }
	}

    // other functions
	function setArgs(argString)
	{ 
		if( hdvHelper.isPlatformSupported() ) {
			var args = argString.split('#');
			for (var i = 0; i < args.length; i++) {   
				var arg = args[i].split("=");
				setProperty(arg[0], arg[1]);
			}
		}
	}

	function setProperty(prop, val)
	{
		if( hdvHelper.isPlatformSupported() ) {    
			if( prop == "FileName" ) {
				curFilename = val;
				var pageArgs = argHref.split('?');
				var pagePath = pageArgs[0].substring(0, pageArgs[0].lastIndexOf('/') + 1);
				val = pagePath + val;
			}

			// Determine local decimal point representation and format
			// the val correctly under IE, Firefox uses "." regardless.
			if (isIE) {
				if( prop == "FOV" || prop == "Yaw" || prop == "Pitch" ||
					prop == "Zoom" || prop == "XCtr" || prop == "YCtr" )
				{
					var separator = Number(1.1).toLocaleString().charAt(1);
					val = val.replace(/\./, separator);
				}
			}

			eval(hdvobj + '.' + prop + '= val;');
		}
	}

	function getProperty(prop)
	{
		if( hdvHelper.isPlatformSupported() ) {
			var val;
			eval('val = ' + hdvobj + '.' + prop + ';');
			return val;
		}
	}
	//
	// function: permalinkPopUp
	//
	// synopsis: call this function to create a pop-up window that contains
	//           a 'permalink' url for the current control view parameters.  
	//           The user is prompted to copy the url to the clipboard.
	//           
	function permalinkPopUp()
	{
		if ( hdvHelper.isPlatformSupported() )
		{
			win = window.open("", "", "width=600, height=200"); 
			win.document.open(); 
			win.document.write('<html><body>');
			win.document.write('<div align="center">');

			var pageArgs = argHref.split('?');
			var permalink = pageArgs[0] +
				            "?FileName=" + curFilename +
							"&BackgroundColor=" + getProperty('BackgroundColor') +
							"&FOV=" + Math.round(getProperty('FOV') * 1000) / 1000 +
							"&Yaw=" + Math.round(getProperty('Yaw') * 1000) / 1000 +
							"&Pitch=" + Math.round(getProperty('Pitch') * 1000) / 1000 +
							"&Zoom=" + Math.round(getProperty('Zoom') * 1000) / 1000 +
							"&XCtr=" + Math.round(getProperty('XCtr') * 1000) / 1000 +
							"&YCtr=" + Math.round(getProperty('YCtr') * 1000) / 1000 +
				            "&ToneMode=" + getProperty('ToneMode');
			var permadisp = pageArgs[0] +
				            "<wbr>?FileName=" + curFilename +
							"<wbr>&BackgroundColor=" + getProperty('BackgroundColor') +
							"<wbr>&FOV=" + Math.round(getProperty('FOV') * 1000) / 1000 +
							"&Yaw=" + Math.round(getProperty('Yaw') * 1000) / 1000 +
							"&Pitch=" + Math.round(getProperty('Pitch') * 1000) / 1000 +
							"<wbr>&Zoom=" + Math.round(getProperty('Zoom') * 1000) / 1000 +
							"&XCtr=" + Math.round(getProperty('XCtr') * 1000) / 1000 +
							"&YCtr=" + Math.round(getProperty('YCtr') * 1000) / 1000 +
                            "<wbr>&ToneMode=" + getProperty('ToneMode');
			win.document.write('<a target = window.name href = ' + permalink + '><font color="#a000a0">' + permadisp + '</font></a>');
			if ( isIE )
			{
			    win.document.write('<form><input type = button value = " Copy & Close "');
			    win.document.write("onClick = \"clipboardData.setData('Text', '" + permalink + "'); window.close();\">");
			    win.document.write('</form>');
			}
			win.document.write('</div></body></html>'); 
			win.document.close();   
		}
	}

	function buildHTMLForInstall()
	{
		var style1 = 'align="center" style="color:white; width: 500px; background-color:#404040"';
		var style2 = 'style="text-align:center; font-size:x-large; font-weight:bold"';

		var imgInstall = '"' + hdvHelper.getCodepath() + 'HDInstall.jpg"';
		var pageInstall = '"' + hdvHelper.getCodepath() + 'HDInstall.htm"';
		
		// create an install message
		var html = "";
		html += '<table ' + style1 + '>';
        html += '<tr><td><p ' + style2 +'>L&quot;afficheur de panoramas HD View Beta2 doit être installé.</p></td></tr>';
        html += '<tr><td><em><br/>Afin d&quot;afficher le contenu de cet article, vous devez ';
		html += 'installer le plugin HD View.  Cliquez sur le bouton ci-dessous pour atteindre la page d&quot;installation.</em><br/></tr></td>';
        html += '<tr><td style="text-align:center"><br/>';
        html += '<a href=' + pageInstall + ' target="_top"><img alt="GOTO INSTALL" src=' + imgInstall + '/><br/><br/></td></tr></a>';
        html += '<tr><td><em>Si vous avez déjà installé le plugin et voyez toujours ce message, ';
		html += 'il vous faut relancer votre navigateur.</em><br/></tr></td>';
        html += '</table>';

	    return html;
	}

	function buildHTMLForControlIE(id, width, height)
	{
		var html = "";
		html += '<object id="' + id + '"';
		html += ' classid="CLSID:' + hdvHelper.getClsid() + '"';
		html += ' width='+width;
		html += ' height='+height;
		html += '></object>';

		// Handle IConnectionPoint events.
		html += '<SCRIPT LANGUAGE="JavaScript" FOR="' + id + '" EVENT="RotateEvent(f,y,p)">';
		html += 'try { onRotateEvent(f,y,p); } catch(e) {}';
		html += '</SCRIPT>';
		
		html += '<SCRIPT LANGUAGE="JavaScript" FOR="' + id + '" EVENT="TranslateEvent(z,x,y)">';
		html += 'try { onTranslateEvent(z,x,y); } catch(e) {}';
		html += '</SCRIPT>';

		html += '<SCRIPT LANGUAGE="JavaScript" FOR="' + id + '" EVENT="FrameEvent(n)">';
		html += 'try { onFrameEvent(n); } catch(e) {}';
		html += '</SCRIPT>';

		html += '<SCRIPT LANGUAGE="JavaScript" FOR="' + id + '" EVENT="PanModeEvent(n)">';
		html += 'try { onPanModeEvent(n); } catch(e) {}';
		html += '</SCRIPT>';

		html += '<SCRIPT LANGUAGE="JavaScript" FOR="' + id + '" EVENT="ToneModeEvent(n)">';
		html += 'try { onToneModeEvent(n); } catch(e) {}';
		html += '</SCRIPT>';

		return html;
	}

	function buildHTMLForControlFF(id, width, height)
	{
		var html = "";
		html += '<embed id="' + id + '"';
		html += ' type="' + hdvHelper.getMimeType() + '"';
		html += ' width='+width;
		html += ' height='+height;
		html += '></embed>';
		return html;
	}


	function buildHTMLForNotSupported()
	{
		var html = "";
		html += '<br><br><p style="color:#FF9933; font-size:large;">';
		html += 'L&quot;afficheur de panoramas ne fonctionne pas sur votre ordinateur.'
		html += '  Il nécessite Internet Explorer ou Firefox sur Windows XP, Serveur 2003, ou Vista.'
		html += '</p><br>';

		return html;
	}
}

// Handle Firefox callbacks.
function RotateEvent(f,y,p) { try { onRotateEvent(f,y,p); } catch(e) {} }
function TranslateEvent(z,x,y) { try { onTranslateEvent(z,x,y); } catch(e) {} }
function FrameEvent(n) { try { onFrameEvent(n); } catch(e) {} }
function PanModeEvent(n) { try { onPanModeEvent(n); } catch(e) {} }
function ToneModeEvent(n) { try { onToneModeEvent(n); } catch(e) {} }