/**************************************************
Trivantis (http://www.trivantis.com)
**************************************************/

/*
** If you want to enable a Debug Window that will show you status
** and debugging information for your HTML published content,
** copy the file "trivantisdebug.html" from your Support Files directory
** (typically C:\Program Files\Trivantis\(Product Name)\Support Files
** and place in the root folder of your published content (next to this file)
** and then change the value of the trivDebug variable from 0 to 1
** (don't forget to save the modified file).
**
*/
var theApp = new webtoraAppl();
var is = theApp.is;

var trivDebug      = 0;
var trivAddMsgFunc = null;
var trivDebugWnd   = '';
var trivSaveMsg    = '';

function trivLogMsg( msg ){
  if( !trivDebug ) {return;}
  var topWnd = findTrivLogMsg( window, true );
  if( topWnd.trivDebug ){
    if( msg ){
      if( topWnd.trivSaveMsg.length ) {topWnd.trivSaveMsg += '<br />';}
      topWnd.trivSaveMsg += msg;
    }
    if( !topWnd.trivDebugWnd && topWnd.opening == 1 ){
   	  setTimeout( "trivLogMsg()", 200 );
    }
    else if( !topWnd.trivDebugWnd || topWnd.trivDebugWnd.closed || !topWnd.trivDebugWnd.location ){
      topWnd.opening = 1;
      topWnd.trivDebugWnd = topWnd.open( 'trivantisdebug.html', 'TrivantisDebug', 'width=400,height=400,scrollbars=0,resizable=1,menubar=0,toolbar=0,location=0,status=0' );

   	  setTimeout( "trivLogMsg()", 200 );
    }
    else{
      if( topWnd.trivAddMsgFunc ){
        msg = topWnd.trivSaveMsg;
        topWnd.trivSaveMsg = '';
        topWnd.trivAddMsgFunc( msg );
      }
    }
  }
}

function findTrivLogMsg( win, bCheckOpener ) {

	// btnSaveTitle check ensures that we are not looking at the publisher window in preview mode.
   if( bCheckOpener && win.opener && (!win.opener.btnSaveTitle) && win.opener.trivLogMsg ) {
     return findTrivLogMsg( win.opener, false );
   }

   while( win ) {
     if( win.parent && win.parent != win && (!win.parent.btnSaveTitle) && win.parent.trivLogMsg ) {win = win.parent;}
     else {break;}
   }
   return win;
}

var winW = screen.width;
var winH = screen.height;
function findWH() {
    winW = (is.ns)? window.innerWidth-16 : document.body.offsetWidth-20;
    winH = (is.ns)? window.innerHeight   : document.body.offsetHeight;
}

/*
 *  ObjLayer
 */

function ObjLayer(id,pref,frame) {
  var THIS = this;
  if (!ObjLayer.bInit && !frame) {InitObjLayers();}
  THIS.frame = frame || self;
  if (is.ns) {
    if (is.ns5) {
      THIS.ele = THIS.event = document.getElementById(id);
      THIS.styObj = THIS.ele.style;
      THIS.doc = document;
      THIS.x = THIS.ele.offsetLeft;
      THIS.y = THIS.ele.offsetTop;
      THIS.w = THIS.ele.offsetWidth;
      THIS.h = THIS.ele.offsetHeight;
    }
    else if (is.ns4) {
      if (!frame) {
        if (!pref) {pref = ObjLayer.arrPref[id];}
        THIS.styObj = (pref)? eval("document."+pref+".document."+id) : document.layers[id];
      }
      else {THIS.styObj = (pref) ? eval("frame.document."+pref+".document."+id) : frame.document.layers[id];}
      THIS.ele = THIS.event = THIS.styObj;
      THIS.doc = THIS.styObj.document;
      THIS.x = THIS.styObj.left;
      THIS.y = THIS.styObj.top;
      THIS.w = THIS.styObj.clip.width;
      THIS.h = THIS.styObj.clip.height;
    }
  }
  else if (is.ie) {
    THIS.ele = THIS.event = THIS.frame.document.all[id];
    THIS.styObj = THIS.frame.document.all[id].style;
    THIS.doc = document;
    THIS.x = THIS.ele.offsetLeft;
    THIS.y = THIS.ele.offsetTop;
    THIS.w = THIS.ele.offsetWidth;
    THIS.h = THIS.ele.offsetHeight;
  }

  //webtora if( THIS.styObj ) {THIS.styObj.visibility = (is.ns4)? "hide" : "hidden";}

  THIS.id = id;
  THIS.unique = 1;
  THIS.pref = pref;
  THIS.hasMoved = false;
  THIS.newX = null;
  THIS.newY = null;
}

