// ---------------------------------------------
// VR System General script, DOT NOT EDIT
// ---------------------------------------------

var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);
var xpcomversion = "1.4.0.0";

function element(id)
{
	return document.getElementById(id);
}

function createTurnTool(width, height, file, color, transparent)
{
	var turntoolObject = '';
	if(isTurnToolInstalled())
	{
		if (ie4||ie5)
		{
			turntoolObject += ' <object id="TNTCtrl" width="'+width+'" height="'+height+'" classid="CLSID:402ee96e-2ce8-482d-ada5-ceceea07e16d"';
			turntoolObject += ' codebase="/download/ViewerInstall.exe#version=2,12,0,8"><param name="transparent"'; 
			turntoolObject += ' value="'+transparent+'"><param name="ctrl_color" value="'+color+'"><param name="tnt_back_color" value="'+color+'">';
			turntoolObject += '<param name="script" value="ProgressBar.SetDownloadText(\'Downloading TurnTool Resource\');'
			+'ProgressBar.SetCoreDownloadText(\'Downloading TurnTool Core\');TNTCtrl.SetLogo(\'None\');">';
			turntoolObject += '<param name="src" value="'+file+'"></object>';
			turntoolObject += '<sc'+'r'+'ipt type="text/javascript" FOR="TNTCtrl" EVENT="TNTEvent(string)"> execScript(string); </sc'+'r'+'ipt>';
		}
		else
		{
			turntoolObject += '<embed id="TNTCtrl" width="'+width+'" height="'+height+'" script="ProgressBar.SetDownloadText(\'Downloading TurnTool Resource\');'
			+'ProgressBar.SetCoreDownloadText(\'Downloading TurnTool Core\');TNTCtrl.SetLogo(\'None\');" src="'+file+'" transparent="'+transparent+'" ctrl_color="'+color+'"';
			turntoolObject += 'tnt_back_color="'+color+'" pluginspage="/download/ViewerInstall.xpi" pluginsurl="/download/ViewerInstall.xpi" type="application/tntfile"></embed>';
		}
		element('TurnTool').innerHTML = turntoolObject;
		element('turnToolInstall').style.display = 'none';
	}
	else
	{
		if (ie4||ie5)
		{
			//
		}
		else
		{
			element('u8').innerHTML = 'TurnTool viewer (3D ActiveX player) User Agreement \n\n1. This software is under protection of the Copyright Law of People\'s Republic of China'
			 +' international copyright treaties and other intellectual property laws and treaties, and all its intellectual property belongs to the TurnTool Aps (hereinafter referred to TT). \n\n'
			 +'2. This software (including but not limited to the software products contained in any images, photographs, animation, video, sound recording, music, text and additional procedures'
			 +' (dll, exe, etc.)), with attached help material, and any copies of the software are all owned by TT. Individual users can not copy and modify these materials.\n\n'
			 +'3. Users may not reverse engineer, decompile, or disassemble this software. Offenders will face prosecution in accordance with Chinese and international law for such actions.\n\n'
			 +'4. This software is free. Non-commercial users can download, install, reproduce and distribute the software products. Commercial users who wish to sell, reproduce or distribute'
			 +' copies of this software, for example, in pre-installed bundled software packages, must first obtain written authorization, licensing and approval from TT.\n\n5. This software allows'
			 +' users\' internet browsers to play 3D content with ".tnt" format. After the installation of the software, user\'s interface will not change, and the software will only become active when'
			 +' the user visits web-pages with the ".tnt" format files. \n\n6. Due to users\' different computer hardware and software specifications, TT cannot guarantee this software will perform'
			 +' in a certain way. TT does not undertake any responsibility, nor will be held responsible for consequences resulting from the use of this software.\n\n7. In order to timely provide users'
			 +' with new features and solve software bugs, this software will update automatically. TT ensures that these updates will not contain any malicious viruses that access or gather user\'s'
			 +' private data or information; track or monitor a user\'s computer or Internet behavior, and does not breach any aspects of the user\'s privacy. \n\n8. This software is free. TT provides'
			 +' telephone, fax, Email/Web, and other forms of support. Free support Tel:021-55666130, e-mail: China@turntool.com.\n\n9. TT ensures that these updates will not contain any'
			 +' malicious viruses that access or gather user\'s private data or information; track or monitor a user\'s computer or Internet behavior, and does not breach any aspects of the user\'s'
			 +' privacy. \n\n10. This software has gone through thorough testing, but TT cannot guarantee its compatibility with all hardware and software systems. For any incompatibility issues,'
			 +' users may call our free support hotline for technical support and advice. If incompatibility issues cannot be solved, users may choose to uninstall it. TT is not responsible for damages'
			 +' caused by using this software except by obvious quality defects. Such damage may result from its conflict with other software on users\' computers, or from its unavailability.'
			 +' Such damages include (but are not limited to) direct or indirect personal damage, loss of business profits, trade disruption, loss of business information, or any other pecuniary loss.\n\n'
			 +'11. If a user downloads this software from non-designated TT site TT can not guarantee that the software is free from viruses, ad ware, or other malicious programs, and TT will not'
			 +' bear any direct or indirect liability for damage. \n\n12. By clicking "yes" on your browser\'s security box when installing this software, users voluntarily choose to install this software,'
			 +' and accept all the provisions of this Agreement. If you do not accept with this Agreement, please click "no" and discontinue the installation of this software.\n';
		}
		element('turnToolInstall').style.display = "";	
	}
}
function manualInstallTurnTool()
{
	if (ie4||ie5)
	{
		window.location.href = '/download/ViewerInstall.exe';
	}
	else
	{
		var xpi = {'TurnTool Viewer Installation':'/download/ViewerInstall.xpi'};
		InstallTrigger.install(xpi,installFinish);
	}
}

