//Silverlight.js 
//  Copyright (c) 2007 Microsoft Corporation. All rights reserved.
//
if(!window.Silverlight)window.Silverlight={};Silverlight._silverlightCount=0;Silverlight.ua=null;Silverlight.available=false;Silverlight.fwlinkRoot="http://go.microsoft.com/fwlink/?LinkID=";Silverlight.detectUserAgent=function(){var a=window.navigator.userAgent;Silverlight.ua={OS:"Unsupported",Browser:"Unsupported"};if(a.indexOf("Windows NT")>=0)Silverlight.ua.OS="Windows";else if(a.indexOf("PPC Mac OS X")>=0)Silverlight.ua.OS="MacPPC";else if(a.indexOf("Intel Mac OS X")>=0)Silverlight.ua.OS="MacIntel";if(Silverlight.ua.OS!="Unsupported")if(a.indexOf("MSIE")>=0){if(navigator.userAgent.indexOf("Win64")==-1)if(parseInt(a.split("MSIE")[1])>=6)Silverlight.ua.Browser="MSIE"}else if(a.indexOf("Firefox")>=0){var b=a.split("Firefox/")[1].split("."),c=parseInt(b[0]);if(c>=2)Silverlight.ua.Browser="Firefox";else{var d=parseInt(b[1]);if(c==1&&d>=5)Silverlight.ua.Browser="Firefox"}}else if(a.indexOf("Safari")>=0)Silverlight.ua.Browser="Safari"};Silverlight.detectUserAgent();Silverlight.isInstalled=function(d){var c=false,a=null;try{var b=null;if(Silverlight.ua.Browser=="MSIE")b=new ActiveXObject("AgControl.AgControl");else if(navigator.plugins["Silverlight Plug-In"]){a=document.createElement("div");document.body.appendChild(a);if(Silverlight.ua.Browser=="Safari")a.innerHTML='<embed type="application/x-silverlight" />';else a.innerHTML='<object type="application/x-silverlight"  data="data:," />';b=a.childNodes[0]}document.body.innerHTML;if(b.IsVersionSupported(d))c=true;b=null;Silverlight.available=true}catch(e){c=false}if(a)document.body.removeChild(a);return c};Silverlight.createObject=function(l,g,m,j,k,i,h){var b={},a=j,c=k;a.source=l;b.parentElement=g;b.id=Silverlight.HtmlAttributeEncode(m);b.width=Silverlight.HtmlAttributeEncode(a.width);b.height=Silverlight.HtmlAttributeEncode(a.height);b.ignoreBrowserVer=Boolean(a.ignoreBrowserVer);b.inplaceInstallPrompt=Boolean(a.inplaceInstallPrompt);var e=a.version.split(".");b.shortVer=e[0]+"."+e[1];b.version=a.version;a.initParams=i;a.windowless=a.isWindowless;a.maxFramerate=a.framerate;for(var d in c)if(c[d]&&d!="onLoad"&&d!="onError"){a[d]=c[d];c[d]=null}delete a.width;delete a.height;delete a.id;delete a.onLoad;delete a.onError;delete a.ignoreBrowserVer;delete a.inplaceInstallPrompt;delete a.version;delete a.isWindowless;delete a.framerate;delete a.data;delete a.src;if(Silverlight.isInstalled(b.version)){if(Silverlight._silverlightCount==0)if(window.addEventListener)window.addEventListener("onunload",Silverlight.__cleanup,false);else window.attachEvent("onunload",Silverlight.__cleanup);var f=Silverlight._silverlightCount++;a.onLoad="__slLoad"+f;a.onError="__slError"+f;window[a.onLoad]=function(a){if(c.onLoad)c.onLoad(document.getElementById(b.id),h,a)};window[a.onError]=function(a,b){if(c.onError)c.onError(a,b);else Silverlight.default_error_handler(a,b)};slPluginHTML=Silverlight.buildHTML(b,a)}else slPluginHTML=Silverlight.buildPromptHTML(b);if(b.parentElement)b.parentElement.innerHTML=slPluginHTML;else return slPluginHTML};Silverlight.supportedUserAgent=function(){var a=Silverlight.ua,b=a.OS=="Unsupported"||a.Browser=="Unsupported"||a.OS=="Windows"&&a.Browser=="Safari"||a.OS.indexOf("Mac")>=0&&a.Browser=="IE";return !b};Silverlight.buildHTML=function(c,d){var a=[],e,i,g,f,h;if(Silverlight.ua.Browser=="Safari"){a.push("<embed ");e="";i=" ";g='="';f='"';h=' type="application/x-silverlight"/>'+"<iframe style='visibility:hidden;height:0;width:0'/>"}else{a.push('<object type="application/x-silverlight" data="data:,"');e=">";i=' <param name="';g='" value="';f='" />';h="</object>"}a.push(' id="'+c.id+'" width="'+c.width+'" height="'+c.height+'" '+e);for(var b in d)if(d[b])a.push(i+Silverlight.HtmlAttributeEncode(b)+g+Silverlight.HtmlAttributeEncode(d[b])+f);a.push(h);return a.join("")};Silverlight.default_error_handler=function(e,b){var d,c=b.ErrorType;d=b.ErrorCode;var a="\nSilverlight error message     \n";a+="ErrorCode: "+d+"\n";a+="ErrorType: "+c+"       \n";a+="Message: "+b.ErrorMessage+"     \n";if(c=="ParserError"){a+="XamlFile: "+b.xamlFile+"     \n";a+="Line: "+b.lineNumber+"     \n";a+="Position: "+b.charPosition+"     \n"}else if(c=="RuntimeError"){if(b.lineNumber!=0){a+="Line: "+b.lineNumber+"     \n";a+="Position: "+b.charPosition+"     \n"}a+="MethodName: "+b.methodName+"     \n"}alert(a)};Silverlight.createObjectEx=function(b){var a=b,c=Silverlight.createObject(a.source,a.parentElement,a.id,a.properties,a.events,a.initParams,a.context);if(a.parentElement==null)return c};Silverlight.buildPromptHTML=function(l){var a=null,d=Silverlight.fwlinkRoot,c=Silverlight.ua.OS,b="92822",e,f="Get Microsoft Silverlight",m="0x409";if(l.inplaceInstallPrompt){var n="98109",i;if(Silverlight.available){e="96189";i="96422"}else{e="96188";i="96422"}var h="93481",g="93483";if(c=="Windows"){b="92799";h="92803";g="92805"}else if(c=="MacIntel"){b="92808";h="92804";g="92806"}else if(c=="MacPPC"){b="92807";h="92815";g="92816"}var k='By clicking <b>"Get Microsoft Silverlight"</b> you accept the<br /><a title="Silverlight License Agreement" href="{2}" target="_top" style="text-decoration: underline; color: #96C5E1"><b>Silverlight license agreement</b></a>',j='Silverlight updates automatically, <a title="Silverlight Privacy Statement" href="{3}" target="_top" style="text-decoration: underline; color: #96C5E1"><b>learn more</b></a>';a='<table border="0" cellpadding="0" cellspacing="0" width="206px"><tr><td><img style="display: block; cursor: pointer; border= 0;" title="'+f+'" alt="'+f+'" onclick="javascript:Silverlight.followFWLink({0});" src="{1}" /></td></tr><tr><td style="width: 206px; margin: 0px; background: #FFFFFF; color: #C7C7C7; text-align: left; border-left-style: solid; border-right-style: solid; padding-left: 6px; padding-right: 6px; padding-top: 3px; padding-bottom: 0px; border-width: 2px; border-color: #c7c7bd; font-family: Verdana; font-size: 55%">'+k+'</td></tr><tr><td><img src="{5}" style="border: 0; display: block" /></td></tr><tr><td style="width: 206px; margin: 0px; background: #D8EFF9; color: #C7C7C7; text-align: left; border-left-style: solid; border-right-style: solid; padding-left: 6px; padding-right: 6px; padding-top: 0px; padding-bottom: 2px; border-width: 2px; border-color: #c7c7bd; font-family: Verdana; font-size: 55%">'+j+'</td></tr><tr><td><img alt="" src="{4}" /></td></tr></table>';a=a.replace("{2}",d+h);a=a.replace("{3}",d+g);a=a.replace("{4}",d+i);a=a.replace("{5}",d+n)}else{if(Silverlight.available)e="94377";else e="92801";if(c=="Windows")b="92800";else if(c=="MacIntel")b="92812";else if(c=="MacPPC")b="92811";a='<div style="display:block; width: 205px; height: 67px;"><img onclick="javascript:Silverlight.followFWLink({0});" style="border:0; cursor:pointer" src="{1}" title="'+f+'" alt="'+f+'"/></div>'}a=a.replace("{0}",b);a=a.replace("{1}",d+e+"&amp;clcid="+m);return a};Silverlight.__cleanup=function(){for(var a=Silverlight._silverlightCount-1;a>=0;a--){window["__slLoad"+a]=null;window["__slError"+a]=null}if(window.removeEventListener)window.removeEventListener("unload",Silverlight.__cleanup,false);else window.detachEvent("onunload",Silverlight.__cleanup)};Silverlight.followFWLink=function(a){top.location=Silverlight.fwlinkRoot+String(a)};Silverlight.HtmlAttributeEncode=function(c){var a,b="";if(c==null)return null;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);if(a>96&&a<123||a>64&&a<91||a>43&&a<58&&a!=47||a==95)b=b+String.fromCharCode(a);else b=b+"&#"+a+";"}return b}


