﻿if (!window.Silverlight)
{
    window.Silverlight = { };
}

// Silverlight control instance counter for memory mgt
Silverlight._silverlightCount = 0;
Silverlight.fwlinkRoot='http://go2.microsoft.com/fwlink/?LinkID=';  
Silverlight.onGetSilverlight = null;
Silverlight.onSilverlightInstalled = function () {window.location.reload(false);};

//////////////////////////////////////////////////////////////////
// isInstalled, checks to see if the correct version is installed
//////////////////////////////////////////////////////////////////
Silverlight.isInstalled = function(version)
{
    var isVersionSupported=false;
    var container = null;
    
    try 
    {
        var control = null;
        
        try
        {
            control = new ActiveXObject('AgControl.AgControl');
            if ( version == null )
            {
                isVersionSupported = true;
            }
            else if ( control.IsVersionSupported(version) )
            {
                isVersionSupported = true;
            }
            control = null;
        }
        catch (e)
        {
            var plugin = navigator.plugins["Silverlight Plug-In"] ;
            if ( plugin )
            {
                if ( version === null )
                {
                    isVersionSupported = true;
                }
                else
                {
                    var actualVer = plugin.description;
                    if ( actualVer === "1.0.30226.2")
                        actualVer = "2.0.30226.2";
                    var actualVerArray =actualVer.split(".");
                    while ( actualVerArray.length > 3)
                    {
                        actualVerArray.pop();
                    }
                    while ( actualVerArray.length < 4)
                    {
                        actualVerArray.push(0);
                    }
                    var reqVerArray = version.split(".");
                    while ( reqVerArray.length > 4)
                    {
                        reqVerArray.pop();
                    }
                    
                    var requiredVersionPart ;
                    var actualVersionPart
                    var index = 0;
                    
                    
                    do
                    {
                        requiredVersionPart = parseInt(reqVerArray[index]);
                        actualVersionPart = parseInt(actualVerArray[index]);
                        index++;
                    }
                    while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
                    
                    if ( requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart) )
                    {
                        isVersionSupported = true;
                    }
                }
            }
        }
    }
    catch (e) 
    {
        isVersionSupported = false;
    }
    if (container) 
    {
        document.body.removeChild(container);
    }
    
    return isVersionSupported;
}
Silverlight.WaitForInstallCompletion = function()
{
    if ( ! Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled )
    {
        try
        {
            navigator.plugins.refresh();
        }
        catch(e)
        {
        }
        if ( Silverlight.isInstalled(null) )
        {
            Silverlight.onSilverlightInstalled();
        }
        else
        {
              setTimeout(Silverlight.WaitForInstallCompletion, 3000);
        }    
    }
}
Silverlight.__startup = function()
{
    Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null);//(!window.ActiveXObject || Silverlight.isInstalled(null));
    if ( !Silverlight.isBrowserRestartRequired)
    {
        Silverlight.WaitForInstallCompletion();
    }
    if (window.removeEventListener) { 
       window.removeEventListener('load', Silverlight.__startup , false);
    }
    else { 
        window.detachEvent('onload', Silverlight.__startup );
    }
}

if (window.addEventListener) 
{
    window.addEventListener('load', Silverlight.__startup , false);
}
else 
{
    window.attachEvent('onload', Silverlight.__startup );
}

///////////////////////////////////////////////////////////////////////////////
// createObject();  Params:
// parentElement of type Element, the parent element of the Silverlight Control
// source of type String
// id of type string
// properties of type String, object literal notation { name:value, name:value, name:value},
//     current properties are: width, height, background, framerate, isWindowless, enableHtmlAccess, inplaceInstallPrompt:  all are of type string
// events of type String, object literal notation { name:value, name:value, name:value},
//     current events are onLoad onError, both are type string
// initParams of type Object or object literal notation { name:value, name:value, name:value}
// userContext of type Object
/////////////////////////////////////////////////////////////////////////////////