function initTurnTool()
{
	createTurnTool(tntSizeX,tntSizeY,tntSource, tntCtrlColor, tntTransparentOption);	// create embed and object tag
	if(TNTsupportedPlatform()==true)
	{//in Win Platform
		if (isTurnToolNewestVersion()==false && ns6)
		{
			// this is mozilla only, if missing plugin or plugin is outdated
			element('InstallTag').innerHTML = '<input type="button" value="Install 3D Viewer" onclick="manualInstallTurnTool();" />';
			//manualInstallTurnTool();
		}
		if(isTurnToolInstalled() == false && (ie4||ie5))
		{
			element('InstallTag').innerHTML = '<input type="button" value="Install 3D Viewer" onclick="manualInstallTurnTool();" />';
			checkRefresh();
		}
	}
	else
	{
		var failedString = "Sorry, your OS does not support this VR System of 3D Viewer!";
		alert(failedString);
		element('TurnTool').innerHTML = '<p><br />' + failedString + '</p>';
		element('turnToolInstall').style.display = 'none';
	}
}
function isTurnToolNewestVersion()
{
	var tntInstalled = false;
	if(ie4||ie5)
	{
		try
		{
			var xObj = new ActiveXObject("TNT.TNTCtrl");
			if (xObj)
			{
				tntInstalled = true;
			}
		}
		catch (e)
		{
		}
	}
	else
	{
		var isSupported = navigator.mimeTypes['application/tntfile'];
		isSupported = isSupported && isSupported.enabledPlugin; //in case they disabled it
		if(isSupported)
		{
			var v = navigator.plugins.namedItem("TurnTool XPCOM Plugin");
			if(v && v.description) {
				tntInstalled = true;
			}
		}	
	}	
	return tntInstalled;
}
function isTurnToolInstalled()
{
	var tntInstalled = false;
	if (ie4||ie5)
	{
		try
		{
			var xObj = new ActiveXObject("TNT.TNTCtrl");
			if (xObj)
			{
				tntInstalled = true;
			}
		}
		catch (e)
		{
		}
	}
	else
	{
		var v = navigator.plugins.namedItem("TurnTool XPCOM Plugin");
		if(v && v.description) {
			var version = v.description.replace(/([a-zA-Z]|\s)+/, "").split(".");
			var minversion = xpcomversion.split(".");
			for (var i=0; i<minversion.length; i++)
			{
				if (i >= version.length)
					break;
				if (version[i] > minversion[i])
				{
					tntInstalled = true;
					break;
				}
				if (version[i] < minversion[i])
					break;
				if (i == (minversion.length-1))
					tntInstalled = true;
			}
		}
	}
	return tntInstalled;
}