ObjLayer.arrPref = new Array();
ObjLayer.arrRef = new Array();
ObjLayer.arrRef.i = 0;
ObjLayer.bInit = false;

// Setup prototypes
var p=ObjLayer.prototype;

// in TrivantisPage.js
p.actionGoTo = ObjLayerActionGoTo;
p.actionGoToNewWindow = ObjLayerActionGoToNewWindow;

function ObjLayerActionGoTo( destURL, destFrame, subFrame, bFeed ) {
  var targWind = null;
  var bFeedback = bFeed != null ? bFeed : true;
  if( destFrame ) {
    if( destFrame == "opener" ) targWind = parent.opener;
    else if( destFrame == "_top" ) targWind = window.top;
    else if(destFrame == "NewWindow" ) targWind = open( destURL, 'NewWindow' );
    else {
      var parWind = eval( "parent" );
      var index=0;
      while( index < parWind.length ) {
        if( parWind.frames[index].name == destFrame ) {
          targWind = parWind.frames[index];
          break;
        }
        index++;
      }
      if( subFrame ) {
        index=0;
        parWind = targWind;
        while( index < parWind.length ) {
          if( parWind.frames[index].name == subFrame ) {
            targWind = parWind.frames[index];
            break;
          }
          index++;
        }
      }
      try
      {
        if( !targWind.closed && targWind.trivExitPage ) {
          targWind.trivExitPage( destURL, bFeedback );
          return;
        }
      }catch(e){}
    }
  }
  if( !targWind ) targWind = window;
  try
  {
    if( !targWind.closed ) targWind.location.href = destURL;
  }catch(e){}
}

function ObjLayerActionGoToNewWindow( destURL, name, props ) {
  var targWind;
  if ((props.indexOf('left=') == -1) && (props.indexOf('top=') == -1)) props += GetNewWindXAndYPos( props );
  targWind = window.open( destURL, name, props, false );
  if( targWind ) targWind.focus();
  return targWind;
}

function preload(arImgs) {
	setTimeout(function(){
		  if (!document.images) return;
		  var ar =[];
		  for (var i = 0; i < arImgs.length; i++) {
		    ar[i] = new Image();
		    ar[i].src = arImgs[i];
 		  }
	},100);
}

p.moveTo = function(x,y) {
  var THIS = this;
  if (x!==null) {
    THIS.x = x;
    if( THIS.styObj ) {THIS.styObj.left = THIS.x;}
  }
  if (y!==null) {
    THIS.y = y;
    if( THIS.styObj ) {THIS.styObj.top = THIS.y;}
  }
};

p.moveBy = function(x,y) {
  this.moveTo(this.x+x,this.y+y);
};

p.clipInit = function(t,r,b,l) {
  if (!is.ns4) {
    if (arguments.length==4) {this.clipTo(t,r,b,l);}
    else {this.clipTo(0,this.ele.offsetWidth,this.ele.offsetHeight,0);}
  }
};

p.clipTo = function(t,r,b,l) {
  var THIS = this;
  if( !THIS.styObj ) {return;}
  if (is.ns4) {
    THIS.styObj.clip.top = t;
    THIS.styObj.clip.right = r;
    THIS.styObj.clip.bottom = b;
    THIS.styObj.clip.left = l;
  }
  else {THIS.styObj.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)";}
};

p.show = function() {
  if( this.styObj ) {this.styObj.visibility = "inherit";}
};

p.hide = function() {
  if( this.styObj ) {this.styObj.visibility = (is.ns4)? "hide" : "hidden";}
};

p.actionPlay = function(){};

p.actionStop = function(){};

p.actionShow = function(){this.show();};

p.actionHide = function(){this.hide();};

p.actionLaunch = function(){};

function ObjLayerActionExit()
{
    window.top.close();
}
p.actionExit = ObjLayerActionExit;

p.actionChangeContents = function(){};

p.actionTogglePlay = function(){};

p.isVisible = function() {
  if( !this.styObj || this.styObj.visibility == "hide" || this.styObj.visibility == "hidden" ) {return false;}
  else {return true;}
};

p.write = function(html) {
  if (is.ns4) {
    this.doc.open();
    this.doc.write(html);
    this.doc.close();
  }
  else
    this.event.innerHTML = html;
};

