//
// HDView2.js    copyright 2007, Microsoft Corporation
//
// This script contains helper functions for initializing the HD View
// control.  Currently HD View is supported on IE, Firefox, Flock, Netscape,
// and Safari 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 ||  // also true for Flock, Netscape
	                  ua.indexOf( "Safari" ) != -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,22";  }
	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[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[0] == pluginVersionArray[0] && 
								 reqVersionArray[3] <= pluginVersionArray[3]);
				}
			}
		}
		catch (e) {}
		return installed;
	}
};
var hdvHelper = new hdvHelperFn();

var argIFrame = 0;
function hdvIFrame(IFrame)
{
    argIFrame = IFrame;
}

function hdvHost(id, elementId, width, height, href, args)
{	
	// variables that determine the platform
	var ua   = navigator.userAgent;
	var isIE      = ( ua.indexOf( "MSIE" ) != -1 );
	var isSafari  = ( ua.indexOf( "Safari" ) != -1 );
	var isFF      = ( ua.indexOf( "Firefox" ) != -1 ||  // also true for Flock, Netscape
	                  isSafari );

	// 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;
	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'.
	// 
	window.onload = onLoad;

	constructor();

	function onLoad()
	{
		setArgs(argArgs);
	}

	function constructor()
	{
		if ( !hdvHelper.isPlatformSupported() ) {
		    document.getElementById(argElementId).innerHTML = 
				buildHTMLForNotSupported();
		}
		else {
			if ( !hdvHelper.isHDViewInstalled() ) {
				document.getElementById(argElementId).innerHTML = 
					buildHTMLForInstall();
			}
			else {
				document.getElementById(argElementId).innerHTML =
					buildHTMLForControl(argId, argWidth, argHeight);
			}
        }
	}

    // other functions
	function setArgs(argString)
	{ 
		if( hdvHelper.isPlatformSupported() ) {
			var args = argString.split('&');
			for (var i = 0; i < args.length; i++) {   
				var arg = args[i].indexOf("=");
				setProperty(args[i].substr(0,arg), args[i].substr(arg+1));
			}
		}
	}

	function setProperty(prop, val)
	{
		if( hdvHelper.isPlatformSupported() ) {    
			if( prop == "FileName" ) {
			    val = unescape(val);
				curFilename = val;
				if ( argIFrame == 0 )
				{
				    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( prop == "FOV" || prop == "Yaw" || prop == "Pitch" ||
				prop == "Zoom" || prop == "XCtr" || prop == "YCtr" )
			{
				var separator = Number(1.1).toLocaleString().charAt(1);
				val = val.replace('/\\' + separator + '/', '.');
			}
			
			if( prop == "BackgroundColor" )
			    val = parseInt(val);

			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=450, height=180"); 
			win.document.open(); 
			win.document.write('<html><body>');
			win.document.write('<div align="center">');

			var pageArgs = argHref.split('?');
			var pagePath = pageArgs[0].substring(0, pageArgs[0].lastIndexOf('/') + 1);

            var escfile   = escape(curFilename);
			var permafile = "FileName=" + escfile; 
			var embedfile = "FileName=" + pagePath + escfile;
			var permalinkargs = "&BackgroundColor=0x" + Number(getProperty('BackgroundColor')).toString(16) +
							"&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 +
				            "&PanMode=" + getProperty('PanMode') +
				            "&ProjMode=" + getProperty('ProjMode') +
				            "&ToneMode=" + getProperty('ToneMode');
            var iframe = "<iframe frameborder='0' scrolling='no' marginwidth='0' marginheight='0' src='" +
                hdvHelper.getCodepath() + "HDIFrame.htm?" + embedfile + permalinkargs + "'></iframe>";

            win.document.write('<form id=LinkForm name=LinkForm>');
            win.document.write('Link to paste in email or IM: <input type="text" id="PermaLink" size="50" value="' +
                pageArgs[0] + '?' + permafile + permalinkargs + '" contentEditable="false" onclick="select()"><br><br>');
            win.document.write('HTML to embed in web site: <input type="text" id="IFrame" size="50" value="' +
                iframe + '" contentEditable="false" onclick="select()"><br><br>');
			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"';
		if (document.body.clientWidth < 500)
		{
		    style1 = 'align="center" style="color:white; width: 320px; background-color:#404040"';
		    style2 = 'style="text-align:center; font-size:large; font-weight:bold"';
		}

		var imgInstall = '"' + hdvHelper.getCodepath() + 'images/HDInstall.jpg"';
		var pageInstall = '"' + hdvHelper.getCodepath() + 'HDInstall.htm"';
		
		var reqVersionArray = hdvHelper.getVersion().split(',');
		
		// create an install message
		var html = "";
		html += '<table ' + style1 + '>';
        html += '<tr><td ' + style2 +'>HD View Beta 3-' + reqVersionArray[0] + '.0.0.' + reqVersionArray[3] + ' needs to be installed.</td></tr>';
        html += '<tr><td><em><br/>In order to view the content on this page you ';
		html += 'must install the HD View Add-on.  Please click on the button below to visit the install page.</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>If you have already installed Beta3 and you still see this message, ';
		html += 'then you need to restart your browser.</em><br/></tr></td>';
        html += '</table>';

	    return html;
	}

	function buildHTMLForControl(id, width, height)
	{
		var html = "";
		html += '<object id="' + id + '"';
		html += ' type="' + hdvHelper.getMimeType() + '"';
		html += ' width='+width;
		html += ' height='+height;
		html += '></object>';

		return html;
	}

	function buildHTMLForNotSupported()
	{
		var html = "";
		html += '<br><br><p style="color:#FF9933; font-size:large;">';
		html += 'Sorry the HD View Beta is not supported on this platform.'
		html += '  Must be Internet Explorer, Firefox, Flock, Netscape, or Safari on Windows XP, Server 2003, or Vista.'
		html += '</p><br>';

		return html;
	}
}