function installTurnTool() 
{
	element('InstallTag').innerHTML = '<input type="button" value="Install 3D Viewer" onclick="manualInstallTurnTool();" />';
	if (ns6)
	{
		alert('Sorry, you need to click the button to start this installation manually for browser security.');
		return false;
	}
	checkRefresh();
}

function installFinish(url, result)
{
	if (result>=0)
	{
		element('TurnTool').innerHTML = 'You must restart your browser to view the content of this page.<br />Please reopen this page after restart of your browser.';
		//alert('The installation requires that you restart your browser');
	}
	else if(result == -210)
	{
		alert('You must install the TurnTool Viewer to see the 3d content of this page.');
	}
	else
	{
		alert('The installation failed, please close all browser windows and try again.\n\nIf the problem continues, try restarting your computer.\n\n'
		+'If the problem still continues, please contact your content provider.');
	}
}

var checkCounter = 0;
function checkRefresh()
{
	var tntInstalled = isTurnToolInstalled();
	if(tntInstalled==false)
	{
		checkCounter++;
		if (checkCounter>120)
		{
			checkCounter=0;
			installTurnTool();
		}
		if(ie4||ie5)
		setTimeout('checkRefresh()',500);
	}
	else
	{
		window.location.href = window.location;
	}
}

function TNTDoCommand(string)
{
	var control = element("TNTCtrl");
	if(control && control.ready)
		return control.TNTDoCommand(string);
	return "";
}

function focus()
{
	element("TNTCtrl").focus();
}

function OnClick( obj )
{
	if(TNTDoCommand('Objects(' + obj + ').GetStopFrame()')!=100)
		TNTDoCommand('Objects(' + obj + ').PlayAnimation(,100)');
	else
		TNTDoCommand('Objects(' + obj + ').PlayAnimation(,0)');
	window.status = "Object clicked: " + obj;	
}

function OnMouseEnter( obj )
{
	TNTDoCommand('Objects(' + obj + ').SetDiffuseColor(#FF0000)');
	window.status = "Mouse Entered: " + obj;	
}

function OnMouseExit( obj )
{
	TNTDoCommand('Objects(' + obj + ').ResetMaterial()');
	window.status = "Mouse Exited: " + obj;	
}

function OnZoneEnter( zone, physics )
{
	focus();
	window.status = "Zone Entered: " + zone + ", by physics object: " + physics;	
}

function OnZoneExit( zone, physics )
{
	focus();
	window.status = "Zone Exited: " + zone + ", by physics object: " + physics;	
}

function OnKeyPress( keyCode, ascii )
{
	window.status = "KeyPress: KeyCode=" + keyCode + " Ascii=" + ascii;
}

function OnKeyRelease( keyCode, ascii )
{
	window.status = "KeyRelease: KeyCode=" + keyCode + " Ascii=" + ascii;
}

function Restart()
{
	TNTDoCommand('SceneGraph.Physics.Reset()');
	TNTDoCommand('Objects(*).StopAnimation()');
	TNTDoCommand('Objects(*).SetFrame(0)');
	cameraName = TNTDoCommand('SceneGraph.Camera(0).GetName()');
	TNTDoCommand('CameraCtrl.SetCurrent("'+ cameraName+'")');
}