//XML.js 
//  Copyright (c) ?? ??. All rights reserved.
//
var _XMLRef = null;

function XML( )
{ 
	this.XML = "";
	this.url = null;
	this.Error = false;
	this.ErrorMessage = "";
	this.HTTPRequestObject = null;
	this.XmlDocument = null;
} 

XML.prototype =
{
	LoadXml: function( XML )
	{
		_XMLRef = this;
		_XMLRef.XML = XML;
		if (!window.ActiveXObject)
		{
			var parser = new DOMParser();
			_XMLRef.XmlDocument = parser.parseFromString(XML,"text/xml");
		}
		else //is IE...
		{ 
			_XMLRef.XmlDocument = new ActiveXObject("Microsoft.XMLDOM");
			_XMLRef.XmlDocument.async = "false";
			_XMLRef.XmlDocument.loadXML(XML);
		}
	},
	
	Load: function( url )
	{
		this.url = url;
		
		_XMLRef = this;
		
		if (window.XMLHttpRequest)
		{ 
			// everyone but ie 5 and 6...
			this.HTTPRequestObject = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// IE 5 and 6
			try
			{
				this.HTTPRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); 
			}
			catch (Exception)
			{
				this.Error = true;
				this.ErrorMessage = Exception.description;
			}
		}
		else 
		{
			// we don't support xml...  try the xml mini me...
			this.Error = true;
			this.ErrorMessage = e.description;
		}		
		
		if (this.HTTPRequestObject && !this.Error ) 
		{
			this.HTTPRequestObject.open("GET", this.url, true); 
			this.HTTPRequestObject.onreadystatechange = this.XMLObjCallback;
			this.HTTPRequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			this.HTTPRequestObject.send(null);
		}
		
	},

	XMLObjCallback: function( )
	{
		// Check for the completed status
		if (_XMLRef.HTTPRequestObject.readyState == 4) 
		{
			// Check for successful server response
			if (_XMLRef.HTTPRequestObject.status == 200)
			{
				if( _XMLRef.XML == "" )
				{
					_XMLRef.XML = _XMLRef.HTTPRequestObject.responseText;
				}
				
				if (!window.ActiveXObject)
				{
					var parser = new DOMParser();
					_XMLRef.XmlDocument = parser.parseFromString(_XMLRef.XML,"text/xml");
				}
				else //is i.e
				{ 
					_XMLRef.XmlDocument = new ActiveXObject("Microsoft.XMLDOM");
					_XMLRef.XmlDocument.async = "false";
					_XMLRef.XmlDocument.loadXML(_XMLRef.XML);
				}
			}
			else 
			{
				// HTTP error
				alert('Error: ' + _XMLRef.HTTPRequestObject.status);
			} 
		} 
	},

	SelectNodesAttributes: function( NodeName, AttributeName )
	{
		try 
		{ 
			var NodeList = this.XmlDocument.getElementsByTagName(NodeName);

			var Output = "";
			var Delimiter = "";
			var Length = NodeList.length;

			for( var x = 0; x < Length; x++ )
			{
				Output += Delimiter + NodeList[x].getAttribute(AttributeName);
				Delimiter = "~";
			}
			return Output.split( Delimiter );
		} 
		catch(Exception)
		{
		
		}
	},

	SelectNodes: function( NodeName )
	{
		try 
		{ 
			var NodeList = this.XmlDocument.getElementsByTagName(NodeName);

			var Output = "";
			var Delimiter = "";
			var Length = NodeList.length;

			for( var x = 0; x < Length; x++ )
			{
				var Value = ( NodeList[x].text) ? NodeList[x].text: NodeList[x].textContent ;
				
				Output += Delimiter + Value;
				Delimiter = "~";
			}
			return Output.split( Delimiter );
		} 
		catch(Exception)
		{
		
		}
	}
}
			
			