// InitObjLayers Function
function InitObjLayers(pref) {
  var doc = document;
  if (!ObjLayer.bInit) {ObjLayer.bInit = true;}
  if (is.ns) {
    if (pref) {ref = eval('document.'+pref+'.document');}
    else {
      pref = '';
      if( is.ns5 ) {
        doc.layers = doc.getElementsByTagName("*");
        ref = doc;
      }
      else {ref = doc;}
    }
    for (var i=0; i<ref.layers.length; i++) {
      var divname;
      if( is.ns5 ) {
        if( ref.layers[i] ) {divname = ref.layers[i].tagName;}
        else {divname = null;}
      }
      else {divname = ref.layers[i].name;}
      if( divname ) {
        ObjLayer.arrPref[divname] = pref;
        if (!is.ns5 && ref.layers[i].doc.layers.length > 0) {
          ObjLayer.arrRef[ObjLayer.arrRef.length] = (pref==='')? ref.layers[i].name : pref+'.document.'+ref.layers[i].name;
        }
      }
    }
    if (ObjLayer.arrRef.i < ObjLayer.arrRef.length) {
      InitObjLayers(ObjLayer.arrRef[ObjLayer.arrRef.i++]);
    }
  }
  return true;
}

// CSS Function
function buildCSS(id,left,top,width,height,visible,zorder,color,other) {
  var len = arguments.length;
  var str = (left!==null && top!==null)? '#'+id+' {position:absolute; left:'+left+'px; top:'+top+'px;' : '#'+id+' {position:relative;';
  if (len>=4 && width!==null) {str += ' width:'+width+'px;';}
  if (len>=5 && height!==null) {
    str += ' height:'+height+'px;';
    if (len<9 || other.indexOf('clip')==-1) {str += ' clip:rect(0px '+width+'px '+height+'px 0px);';}
  }
  if (len>=6 && visible!==null) {str += ' visibility:'+ ( (visible)? 'inherit' : ( (is.ns4)? 'hide' : 'hidden' ) ) +';';}
  if (len>=7 && zorder!==null) {str += ' z-index:'+zorder+';';}
  if (len>=8 && color!==null) {str += (is.ns4)? ' layer-background-color:'+color+';' : ' background:'+color+';';}
  if (len==9 && other!==null) {str += ' '+other;}
  str += '}\n';
  return str;
}

function writeStyleSheets(str) {
  var cssStr = '<style type="text/css">\n';
  cssStr += str;
  cssStr += '</style>';
  document.write(cssStr);
}

function getHTTP(dest, method, parms)
{
    var httpReq;
    if( method == 'GET' ) {
        if( parms ) {
        dest += '?' + parms;
        parms = null;
        }
    }

    var msg = 'Issuing ' + method + ' to ' + dest;
    if( parms ) msg += ' for [' + parms + ']';
    trivLogMsg( msg );

    var requestSent = 0;
    try {
        // branch for native XMLHttpRequest object
        if (window.XMLHttpRequest) {
            httpReq = new XMLHttpRequest();
            httpReq.open(method, dest, false);
            httpReq.onreadystatechange = null;
            if( method == 'POST' ) {
              httpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            }
            httpReq.send(parms);
            requestSent = 1;
        }
    }
    catch(e){}

    // branch for IE/Windows ActiveX version
    if (!requestSent && window.ActiveXObject) {
        httpReq = new ActiveXObject("Microsoft.XMLHTTP");
        if (httpReq) {
            httpReq.open(method, dest, false);
            if( method == 'POST' ) {
              httpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            }
            httpReq.send(parms);
        }
    }
    trivLogMsg( 'ReturnCode = ' + httpReq.status + ' Received Data [' + httpReq.responseText + ']' );
    return httpReq;
}

function GenRand( min, max )
{
  return Math.floor( Math.random() * ( max - min + 1 ) + min );
}

function GetNewWindXAndYPos( props ) {
    var same = "\\s*([^,\\s]*)\\s*";
    var regExp = new RegExp("width="+same,"i");
    regExp.test(props);
    var wndW = RegExp.$1;
    regExp = new RegExp("height="+same,"i");
    regExp.test(props);
    var wndH = RegExp.$1;
    var wndX = (screen.width - wndW) / 2;
    var wndY = (screen.height - wndH) / 2;
    return ',left=' + wndX + ',top=' + wndY;
}