function TNTsupportedPlatform()
{
	if (navigator.platform.toString().indexOf("Win") != -1)
		return true;
	if (navigator.platform.toString().toLowerCase().indexOf("mac")!=-1 || navigator.platform.toString().toLowerCase().indexOf("linux")!=-1)
		return false;
	return true;
}

function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj.attachEvent( "on"+type, function() { obj["e"+type+fn](); } );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj["e"+type+fn] );
		obj["e"+type+fn] = null;
	}
}

addEvent(window,"load",initTurnTool);


// ---------------------------------------------
//      VR System Template specefic script
// ---------------------------------------------

function OnReady()
{
	loadExternalTextures();
	focus();
	element('Information').innerHTML = '';
	window.status = "VR System Ready";	
}

function loadExternalTextures()
{
	var texcnt = 0;
	texcnt = TNTDoCommand('SceneGraph.GetBitmapCount()');
	var bExternal = 64;
	var bHasAlpha = 32;
	for( var i=0; i<texcnt; i++ )
	{
		var props = 0;
		props = TNTDoCommand('SceneGraph.Bitmap(' + i + ').GetProperties()');
		if(props & bExternal)
		{
			var name = TNTDoCommand('SceneGraph.Bitmap(' + i + ').GetName()');
			if(props & bHasAlpha)
				name += '.png';
			else
				name += '.jpg';
			TNTDoCommand('SceneGraph.Bitmap('+i+').Load("'+name+'")');
		}
	}
}

function changeCamera(newCamera)
{
	var currentCamera = TNTDoCommand('CameraCtrl.GetCurrent()');
	var srcParentNodeIdx = TNTDoCommand('Objects('+currentCamera+').GetParentNodeIndex()');
	var desParentNodeIdx = TNTDoCommand('Objects('+newCamera+').GetParentNodeIndex()');
	if (srcParentNodeIdx == desParentNodeIdx)
	{
		var frameCount = TNTDoCommand('Objects('+newCamera+').GetFrameCount()');
		if (frameCount>1)
		{
			TNTDoCommand('Objects(*).PlayAnimation(0,'+frameCount+')');	
			TNTDoCommand('CameraCtrl.SetCurrent("'+newCamera+'")');	
		}
		else
		{
			TNTDoCommand('CameraCtrl.Match("'+newCamera+'",2000)');
		}
	}
	else
	{
		TNTDoCommand('SceneGraph.Physics.Reset()');	
		TNTDoCommand('CameraCtrl.SetCurrent("'+newCamera+'")');
	}
}

function init()
{
	element('ControlPanel').innerHTML = html;
}

addEvent(window,"load",init);


/*
 * Copyright (c) 2006, www.never-online.net! All rights reserved.
 * web    : http://www.never-online
 * author : never-online, BlueDestiny
 * version: 0.10.1 
 * this is a autocomplete extras version, complete version in neverModules framework.
 * debug in IE6.0, Opera9.0, Mozilla Firefox1.5.0
 */ 

if (typeof getElementById!="function") {
  var getElementById = function (id) {
    if   (typeof(id)=="object") return id;
    if   (document.getElementById(id)) { return document.getElementById(id); } 
    else { throw new Error(id +" argument error, can not find \"" +id+ "\" element"); }
  }
}

function getElCoordinate (e) {
  var t = e.offsetTop;
  var l = e.offsetLeft;
  var w = e.offsetWidth;
  var h = e.offsetHeight;
  while (e=e.offsetParent) {
    t += e.offsetTop;
    l += e.offsetLeft;
  }; return {
    top: t,
    left: l,
    width: w,
    height: h,
    bottom: t+h,
    right: l+w
  }
}

var neverModules = window.neverModules || {};
neverModules.modules = neverModules.modules || {}; 