function XMLDocument( Xml )
{
	this.XML = Xml;
}

XMLDocument.prototype =
{
	LoadXml: function( Xml )
	{
		this.XML = Xml;
	},

	SelectNodes: function( xPath )
	{
		return this._getArray( this._getNode(xPath), this.XML );
	},

	_getNode: function( xPath )
	{
		if( xPath.indexOf('//') != -1 )
		{
			return xPath.substring( xPath.indexOf('//') + 2 );
		}
		else if( xPath.indexOf('/') )
		{
			return xPath.substring( xPath.indexOf('/') + 1);
		}
		else
		{
			return xPath;
		}
	},

	_getArray: function ( NodeName, XmlString )
	{
		var TempArray = XmlString.split( "<" + NodeName + ">" );
		var Output = "";
		var Delimiter = "";
		var Length = TempArray.length;

		for( var x = 1; x < Length; x++ )
		{
			Output += Delimiter + this._scrub(TempArray[x].split( "</" + NodeName + ">" )[0]);
			Delimiter = "~";
		}
		return Output.split( Delimiter );
	},

	_scrub: function( value )
	{
		if( value.indexOf( '<![CDATA[' ) != -1 )
		{
			value = value.split('<![CDATA[')[1];
			value = value.split(']]>')[0];
		}

		// trim up the string
		value = value.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
		value = value.replace(/\s+/g," ");

		return value;
	}
}