function ReFlow(publishName, bCenterPage, bSCORMTitle) {
    if (is.ns4 && winW && (winW!=window.innerWidth-16 || winH!=window.innerHeight))
    {
    	if( bSCORMTitle )
            trivExitPage( publishName, false );
        else
            targWind.location.href = '#top';
    }
    else if ( bCenterPage )
    {
        var wndPage = document.getElementById('wndPage');
        var bodyWidth = document.documentElement.clientWidth;
   	    var bodyHeight = document.documentElement.clientHeight;
       	var topOffset = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
    	var left = Math.ceil((bodyWidth - wndPage.offsetWidth) / 2);
    	if (left<0) left = 0;
    	var top = Math.ceil((bodyHeight - wndPage.offsetHeight) / 2) +  topOffset;
    	if (top<0) top = 0;
       	wndPage.style.left = String(left) + 'px';
       	wndPage.style.top = String(top) + 'px';
    }
}

function UniEscape( s )
{
  if( s == null ) return '';
  var sEsc = escape( String(s) );
  sEsc.replace(/%u/g, '%5Cu');
  return sEsc;
}

function UniUnescape( s )
{
  if( s == null ) return '';
  return( unescape( String(s).replace(/%5Cu/g, '%u') ) );
}

function HtmlEscape( s )
{
  if( s == null ) return '';
  var sEsc = escape( String(s) );
  sEsc = HtmlUni( sEsc );
  return sEsc;
}

function HtmlUni( s )
{
  var val = "";
  if( s != null )
  {
    for( i=0; i<s.length; i++ )
    {
      if( s.charAt(i) == '%' && s.length > (i + 5) && s.charAt(i+1) == 'u' )
      {
        val += "%26%23";
        i += 2;
        uniString = s.substring(i,i+4);
        uniInt = parseInt(uniString,16);
        val += uniInt;
        i += 3;
        val += "%3B";
      }
      else
      {
        val += s.charAt(i);
      }
    }
  }
  return val;
}

function wndPagePublished()
{
    var THIS = this;
    THIS.rtData1=-1;
    THIS.rtData2=-1;
    var pageDiv = document.getElementById("wndPage");
    THIS.div = pageDiv;
    if (pageDiv)
    {
    	pageDiv.onmousedown = function(e) { THIS.mouseDown(e); };
    	pageDiv.onmousemove = function(e) { THIS.mouseMove(e); };
    	pageDiv.onmouseup = function(e) { THIS.mouseUp(e); };
    	pageDiv.ondblclick = function(e) { THIS.mouseDblClk(e); };
    	pageDiv.oncontextmenu = function(e) { THIS.contextMenu(e); };
    	document.onkeydown = function(e) { THIS.keyDown(e); };
    }
    THIS.currMouseObj = 0;
    THIS.arDelayAct=[];
	THIS.arTransInWnds=[];
	THIS.arTransOutWnds=[];
}
p = wndPagePublished.prototype;
p.processMouseAct = function(e,type)
{
    if(!e) e = window.event;
    var div = (e.target?e.target:e.srcElement?e.srcElement:null);
	var obj = this.getDivObj(div);
	switch (type)
	{
	    case 1: // down
        	if (obj)
                obj.mouseDown(e);
            else if(typeof(pageClick)=='function')
            	pageClick(e);
            break;
        case 2: // move
            this.setCurrMouseObj(obj);
        	if (obj)
        	   obj.mouseMove(e);
        	break;
        case 3: // up
        	if (obj)
                obj.mouseUp(e);
            break;
        case 4: // dbl click
        	if (obj&&obj.mouseDblClk)
                obj.mouseDblClk(e);
            break;
        case 5: // context menu
        	if (obj&&obj.contextMenu)
                obj.contextMenu(e);
            else if(typeof(pageRClick)=='function'){
            	pageRClick(e);
				return cancelEvent(e);
            }
            break;
	}
};
p.mouseDown = function(e){
	if(!e) e = window.event;
	if(e.which==1||(!e.which&&e.button==1))
    	this.processMouseAct(e,1);
};
p.mouseMove = function(e){
    this.processMouseAct(e,2);
};
p.mouseUp = function(e){
    this.processMouseAct(e,3);
};
p.mouseDblClk = function(e){
	if(!e) e = window.event;
	if(e.which==1||(!e.which&&e.button==1))
	    this.processMouseAct(e,4);
};
p.contextMenu = function(e){
    this.processMouseAct(e,5);
};
p.keyDown = function(e){
	if(typeof(pageKey)=='function'){
	    if(!e) e = window.event;
	    var keyVal = 0;
		var keyFlags = 0;
	    if( e.keyCode == 18 )
	        keyFlags |= 1;
	    else if( e.keyCode == 17 )
	        keyFlags |= 2;
	    else if( e.keyCode == 16 )
	        keyFlags |= 4;
	    else
	        keyVal = e.keyCode;
	    pageKey(keyVal,keyFlags);
	}
};
p.setCurrMouseObj = function(obj) {
    var currObj = this.currMouseObj;
    if(currObj != obj)
    {
       if (currObj && currObj.mouseExit) currObj.mouseExit();
	   this.currMouseObj=obj;
	   if (obj && obj.mouseEnter) obj.mouseEnter();
    }
};
p.getDivObj = function(div){
    var obj = 0;
	while(!obj && div){
	    obj = ( div.popM ? div.popM : ( div.tObj ? div.tObj : 0 ) );
		div = div.parentNode;
	}
	return obj;
};
p.issueShowActions = function(arWnds) // call show if visible
{
    trivIssueShowActs(arWnds);
};
p.doAction = function(func){
    if (typeof func != 'undefined') func();
};
p.findWndByObj = function (o){
    return o.wnd;
};
/*
 * in css we set the cursor for A tags to pointer, since IE needs the pointer
 * to be set to hand instead of pointer we do that here. This is necessary because
 * we remove href from our A tags, and the cursor then defaults to a text cursor.
 */