neverModules.modules.slider = function (cfg) {
  if ((typeof cfg)!="object") 
  throw new Error("config argument is not a object, err raise from slider constructor");

  this.targetId  = cfg.targetId;
  this.hints     = cfg.hints?cfg.hints:"";
  this.sliderCss = cfg.sliderCss?cfg.sliderCss:"";
  this.barCss    = cfg.barCss?cfg.barCss:"";
  this.min       = cfg.min?cfg.min:0;
  this.max       = cfg.max?cfg.max:100;
  this.onstart   = null;
  this.onchange  = null;
  this.onfinish  = null;

  this._defaultInitializer.apply(this);
}

neverModules.modules.slider.prototype = {
  _defaultInitializer: function () {
    this._bar     = null;
    this._slider  = null;
    this._wrapper = null;
    this._target  = getElementById(this.targetId);
    if (this.min>this.max){var x=this.min;this.min=this.max;this.max=x;}
    this._value   = this.min;
  },

  create: function () {
    this._createSlider();
  },

  dispose: function () {
    //virtual function
  },

  createBar: function () { with(this) {
    //0.10 can not create mutilple bar
    //this interface is for next version
    //by never-online
    var _self = this;
    _bar = document.createElement("DIV");
    _wrapper.appendChild(_bar);
    _bar.title = hints;
    _bar.id = targetId + "_bar";
    _bar.className = barCss;
    _bar.style.position  = "absolute";

    _bar.onmousedown = function (event) {
      _self._initHandle(event);
    }
  }},

  setValue: function (value) { with(this) {
    if (!_bar) return;
    value = Number(value);
    value = value>max?max:value<min?min:value;
    _bar.style.left = Math.round((value-min)*((_slider.offsetWidth-_bar.offsetWidth)/(max-min)))+"px";
    _value = value;
    onchange.call(this);
    onfinish.call(this);
  }},

  getValue: function () {
    return this._value;
  },

  _createSlider: function () { with(this) {
     var _self = this;
    _wrapper = document.createElement("DIV");
    _target.appendChild(_wrapper);
    _wrapper.id = targetId + "_wrapper";
    _wrapper.style.position = "relative";

    _slider = document.createElement("DIV");
    _wrapper.appendChild(_slider);
    _slider.id = targetId + "_slider";
    _slider.className = sliderCss;
    _slider.style.position  = "absolute";
    

    this.createBar();
    _slider.onclick = function (event) { _self._moveTo(event); }
  }},

  _moveTo: function (evt) { with(this) {
    evt = evt?evt:window.event; 
    var x = evt.clientX-getElCoordinate(_slider).left-Math.round(_bar.offsetWidth/2);
    x = x<=_slider.offsetLeft?_slider.offsetLeft:x>=_slider.offsetLeft+_slider.offsetWidth-_bar.offsetWidth?_slider.offsetLeft+_slider.offsetWidth-_bar.offsetWidth:x;
    _bar.style.left = x+"px"; _value = Math.round(x/((_slider.offsetWidth-_bar.offsetWidth)/(max-min))+min);
    onchange.call(this);
    onfinish.call(this);
  }},

  _initHandle: function (evt) { with(this) {
    evt  = evt?evt:window.event; var _self = this;
    _bar.slider_x = evt.clientX-_bar.offsetLeft;
    document.onmousemove = function (event) { _self._changeHandle(event); }
    document.onmouseup   = function (event) { _self._stopHandle(event);   }
    onstart.call(this);
  }},

  _changeHandle: function (evt) { with(this) {
    evt = evt?evt:window.event; var x = evt.clientX-_bar.slider_x;
    x = x<=_slider.offsetLeft?_slider.offsetLeft:x>=_slider.offsetLeft+_slider.offsetWidth-_bar.offsetWidth?_slider.offsetLeft+_slider.offsetWidth-_bar.offsetWidth:x;
    _bar.style.left = x+"px"; _value = Math.round(x/((_slider.offsetWidth-_bar.offsetWidth)/(max-min))+min);
    onchange.call(this);
  }},

  _stopHandle: function (evt) { with(this) {
    //Release event
    document.onmousemove = null;
    document.onmouseup   = null;
    onfinish.call(this);
  }}
}