//Default.html.js 
//  Copyright (c) 2007-2008 Jockersoft. All rights reserved.
//
function createEyeRoller(facePath)
{
    unpackXaml();
    facePath = escape(facePath);
	var scene = new EyeRollerWebJS.Scene();
	Silverlight.createObjectEx({
		source: '#eyerollerwebXaml',
		parentElement: document.getElementById('EyeRollerControlHost'),
		id: 'EyeRollerControl',
		properties: {
			width: '100%',
			height: '100%',
			background:'#ffffff',
            isWindowless: 'false',
			version: '1.0'
		},
		events: {
		    onError: null,
			onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
		},		
		context: null,
		initParams: facePath
	});
	
    runAfterPluginLoaded();
}

if (!window.Silverlight) 
	window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
	return function() {
        return method.apply(instance, arguments);
    }
}


function runAfterPluginLoaded() {
    // browser detect
    var IE = document.all ? true : false;

    // request mouse move event notification
    if (!IE) {
        try {
            document.captureEvents(Event.MOUSEMOVE);
        } catch(e) {}
    }
    document.onmousemove = updateMousePos;

    function updateMousePos(e) {
        var x;
        var y;
        if (IE) {
            x = event.clientX + document.body.scrollLeft;
            y = event.clientY + document.body.scrollTop;
        } else {
            x = e.pageX;
            y = e.pageY;
        }  
        // catch possible negative values in NS4
        if (x < 0) x = 0;
        if (y < 0) y = 0; 
        
        var control = document.getElementById("EyeRollerControl");
        if (control) {          	
		    //add plugin offset
		    var host = document.getElementById("EyeRollerControlHost");
				if (IE) {
				    var bounds = host.getBoundingClientRect();
				    x -= bounds.left;
				    y -= bounds.top;
				} else {
		        x -= host.offsetLeft;
		        y -= host.offsetTop;
				}
		    //send mouse move event
            try {
                HandleMouseMove(x, y);
            }
            catch(e) {
            }
        }
    }

    setTimeout("resizePlugin()", 10);
}

var canBeResizedExternal = false;
function resizePlugin() {
    var w = 0, h = 0;
    if (canBeResizedExternal) {
        var control = document.getElementById("EyeRollerControl");
        if (control) {
            try {
                w = GetFaceWidth();
                h = GetFaceHeight();
            } catch(e) { }
        }
    }
    
    if (w == 0 || h == 0) {
        setTimeout("resizePlugin()", 30);
        return;
    }
    else {
        document.getElementById("EyeRollerControlHost").style.width = w + "px";
        document.getElementById("EyeRollerControlHost").style.height = h + "px";
    }
}