p.fixA = function(){
	if (theApp.is.ie) trivArExec(document.getElementsByTagName("A"),function(o){o.style.cursor='hand';});
};

function cwObjPub()
{
    this.arChld=[];
}
p = cwObjPub.prototype;
p.getTrans = function(bIn)
{
    var tranData=this.transData;
    return (tranData?(bIn?tranData[0]:tranData[1]):0);
};
p.getTransSpeed = function(bIn)
{
    var tranData=this.transData;
    return (tranData?(bIn?tranData[2]:tranData[3]):0);
};
p.getTransDelay = function(bIn)
{
    var tranData=this.transData;
    return (tranData?(bIn?tranData[4]:tranData[5]):0);
};
p.getXPos = function()
{
	return this.rect.x;
};
p.getYPos = function()
{
	return this.rect.y;
};


trivGoToPage = null;
// NOTE: trivCompleteCnt is initialized to one and a trivLeavePage() call is always called as the last thing in the trivExitPage() function.
trivCompleteCnt = 1;
hasProcessedExitActions = false;
trivWndFeedback = null;
trivWndImmFeedback = null;
currFeedbackIdx = 0;
trivPageExited = false;
trivNumQuestions = 0;
trivProcessTest = 0;

function trivOnFocus() {
    if( trivWndFeedback ) {
      try{
        if( !trivWndFeedback.closed )
        {
           trivWndFeedback.close();
           trivWndFeedback = null;
        }
      }catch(e){}
      setTimeout( 'checkLeavePage()', 100);
    }
}

function checkLeavePage()
{
    if( trivWndFeedback == null || trivWndFeedback.closed )
    {
        trivWndFeedback = null;
        currFeedbackIdx++;
        if( currFeedbackIdx > (trivNumQuestions-1)) {
            if(trivProcessTest && ( bInProcessTest || trivGoToPage == null )) {
		              bInProcessTest = false;
		              processTest(1);
		    }
		    else if (trivExitPage.transOutDone && trivExitPage.transOutDone()==false)
		    {
		    	setTimeout( 'checkLeavePage()', 100);
		    }
		    else
		      trivLeavePage();
	        return;
        }
        else if( !checkQuestions( true ))
          return;
    }
    setTimeout( 'checkLeavePage()', 100);
}

function trivLeavePage()
{
	trivCompleteCnt--;
	if( trivCompleteCnt <= 0 )
	{
    	if (trivLeavePage.trivSaveVars) trivLeavePage.trivSaveVars(); // trivSaveVars is written out by publish.js if needed
		hasProcessedExitActions = false;
		eval( trivGoToPage );
		trivGoToPage = null;
		trivPageExited = true;
	}
}

function trivExitPage( newPage, bFeedback )
{
	if( newPage.indexOf( "ObjLayerAction" ) >= 0 ||
		newPage.indexOf( ".action" ) >= 0 ||
		newPage.indexOf( "history.back()" ) >= 0)
			trivGoToPage = newPage;
	else
			trivGoToPage = 'ObjLayerActionGoTo("' + newPage + '")';

	if( !hasProcessedExitActions )
	{
		findWH();

		if (trivExitPage.trivExitPageChkExit)
			if (trivExitPage.trivExitPageChkExit(bFeedback)===0)
				return;

	    // Now add all the Exit actions and Fly Out actions.
	    hasProcessedExitActions = true;

	    if (trivExitPage.trivExitPageItemExits)
	    	trivExitPage.trivExitPageItemExits();

        setTimeout( 'checkLeavePage()', 100);
	}
}