Silverlight.createObject = function(source, parentElement, id, properties, events, initParams, userContext)
{
    var slPluginHelper = new Object();
    var slProperties = properties;
    var slEvents = events;
    
    slPluginHelper.version = slProperties.version;
    slProperties.source = source;    
    slPluginHelper.alt = slProperties.alt;
    
    //rename properties to their tag property names
    if ( initParams )
        slProperties.initParams = initParams;
    if ( slProperties.isWindowless && !slProperties.windowless)
        slProperties.windowless = slProperties.isWindowless;
    if ( slProperties.framerate && !slProperties.maxFramerate)
        slProperties.maxFramerate = slProperties.framerate;
    if ( id && !slProperties.id)
        slProperties.id = id;
    
    // remove elements which are not to be added to the instantiation tag
    delete slProperties.ignoreBrowserVer;
    delete slProperties.inplaceInstallPrompt;
    delete slProperties.version;
    delete slProperties.isWindowless;
    delete slProperties.framerate;
    delete slProperties.data;
    delete slProperties.src;
    delete slProperties.alt;


    // detect that the correct version of Silverlight is installed, else display install

    if (Silverlight.isInstalled(slPluginHelper.version))
    {
        //move unknown events to the slProperties array
        for (var name in slEvents)
        {
            if ( slEvents[name])
            {
                if ( name == "onLoad" && typeof slEvents[name] == "function" && slEvents[name].length != 1 )
                {
                    var onLoadHandler = slEvents[name];
                    slEvents[name]=function (sender){ return onLoadHandler(document.getElementById(id), userContext, sender)};
                }
                var handlerName = Silverlight.__getHandlerName(slEvents[name]);
                if ( handlerName != null )
                {
                    slProperties[name] = handlerName;
                    slEvents[name] = null;
                }
                else
                {
                    throw "typeof events."+name+" must be 'function' or 'string'";
                }
            }
        }
        slPluginHTML = Silverlight.buildHTML(slProperties);
    }
    //The control could not be instantiated. Show the installation prompt
    else 
    {
        slPluginHTML = Silverlight.buildPromptHTML(slPluginHelper);
    }

    // insert or return the HTML
    if(parentElement)
    {
        parentElement.innerHTML = slPluginHTML;
    }
    else
    {
        return slPluginHTML;
    }

}

///////////////////////////////////////////////////////////////////////////////
//
//  create HTML that instantiates the control
//
///////////////////////////////////////////////////////////////////////////////
Silverlight.buildHTML = function( slProperties)
{
    var htmlBuilder = [];

    htmlBuilder.push('<object type=\"application/x-silverlight\" data="data:application/x-silverlight,"');
    if ( slProperties.id != null )
    {
        htmlBuilder.push(' id="' + slProperties.id + '"');
    }
    if ( slProperties.width != null )
    {
        htmlBuilder.push(' width="' + slProperties.width+ '"');
    }
    if ( slProperties.height != null )
    {
        htmlBuilder.push(' height="' + slProperties.height + '"');
    }
    htmlBuilder.push(' >');
    
    delete slProperties.id;
    delete slProperties.width;
    delete slProperties.height;
    
    for (var name in slProperties)
    {
        if (slProperties[name])
        {
            htmlBuilder.push('<param name="'+Silverlight.HtmlAttributeEncode(name)+'" value="'+Silverlight.HtmlAttributeEncode(slProperties[name])+'" />');
        }
    }
    htmlBuilder.push('<\/object>');
    return htmlBuilder.join('');
}