//Scene.xaml to JS 
//  Copyright (c) 2007-2008 Jockersoft. All rights reserved.
//
function unpackXaml() {
    var xamlTxt = '<?xml version="1.0"?>\r\n' +
'<Canvas xmlns="http://schemas.microsoft.com/client/2007" \r\n' +
'        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" \r\n' +
'        MouseMove="Page_MouseMove"\r\n' +
'        Loaded="eyerollerOnLoad">\r\n' +
'  <!-- background -->\r\n' +
'  <Image x:Name="imgBackground"></Image>\r\n' +

'  <!-- eye 1 -->\r\n' +
'  <Image x:Name="imgEye1">\r\n' +
'    <Image.RenderTransform>\r\n' +
'      <TranslateTransform x:Name="eye1Transform"></TranslateTransform>\r\n' +
'    </Image.RenderTransform>\r\n' +
'  </Image>\r\n' +
'  <!-- eye 2 -->\r\n' +
'  <Rectangle x:Name="imgEye2" Width="100" Height="100">\r\n' +
'    <Rectangle.RenderTransform>\r\n' +
'      <TranslateTransform x:Name="eye2Transform"></TranslateTransform>\r\n' +
'    </Rectangle.RenderTransform>\r\n' +
'    <Rectangle.Fill>\r\n' +
'      <ImageBrush x:Name="imgEye2Brush" Stretch="None"></ImageBrush>\r\n' +
'    </Rectangle.Fill>\r\n' +
'  </Rectangle>\r\n' +

'  <!-- mask -->\r\n' +
'  <Image x:Name="imgMask">\r\n' +
'  </Image>\r\n' +

'  <TextBlock Text="pippo" x:Name="txt"></TextBlock>\r\n' +

'<Canvas x:Name="faceProperties" Canvas.Top="1000">\r\n' +
'    <Canvas.Resources>\r\n' +
'      <Storyboard x:Name="facePropertiesStoryboard" Completed="facePropertiesStoryboardCompleted">\r\n' +
'        <DoubleAnimation\r\n' +
'          Name="facePropertiesDoubleAnimation"\r\n' +
'          Storyboard.TargetName="faceProperties"\r\n' +
'          Storyboard.TargetProperty="(Canvas.Top)"\r\n' +
'          From="100.0" By="-101" Duration="0:0:1"\r\n' +
'          />\r\n' +
'      </Storyboard>\r\n' +
'    </Canvas.Resources>\r\n' +

'    <Rectangle Name="recFaceDetailsGrip"\r\n' +
'               Canvas.Top="0" Canvas.Left="50" Width="100" Height="20" \r\n' +
'               RadiusX="10" RadiusY="2" Fill="#e8e8e8" Stroke="#808080"\r\n' +
'               Cursor="Hand"\r\n' +
'               MouseLeftButtonDown="facePropertiesOpen" Canvas.ZIndex="100"></Rectangle>\r\n' +
'    <Rectangle Name="recFaceDetails" \r\n' +
'               Canvas.Top="4" Canvas.Left="00" Width="200" Height="101" \r\n' +
'               RadiusX="10" RadiusY="6" Fill="#BBe8e8e8" Stroke="#c0c0c0"\r\n' +
'               MouseLeftButtonDown="facePropertiesClose"></Rectangle>\r\n' +
    
'    <TextBlock Name="txtLogo" Canvas.Left="4" Canvas.Top="4" Cursor="Hand" MouseLeftButtonDown="eyerollerLinkClicked" \r\n' +
'               TextWrapping="Wrap" FontSize="9">\r\n' +
'      <Run Text="EyeRoller " Foreground="#2f93db" FontSize="16"></Run>\r\n' +
'      <Run Text="WEB " Foreground="#ff0084" FontSize="16"></Run>\r\n' +
'      <Run Text="http://toolshape.com" FontSize="11" TextDecorations="Underline" Foreground="Blue"></Run>\r\n' +
'      <LineBreak />\r\n' +
'      <Run Text="Click here" FontSize="11" TextDecorations="Underline" Foreground="Blue"></Run>\r\n' +
'      <Run Text=" to learn how to add this and other faces to your webpage!" FontSize="11"></Run>\r\n' +
'    </TextBlock>\r\n' +
'    <TextBlock TextWrapping="Wrap"></TextBlock>\r\n' +
    
'    <TextBlock Name="txtFaceDetails" Text="Face not loaded"\r\n' +
'               Canvas.Left="4" Canvas.Top="75"\r\n' +
'               FontSize="11" Width="200" TextWrapping="Wrap"\r\n' +
'               MouseLeftButtonDown="facePropertiesClose">\r\n' +
'    </TextBlock>\r\n' +
'  </Canvas>\r\n' +
    
'</Canvas>\r\n';

    document.getElementById('eyerollerwebXaml').text = xamlTxt;
}


