//
// 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); 
 
 var isOpera = (ua.indexOf("Opera") != -1);
    var isOther = (isOpera);
    
 // 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)) && !isOther} 
 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(parms)
{ 
 // 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        = parms.id;
 var argElementId = parms.elementId;
 var argWidth     = parms.width;
 var argHeight    = parms.height;
 var argHref      = parms.href; 
 var argArgs      = parms.args;
 var argStatImgSrc   = parms.statImgSrc;
 var argStatImgAlt   = parms.statImgAlt;
 
 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('HDView.NS');
       var statImg = document.getElementById('HDView.NS.Image');
       statImg.src = argStatImgSrc;
       var srcCredit = document.getElementById('HDView.Credit');
       var srcCaption = document.getElementById('HDView.Caption');
       document.getElementById('HDView.NS.Credit').innerHTML +=  srcCredit.innerHTML;
       document.getElementById('HDView.NS.Caption').innerHTML = srcCaption.innerHTML;  
       srcCredit.innerHTML = "&nbsp;";
       srcCaption.innerHTML = "&nbsp;";
  }
  else {
   if ( !hdvHelper.isHDViewInstalled() ) {
        document.getElementById(argElementId).innerHTML = buildHTMLForInstall('HDView.Install');
        var srcCredit = document.getElementById('HDView.Credit');
        var srcCaption = document.getElementById('HDView.Caption');
        srcCredit.innerHTML = "&nbsp;";
        srcCaption.innerHTML = "&nbsp;";
        HDI_setup('HDView.Install.Link', 'HDView.Install.Link.Image'); 
   }
   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(Id)
 {
     return getInnerHTML(Id);
 }

 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(Id)
 {
  return getInnerHTML(Id);
 }
 
 function getInnerHTML(Id)
 {
  var html = "";
  var temp = document.getElementById(Id);
  if(temp)
  {
      html = temp.innerHTML;
      temp.innerHTML = "";
  }
  return html;
 }
 
 function setCredit(source, target)
 {
    document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
 }
}

// 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) {} }

function HDI_setup(urlid, imgid) {
 var codepath = "http://msnbcmedia2.msn.com/i/msnbc/Components/downloads/";
 var imgpath = "http://msnbcmedia4.msn.com/j/msnbc/Components/Media/HDView/InstallImages/";
 var isIE = ( navigator.userAgent.indexOf( "MSIE" ) != -1 );
 urlelm = document.getElementById(urlid);
 imgelm = document.getElementById(imgid);
 document.$imgSwaps=new Array();
 if( isIE ) {
  urlelm.href = codepath + 'HDViewInstall_1_20_IE.msi';
 }
 else {
  urlelm.href = codepath + 'HDViewInstall_1_20_FF.msi';
 }
    document.$imgSwaps[0] = imgpath + "HDInstall1.gif,standard.jpg"; 
    document.$imgSwaps[1] = imgpath + "HDInstall2.gif,standard.jpg"; 
    document.$imgSwaps[2] = imgpath + "HDInstall3.gif,standard.jpg"; 
 imgelm.src = document.$imgSwaps[0]; 
}

function HDI_swapImg(id, i) {
var elm = document.getElementById(id);
 elm.src = document.$imgSwaps[i];
}