// createObjectEx, takes a single parameter of all createObject parameters enclosed in {}
Silverlight.createObjectEx = function(params)
{
    var parameters = params;
    var html = Silverlight.createObject(parameters.source, parameters.parentElement, parameters.id, parameters.properties, parameters.events, parameters.initParams, parameters.context);
    if (parameters.parentElement == null)
    {
        return html;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////
// Builds the HTML to prompt the user to download and install Silverlight
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.buildPromptHTML = function(slPluginHelper)
{
    var slPluginHTML = "";
    var urlRoot = Silverlight.fwlinkRoot;
    var shortVer = slPluginHelper.version ;
    if ( slPluginHelper.alt )
    {
        slPluginHTML = slPluginHelper.alt;
    }
    else
    {
        if (! shortVer )
        {
            shortVer="";
        }
        slPluginHTML = "<a href='javascript:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>";
        slPluginHTML = slPluginHTML.replace('{1}', shortVer );
        slPluginHTML = slPluginHTML.replace('{2}', urlRoot + '108181');
    }
    
    return slPluginHTML;
}


Silverlight.getSilverlight = function(version)
{
    if (Silverlight.onGetSilverlight )
    {
        Silverlight.onGetSilverlight();
    }
    
    var shortVer = "";
    var reqVerArray = String(version).split(".");
    if (reqVerArray.length > 1)
    {
        var majorNum = parseInt(reqVerArray[0] );
        if ( isNaN(majorNum) || majorNum < 2 )
        {
            shortVer = "1.0";
        }
        else
        {
            shortVer = reqVerArray[0]+'.'+reqVerArray[1];
        }
    }
    
    var verArg = "";
    
    if (shortVer.match(/^\d+\056\d+$/) )
    {
        verArg = "&v="+shortVer;
    }
    
    Silverlight.followFWLink("114576" + verArg);
}


///////////////////////////////////////////////////////////////////////////////////////////////
/// Navigates to a url based on fwlinkid
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.followFWLink = function(linkid)
{
    top.location=Silverlight.fwlinkRoot+String(linkid);
}












///////////////////////////////////////////////////////////////////////////////////////////////
/// Encodes special characters in input strings as charcodes
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.HtmlAttributeEncode = function( strInput )
{
      var c;
      var retVal = '';

    if(strInput == null)
      {
          return null;
    }
      
      for(var cnt = 0; cnt < strInput.length; cnt++)
      {
            c = strInput.charCodeAt(cnt);

            if (( ( c > 96 ) && ( c < 123 ) ) ||
                  ( ( c > 64 ) && ( c < 91 ) ) ||
                  ( ( c > 43 ) && ( c < 58 ) && (c!=47)) ||
                  ( c == 95 ))
            {
                  retVal = retVal + String.fromCharCode(c);
            }
            else
            {
                  retVal = retVal + '&#' + c + ';';
            }
      }
      
      return retVal;
}
///////////////////////////////////////////////////////////////////////////////
//
//  Default error handling function to be used when a custom error handler is
//  not present
//
///////////////////////////////////////////////////////////////////////////////

Silverlight.default_error_handler = function (sender, args)
{
    var iErrorCode;
    var errorType = args.ErrorType;

    iErrorCode = args.ErrorCode;

    var errMsg = "\nSilverlight error message     \n" ;

    errMsg += "ErrorCode: "+ iErrorCode + "\n";


    errMsg += "ErrorType: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError")
    {
        errMsg += "XamlFile: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError")
    {
        if (args.lineNumber != 0)
        {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " +  args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }
    alert (errMsg);
}

///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__cleanup = function ()
{
    for (var i = Silverlight._silverlightCount - 1; i >= 0; i--) {
        window['__slEvent' + i] = null;
    }
    Silverlight._silverlightCount = 0;
    if (window.removeEventListener) { 
       window.removeEventListener('unload', Silverlight.__cleanup , false);
    }
    else { 
        window.detachEvent('onunload', Silverlight.__cleanup );
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////
/// Releases event handler resources when the page is unloaded
///////////////////////////////////////////////////////////////////////////////////////////////
Silverlight.__getHandlerName = function (handler)
{
    var handlerName = "";
    if ( typeof handler == "string")
    {
        handlerName = handler;
    }
    else if ( typeof handler == "function" )
    {
        if (Silverlight._silverlightCount == 0)
        {
            if (window.addEventListener) 
            {
                window.addEventListener('onunload', Silverlight.__cleanup , false);
            }
            else 
            {
                window.attachEvent('onunload', Silverlight.__cleanup );
            }
        }
        var count = Silverlight._silverlightCount++;
        handlerName = "__slEvent"+count;
        
        window[handlerName]=handler;
    }
    else
    {
        handlerName = null;
    }
    return handlerName;
}

//----------------------------------------------------------------------//
// IDV Solutions Visual Fusion Suite                                    //
// Copyright (C) 2008 IDV Solutions                                     //
//----------------------------------------------------------------------//

// create 'browser is IE' flag
var VfxBrowserIsIE = false;

// register for scroll wheel events
if (window.addEventListener) {
    window.addEventListener('mousewheel', VfxHandleScrollWheel, true); // WebKit
    window.addEventListener('DOMMouseScroll', VfxHandleScrollWheel, true); // Firefox
} else {
    window.onmousewheel = document.onmousewheel = VfxHandleScrollWheel; // IE
    VfxBrowserIsIE = true;
}


// Constructs a new XAP host instance
function VfxXapHost(div, src, id) {
   this.Initialize(div, src, id);
};

// Table of XAP instances
VfxXapHost.Instances = new Object();
VfxXapHost.NamedInst = new Object();

// Accessor for XAP host instances
VfxXapHost.GetXap = function(id) {
   return VfxXapHost.NamedInst[id];
}

// Convenience method for getting map interface
VfxXapHost.prototype.GetMap = function() {
   return this.GetInterface("Map");
}

// Convenience method for getting the feeds interface
VfxXapHost.prototype.GetFeeds = function() {
   return this.GetInterface("Feeds");
}

// Loads the XAP file into the browser
// init: (optional) arguments in form "arg1=value1&arg2=value2&..."
VfxXapHost.prototype.LoadXap = function(init)
{
	Silverlight.createObjectEx({
	   parentElement: document.getElementById(this.XapDiv),
	   initParams: init,
	   source: this.Source,
	   id: this.ID,
	   properties: {
		   width: "100%",
		   height: "100%",
		   version: "2.0",
		   enableHtmlAccess: "true",
		   isWindowless: "false"
	   },
	   events: {
		   onLoad:  this.HandleXapLoaded,
		   onError: this.HandleXapError
	   }
   });
}


// Constructs a new VfxXapHost object instance
VfxXapHost.prototype.Initialize = function(div, src, id)
{
   // setup internal properties
   this.ID = div+"_xapobj";
   this.XapDiv = div+"Xap";
   this.VfxVer = "Unknown";
   this.Parent = div;
   this.Source = src;
   this.Loaded = false;
   this.UrlVars = new Object();
   this.InitVars = new Object();

   // save reference to XapHost object
   VfxXapHost.Instances[this.ID] = this;

   // store in named instances table
   if(id != null && id.length > 0) {
      VfxXapHost.NamedInst[id] = this;
   }
}


// Called when XAP file has been loaded [NOTE: this
// method is executed in context other than VfxXapHost]
VfxXapHost.prototype.HandleXapLoaded = function(sender, args)
{
   if(sender != null) {
      VfxXapHost.Instances[sender.id].HandleXapLoadedImpl(sender, args);
   }
}


// An error occured inside of the XAP file [NOTE: this
// method is executed in context other than VfxXapHost]
VfxXapHost.prototype.HandleXapError = function(sender, args)
{
   if(args.errorType != "ImageError") {
      for(var i in VfxXapHost.Instances) {
         VfxXapHost.Instances[i].HandleXapErrorImpl(sender, args);
      }
   }
}


// Obtains an interface into the VFX application
VfxXapHost.prototype.GetInterface = function(name)
{
   try {
      return this.ManagedObject.Content[name];
   } catch(ex) {
      return null;
   }
}


// Sets the value of a URL variable [this must
// be called BEFORE calling the LoadXap method,
// otherwise the url variable will be ignored]
VfxXapHost.prototype.SetUrlVariable = function(name, value)
{
   this.UrlVars[name] = value;
}


// Sets a variable to use during initialization
VfxXapHost.prototype.SetInitVariable = function(name, value)
{
   this.InitVars[name] = value;
}


// Called when XAP file has been loaded
VfxXapHost.prototype.HandleXapLoadedImpl = function(sender, args)
{
   // save reference to managed XAP object
   this.ManagedObject = sender;
   this.Common = this.GetInterface("VfxXapHostCommon");
   this.Loaded = true;

   // get URL of this application;
   // get common XapHost interface
   var common = this.Common;
   var loc = window.location;

   // initialize silverlight control
   if(common != null) {

      // set common URL varaibles
      this.VfxVer = common.GetVfxVersion();
      common.SetUrlVariable("host", loc.host);
      common.SetUrlVariable("webapp", this.GetWebApp(loc));
      common.SetUrlVariable("domain", this.GetDomain(loc));

      // set initialization variables
      for(var i in this.InitVars) {
         common.SetInitVariable(i, this.InitVars[i]);
      }

      // set any other URL variable
      for(var i in this.UrlVars) {
         common.SetUrlVariable(i, this.UrlVars[i]);
      }

      // let Silverlight know JS is ready
      common.JavaScriptIsReady(this.Parent);
   }

   // notify caller that load has occured
   if(this.onLoadXap != null) {
      this.onLoadXap();
   }
}


// Gets value for the {domain} URL varible
VfxXapHost.prototype.GetDomain = function(loc)
{
   return (loc.protocol+"//"+loc.host);
}


// Gets value for the {domain} URL varible
VfxXapHost.prototype.GetWebApp = function(loc)
{
   var url = loc.href;
   var i = url.lastIndexOf('/');
   if(i >= 0) {
      return url.substring(0, i+1);
   } else {
      return url;
   }
}


// An error occured inside of the XAP file
VfxXapHost.prototype.HandleXapErrorImpl = function(sender, args)
{
   var newNode;
   var parNode;
   var errMsg;

   // create new text area element
   errMsg = this.CreateDefaultErrMsg(args);

   // update Silverlight control host
   parNode = document.getElementById(this.Parent);

   // remove all child nodes
   while(parNode.firstChild != null) {
      parNode.removeChild(parNode.firstChild);
   }

   // create and embed a new text area
   newNode = document.createElement("textarea");
   newNode.appendChild(document.createTextNode(errMsg));
   newNode.setAttribute("cols", Math.floor((parNode.clientWidth/8)-10));
   newNode.setAttribute("rows", Math.floor(parNode.clientHeight/18));
   newNode.setAttribute("readOnly", "readonly");
   newNode.setAttribute("wrap", "off");
   parNode.appendChild(newNode);

   // clear map viewer reference
   gMapViewer = null;
}


// Message for runtime failure
VfxXapHost.prototype.CreateDefaultErrMsg = function(args)
{
   if(args.errorType == "InitializeError" && args.errorCode == 2104) {
      return (
         "Could not download the Silverlight XAP file.\r\n"+
         "Check web server settings and ensure that *.xap\r\n"+
         "files are supported in MIME type settings. See\r\n"+
         "http://learn.iis.net/page.aspx/262/silverlight/\r\n"+
         "for server setup instructions."
      );
   } else {
      return (
         "Silverlight Application Error\r\r"+
         "VFX Version:  " + this.VfxVer    +"\r"+
         "VFX XAP File: " + this.Source    +"\r"+
         "VFX XAP ID:   " + this.ID        +"\r"+
         "Error Type:   " + args.errorType +"\r"+
         "Error Code:   " + args.errorCode +"\r"+
         "\r"+ args.errorMessage +"\r"
      );
   }
}


// Called when scroll wheel is used
function VfxHandleScrollWheel(event) {
    //var m;
    var intDelta = 0;

    // get scroll wheel event
    event = (event) ? event : window.event

    // get actual scroll wheel value
    if (event.wheelDelta) {
        if (window.opera) {
            intDelta = -event.wheelDelta;
        } else {
            intDelta = event.wheelDelta;
        }
    } else if (event.detail) {
        intDelta = -event.detail;
    }

    // calculate change in scroll wheel
    intDelta = (intDelta > 0) ? 1 : -1;

    // pass scroll wheel event to all XAPs
    if (VfxXapHost.Instances != null) {
        for (var i in VfxXapHost.Instances) {
            var common = VfxXapHost.Instances[i].Common;
            if (common != null) {
                common.HandleScrollWheel(intDelta);
            }
        }
    }

    // mark event as handeled
    if (VfxBrowserIsIE) {
        event.returnValue = false;
    } else {
        event.preventDefault();
        event.stopPropagation();
    }
}