//Scene.xaml.js 
//  Copyright (c) 2007-2008 Jockersoft. All rights reserved.
//
if (!window.EyeRollerWebJS)
	window.EyeRollerWebJS = {};

EyeRollerWebJS.Scene = function() 
{
}

var ready = false;
var newSx, newDx;
var movSxPoints, movDxPoints;
var sospendi = false;
var previousMouseLoc = new PointD(0, 0);
var plugIn, rootElement;
///array that contains the face metadata 
var faceProperties = Array();
    

//UI controls
var imgBackground, 
    imgEye1, 
    imgEye2, 
    imgMask, 
    txt;
var eye1Transform,
    eye2Transform;
var imgEye2Brush;

//PointD class
function PointD(x, y) 
{
 	this.x = x;
 	this.y = y;
}

function Point(x, y)
{
 	this.x = x;
 	this.y = y;
}

function loadSparseFace(propertiesXml)
{
    txt.Text = "Downloading components...";
    
    var reader = parseProperties(propertiesXml);
    
    imgBackground.Source = reader.SelectNodes("back")[0];
    imgMask.Source = reader.SelectNodes("mask")[0];
    imgEye1.Source = reader.SelectNodes("eye1")[0];
    imgEye2Brush.ImageSource = reader.SelectNodes("eye2")[0];



//common with faceDownloader_Completed
    ready = true;
    txt.Text = null;

    //set an initial position of the eyes
    handleMouseMove(new PointD(100, 100));

    resizePluginInternal();
}

// Event handler for the Completed event.
function faceDownloader_Completed(faceDownloader, eventArgs)
{
    txt.Text = "Download completed.";
    var errors = null;
    try
    {
        imgBackground.SetSource(faceDownloader, "face.png");
    }
    catch(e)
    {
        try
        {
            imgBackground.SetSource(faceDownloader, "face.jpg");
        }
        catch(e)
        {
            errors += "no face\r\n";
        }
    }

    try
    {
        imgEye1.SetSource(faceDownloader, "pupil.png");

        try
        {
            faceDownloader.GetResponseText("pupil2.png");
            imgEye2.SetSource(faceDownloader, "pupil2.png");
        }
        catch(e)
        {
            imgEye2Brush.SetSource(faceDownloader, "pupil.png");
            if (imgEye1.Width != 0) {
                imgEye2.Width = imgEye1.Width;
                imgEye2.Height = imgEye1.Height;
            }
            else {
                //use default (set in xaml)
            }
        }
    }
    catch(e)
    {
        errors += "no pupil\r\n";
    }

    try
    {
        imgMask.SetSource(faceDownloader, "mask.png");
    }
    catch(e)
    {
        errors += "no mask\r\n";
    }

    var propertiesXml = null;
    try
    {
        propertiesXml = faceDownloader.GetResponseText("properties.xml");
    }
    catch(e)
    {
        errors += "no properties\r\n";
    }
    if (propertiesXml != null)
        parseProperties(propertiesXml);

 //common with loadSparseFace
    if (errors == null)
    {
        ready = true;
        txt.Text = null;

        //set an initial position of the eyes
        handleMouseMove(new PointD(100, 100));

        resizePluginInternal();
    }
    else
    {
        ready = false;
        txt.Text = errors;
    }
}

function faceDownloader_DownloadFailed(sender, e)
{
    if (e == null)
        txt.Text = "download error: " + "-1" + " - " + "exception";
    else
        txt.Text = "download error: " + e.ErrorCode + " - " + e.ErrorMessage;
    ready = false;
}

function GetFaceWidth()
{
    return imgBackground.Width;
}
function GetFaceHeight()
{
    return imgBackground.Height;
}

function parseProperties(propertiesXml)
{
    var reader = new XML();
    reader.LoadXml(propertiesXml);
    
    var pathData;
    pathData = reader.SelectNodes("path1");
    movSxPoints = GraphicsPathDaString(pathData[0]);
    
    pathData = reader.SelectNodes("path2");
    if (pathData.length > 0)
        movDxPoints = GraphicsPathDaString(pathData[0]);
    else
        movDxPoints = movSxPoints;
        
    var propertyNames = Array("name", "version", "subject", "author", "contact", "site", "notes");
    var faceDescr = "";
    for (var i = 0; i < propertyNames.length; i++) 
    {
        var v = reader.SelectNodes(propertyNames[i]);
        if (v.length > 0 && v[0] != "undefined") {
            faceProperties[propertyNames[i]] = v[0];
            faceDescr += propertyNames[i] + ": " + v[0] + "\r\n";
        }
    }
    var txtFaceDetails = rootElement.findName("txtFaceDetails");
    txtFaceDetails.Text = faceDescr;
    
    return reader;
}

/// <param name="serieDiPunti">es "177;174|178;174|179;174"</param>
function GraphicsPathDaString(serieDiPunti)
{
    var s = serieDiPunti.toString().split("|");
    if (s.Length < 3)
        return null;
    else
    {
        var punti = new Array();
        for (var i = 0; i < s.length; i++)
        {
            var vals = s[i].split(";");
            punti[i] = new PointD(parseFloat(vals[0]), parseFloat(vals[1]));
        }
        return punti;
    }
}

function getClosest(points, p)
{
    var distanzaMin = 9999999;
    var puntoMin = new PointD(0, 0);

    for (var i = 0; i < points.length; i++)
    {
        var punto = points[i];
        if (distanzaMin > delta(punto, p))
        {
            distanzaMin = delta(punto, p);
            puntoMin = punto;
        }
    }
    return puntoMin;
}

/// <summary>
/// calcola la distanza fra 2 punti
/// </summary>
function delta(p1, p2)
{
    return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));
}

function resizePluginInternal()
{
    var parentDiv = document.getElementById("EyeRollerControlHost");
    if (parentDiv == null)
    {
        //HTML implementation error or hosted by Microsoft Silverlight Streaming
    }
    else
    {
        if (imgBackground.Width > 0 || imgBackground.Height > 0)
        {
            alert(imgBackground.Width + "  " + imgBackground.Height);
            parentDiv.style.width = imgBackground.Width;
            parentDiv.style.height = imgBackground.Height;
        }
        else
        {
            canBeResizedExternal = true;
        }
    }
}

function HandleMouseMove(x, y)
{
    handleMouseMove(new PointD(x, y));
}

function handleMouseMove(mousePos)
{
    if (!ready)
        return;

    var tempPoint;
    if (mousePos != previousMouseLoc)
    {
        if (true /* this.modalitāStrabica */ )
        {
            //if (movSx.IsVisible(mousePos))
            //{
            //    newSx = new Point(mousePos.x - okkioSx.Width / 2, mousePos.y - okkioSx.Height / 2);
            //}
            //else
            {
                tempPoint = getClosest(this.movSxPoints, mousePos);
                newSx = new PointD(tempPoint.x - imgEye1.Width / 2, tempPoint.y - imgEye1.Height / 2);
            }

            //if (movDx.IsVisible(mousePos))
            //{
            //    newDx = new PointD(mousePos.x - okkioDx.Width / 2, mousePos.y - okkioDx.Height / 2);
            //}
            //else
            {
                tempPoint = getClosest(this.movDxPoints, mousePos);
                newDx = new PointD(tempPoint.x - imgEye2.Width / 2, tempPoint.y - imgEye2.Height / 2);
            }
        }

        previousMouseLoc = mousePos;
    }

    eye1Transform.x = newSx.x;
    eye1Transform.y = newSx.y;
    eye2Transform.x = newDx.x;
    eye2Transform.y = newDx.y;
}

function Page_MouseMove(sender, eventArgs)
{
    var mousePos = eventArgs.GetPosition(null);

    if (sospendi)
        return;

    handleMouseMove(mousePos);
}

function eyerollerLinkClicked(sender, eventArgs)
{
    window.open("http://eyeroller.toolshape.com");
}
function facePropertiesOpen(sender, eventArgs)
{
    rootElement.findName("recFaceDetailsGrip").Visibility = "Collapsed";    
    var facePropertiesCanvas = rootElement.findName("faceProperties");
    var facePropertiesDoubleAnimation = facePropertiesCanvas.findName("facePropertiesDoubleAnimation");
    facePropertiesDoubleAnimation.From = facePropertiesCanvas["Canvas.Top"];
    facePropertiesDoubleAnimation.To = plugIn.content.actualHeight - 4 - facePropertiesCanvas.findName("recFaceDetails").Height;
    sender.findName("facePropertiesStoryboard").begin();
}
function facePropertiesClose(sender, eventArgs)
{
    var facePropertiesCanvas = rootElement.findName("faceProperties");
    var facePropertiesDoubleAnimation = facePropertiesCanvas.findName("facePropertiesDoubleAnimation");
    facePropertiesDoubleAnimation.From = facePropertiesCanvas["Canvas.Top"];
    facePropertiesDoubleAnimation.To = plugIn.content.actualHeight - 4;
    sender.findName("facePropertiesStoryboard").begin();
}
function facePropertiesStoryboardCompleted(sender, eventArgs)
{
    if (rootElement.findName("faceProperties")["Canvas.Top"] == plugIn.content.actualHeight - 4)
        rootElement.findName("recFaceDetailsGrip").Visibility = "Visible";
}
	
	
function onResize(sender, eventArgs)
{    
    var facePropertiesCanvas = rootElement.findName("faceProperties");
    facePropertiesCanvas.findName("recFaceDetails").Width = plugIn.content.actualWidth - 8;
    facePropertiesCanvas.findName("recFaceDetails").Height = plugIn.content.actualHeight - 8;
    facePropertiesCanvas.findName("txtFaceDetails").Width = plugIn.content.actualWidth - 16;
    facePropertiesCanvas.findName("txtLogo").Width = plugIn.content.actualWidth - 9;
    
    facePropertiesCanvas["Canvas.Left"] = 4;
    facePropertiesCanvas["Canvas.Top"] = plugIn.content.actualHeight - 4;
    facePropertiesCanvas.findName("recFaceDetailsGrip")["Canvas.Left"] = (plugIn.content.actualWidth - facePropertiesCanvas.findName("recFaceDetailsGrip").Width) / 2;
}

EyeRollerWebJS.Scene.prototype =
{

	handleLoad: function(plugin, userContext, rootelement) 
	{
		this.plugIn = plugin;
		plugIn = plugin;
		rootElement = rootelement;
		plugIn.content.onResize = onResize;
		
		imgBackground = rootElement.children.getItem(0);	
		imgEye1 = rootElement.children.getItem(1);
		imgEye2 = rootElement.children.getItem(2);
		imgMask = rootElement.children.getItem(3);
		txt = rootElement.children.getItem(4);
		eye1Transform = rootElement.findName("eye1Transform");
		eye2Transform = rootElement.findName("eye2Transform");
		imgEye2Brush = rootElement.findName("imgEye2Brush");
		
        var faceToLoad = null;
        var initParams = plugIn.initParams.split(",");
        faceToLoad = unescape(initParams[0]); //the first parameter is always the path to the face to load
            
        if (faceToLoad.indexOf("<face>") > -1)
        {
            //we are not loading a .jfa file but several image files:
            // faceToLoad contains the propertiesXML content + the back, mask, eye1, eye2 ULRs
            loadSparseFace(faceToLoad);
        }
        else
        {
            //we are loading a .jfa file
            
            txt.Text = "Loading {0}..." + faceToLoad;
            
            // Create a Downloader object.
            var faceDownloader = plugIn.createObject("downloader");
            faceDownloader.addEventListener("downloadFailed", faceDownloader_DownloadFailed);
            faceDownloader.addEventListener("completed", faceDownloader_Completed);
            faceDownloader.open("GET", faceToLoad);

            // Execute the Downloader request.
            try
            {
                faceDownloader.send();
            }
            catch(e)
            {
                faceDownloader_DownloadFailed(faceDownloader, null);
            }
	    }
	}
}
