if (!scriptpath) var scriptpath = "../ui/";
if (!imagepath) var imagepath = "../images/templates/player/";
var statusrefreshperiod=200;
var initialised = false;
var panels = new objectlist();
var communication = new btcommunication();
var media = new btmedia();
var slides = new btslidelist();
var timeline = new bttimeline();
var tabs = new bttabs();
var votes = new btvotes();
var overview = new btoverview();
timeline.setmediaobject(media);
var isIE=document.all;
var isNN=!document.all&&document.getElementById;
var isN4=document.layers;
var xmllastupdate = 0;
if (!browserdata) var browserdata=false;
var xmlrequestmaximum = 5;
var xmlrequestregister = Array();
var debugon = false;
window.onerror = null;

function writedebug(text) {
	if (!debugon) return;
	var debugbox=document.getElementById('debugbox');
	if (!debugbox) {
		var debugbox = document.createElement('div');
		debugbox.id = 'debugbox';
		debugbox.style.display = 'none';
		document.body.appendChild(debugbox);
	}
        return; //added because of debug bug
	if (debugbox) debugbox.innerHTML = debugbox.innerHTML+text+"<br>";
}

function cleardebug() {
	var debugbox=document.getElementById('debugbox');
	if (debugbox) debugbox.innerHTML = "";
}

function toggledebug() {
        debugon = !debugon;
	var debugbox=document.getElementById('debugbox');
	if (debugbox) debugbox.style.display = (debugbox.style.display=='block')?'none':'block';
}

function xmlrequestgetslot() {
  var length = xmlrequestregister.length;
  for (var i=0;i<length;i++) {
    var requestitem = xmlrequestregister[i];
    if (requestitem==null || requestitem.req.readyState==3) return i;
  }
  if (length<xmlrequestmaximum) return length;
  return null;
}

function doxmlrequest(url,returnfunction) {
  var slotindex = xmlrequestgetslot();
  if (slotindex==null) return false;
  var obj = new xmlrequest(slotindex,url,returnfunction);
  xmlrequestregister[slotindex] = obj;
  obj.send();
  return true;
}

function xmlresponsehandler(slotindex) {
  var obj = xmlrequestregister[slotindex];
  if (obj) {	  	  
    if (obj.processresponse()) { 
      writedebug(slotindex + " - Cleared Request");		
      xmlrequestregister[slotindex]=null;
    }
  }
}

function xmlrequesttimeout(slotindex) {
  if (xmlrequestregister[slotindex]) { 
    writedebug(slotindex + " - Request timeout");
	xmlrequestregister[slotindex] = null;
  }
}

function xmlrequest(registerindex, submiturl, returnfunction) {
  this.registerindex = registerindex;
  this.submiturl = submiturl;
  this.returnfunction = returnfunction;
  this.req = null;
  this.timeout = 5000;
  this.timeouthandle = null;
  
	this.createrequest = function() {
		if(window.XMLHttpRequest) {
			try {
				this.req = new XMLHttpRequest();
			} catch(e) {
				this.req = null;
			}
		} else if(window.ActiveXObject) {
			try {
				this.req = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					this.req = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					this.req = null;
				}
			}
		}
	}

  this.send = function() {
    writedebug(this.registerindex + " - Registered request ("+this.submiturl+")");	  
	this.createrequest(); 
	if (!this.req) return false;
    if (this.returnfunction) {
      this.req.onreadystatechange = new Function("xmlresponsehandler("+this.registerindex+")");
    }
    this.req.open("GET", this.submiturl, true);
	if (window.XMLHttpRequest) {		
      this.req.send(null);
    } else {
      this.req.send();
    }
    this.timeouthandle = window.setTimeout('xmlrequesttimeout('+this.registerindex+')',this.timeout);	
  };


  this.processresponse = function() {
    writedebug(this.registerindex + " - Processing Response");	  
    if (this.req.readyState == 4) { // Complete
      if (this.req.status == 200) { // OK response
        writedebug(this.registerindex + " - Response Received OK ");
        var response  = this.req.responseXML.documentElement;
        if (typeof this.returnfunction=='function') {
			  this.returnfunction(response);
			  writedebug(this.registerindex + " - Calling Return Function");
		}
      } else {
    	writedebug(this.registerindex+" - Problem :" + this.req.statusText + "("+this.req.status+")");	
		window.clearTimeout(this.timeouthandle);
      }
      return true;
    }
    writedebug(this.registerindex+" - Ready State : "+this.req.readyState);	
    return false;
  };
};


function objectlist() {
  this.objects = Array();
	
  this.register = function(object) {	
	var uid = this.objects.length;
	this.objects[this.objects.length]=object;
	return uid;
  }
  
  this.call = function(uid,call) {
    var obj = this.objects[uid];
	if (obj) { 
      eval("obj."+call);
	} else {
	  alert("Attempted call to unregistered Object");
	}
  }
}

function callpanel(uid,call) {
  if (panels) panels.call(uid,call);
}

function getAbsX(elt) { 
  return (elt.x) ? elt.x : getAbsPos(elt,"Left"); 
}

function getAbsY(elt) { 
  return (elt.y) ? elt.y : getAbsPos(elt,"Top"); 
}

function getAbsPos(elt,which) {
 iPos = 0;
 while (elt != null) {
  iPos += elt["offset" + which];
  elt = elt.offsetParent;
 }
 return iPos;
}

function imagelist() {
   this.imagearray = Array();
   
   this.addimage = function(alias,filename) {
      var img = new msimage(imagepath + filename);
	  argv = arguments;
	  argc = argv.length;
	  for(var i=2;i<argc;i++) {
	    img.addstate(argv[i]);
	  }
      this.imagearray[alias] = img;
   }
   
   this.getimage = function(alias,state) { 
     if (!this.imagearray[alias]) return false; 
     return this.imagearray[alias].getimage(state);
   }
   
   this.replaceimage = function(id,state) {
     var oldimage = document.getElementById(id); 
	 var newimage = this.getimage(id,state);
	 if (oldimage && newimage) {
	   oldimage.src = newimage.src;
	 }
   }  
}

function msimage(filename) {
  this.filename = filename;
  this.state = Array();
  
  this.addstate = function(statename) {
	var img = new Image();
	img.src = filename.replace("?",statename);
	this.state[statename] = img;
  }
  
  this.getimage = function(statename) {
    //window.status = this.state[statename]?"found":"no";   
    return this.state[statename];
  }
}

function btcommunication() {
   this.id = "unset";
   this.title = "Communication";
   this.presenter = "";
   this.description = "";
   this.companyname = "";
   this.status = "";
   this.playerid = "unset"
   this.playername = "unset";
   this.viewingid = "";
   this.updateurl = null;
   this.polltimeout = null;
   this.dialinnumber = "";
   this.additionaltext = "";
   this.customhtml = false;
   this.userid = "unset";
   this.uid = panels.register(this);

   this.actioncall = function(action) {
     return "callpanel("+this.uid+",'"+action+"')"; 
   }   

   this.drawinfopanel = function() {
      var out = "<div id=\"infobox\">";
      if (this.customhtml!=false) {
        out += this.customhtml;	
      } else {
        out += "<div class=\"title\">"+this.title+"</div>";
        if (this.presentername!="") out += "<div class=\"presentername\">"+this.presenter+"</div>";
        if (this.companyname!="") out += "<div class=\"companyname\">"+this.companyname+"</div>";	  
        if (this.description!="") out += "<div class=\"description\">"+this.description+"</div>";
        if (this.dialinnumber!="") out += "<div class=\"dialinnumber\">"+this.dialinnumber+"</div>";
        if (this.additionaltext!="") out += "<div class=\"additional\">"+this.additionaltext+"</div>";
      }
      out += "</div>";
      document.write(out);
   };

   this.setcustomhtml = function(html) {
      this.customhtml = html;
   };

   this.setupdateurl = function(url) {
      this.updateurl = url;
   };

   this.stoppolling = function() {
      if (this.polltimeout) cleartimeout(this.polltimeout);
   };

   this.pollforupdates = function() {
     if (!this.updateurl) return;
     doxmlrequest(this.updateurl+'?'+Math.random(),processplayerstatus);
     this.polltimeout = setTimeout(this.actioncall('pollforupdates()'),5000);
   };
}

function processplayerstatus(update) {
  writedebug("Processing Player Update");
  //if (!update) return;
  var result = update.getElementsByTagName('update')[0];
  if (!result) return;
  var currentupdate = result.getAttribute('lastupdate');
  if (xmllastupdate<currentupdate) {
    xmllastupdate = currentupdate;
    writedebug("Update Id :"+currentupdate);
    if (media.live) {
      if (result.getElementsByTagName('currentslide')) {
        var currentslide = result.getElementsByTagName('currentslide')[0].firstChild.nodeValue;
        if ((currentslide  || currentslide==0) && slides) slides.show(currentslide);
      }
    }
    if (!result.getElementsByTagName('votes')) return;
    if (!result.getElementsByTagName('votes')[0]) return;
    var votesupdate = result.getElementsByTagName('votes')[0].getElementsByTagName('vote');
    if (votesupdate) {
      for(var voteno=0;voteno<votesupdate.length;voteno++) {
        var resultsarray = Array();
        var vote = votesupdate[voteno];
        var votealias = vote.getAttribute('alias');
        var votestatus = vote.getAttribute('status');
        var starttime = vote.getAttribute('starttime');
        writedebug("Vote update :"+votealias);
        var voteresults = vote.getElementsByTagName('results')[0].getElementsByTagName('result');
        for(var resultno=0;resultno<voteresults.length;resultno++) {
          var voteresult = voteresults[resultno].firstChild.nodeValue;
          resultsarray[resultsarray.length] = parseInt(voteresult);
          writedebug("Result :"+voteresult);
        }
        var currentvote = votes.findvote(votealias);
        if (currentvote) {
           currentvote.setstarttime(starttime);
           currentvote.setstatus(votestatus);
           currentvote.updateresults(resultsarray);
        }
      }
    }
  } 
}

function btmedia() {
  this.mediatype = "WIMP";
  this.streamurl = "";
  this.width = 320;
  this.height = 240;
  this.duration = false;
  this.playerobject = null;
  this.videowindow = true;
  this.live = false;
  this.statustext = Array("0","Stopped","Paused","Playing","Fast Forward","Rewind","Buffering","Waiting...","Stopped","Processing","Stopped","Seeking");
  this.totaltimeplayed = 0;
  this.currentplaystate = false;
  this.uid = panels.register(this);
  this.recordtimeurl = false;
  this.timerobj = window.setInterval("callpanel("+this.uid+",'updatetime()')", statusrefreshperiod);
  this.callid = false;
  
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }  
  
  this.getwidth = function() {
    return this.width;
  }
  
  this.draw = function() {
	if (!this.videowindow) {
	  this.width=0; 
	  this.height=0;
	}
    switch (this.mediatype) {
		
      case "WIMP" : 				
	this.playerobject = new btwimpplayer(this.width,this.height);
	this.playerobject.setstreamurl(this.streamurl);
	this.playerobject.showcontrols = false;
        this.playerobject.live = this.live;
        this.playerobject.draw();
	writecontrol(this);
      break;
	   
      case "REAL" : 	  
        this.playerobject = new btrealplayer(this.width,this.height);
	this.playerobject.setstreamurl(this.streamurl);
	this.playerobject.showcontrols = false;
        this.playerobject.live = this.live;
        this.playerobject.draw();	  
	writecontrol(this);
      break;
	  
      case "QUICKTIME" : 
        this.playerobject = new btqtplayer(this.width,this.height);
	this.playerobject.setstreamurl(this.streamurl);
	this.playerobject.showcontrols = false;
        this.playerobject.live = this.live;
        this.playerobject.draw();	  
	writecontrol(this);
      break;	  
	  
      case "STREAMLESS" : 
	this.playerobject = new btstreamlessplayer(this.width,this.height);
	this.playerobject.setstreamurl(this.streamurl);
	this.playerobject.showcontrols = false;
        this.playerobject.live = this.live;
	this.playerobject.setDuration(this.duration);
        this.playerobject.draw();	  
	if (!this.live) {
           this.playerobject.setcallid(this.callid);
	   writecontrol(this);
        }
      break;	  
	   
      default : 
        alert("Media type "+this.mediatype+" not Supported");
      break;
    }	  
  }

  this.checkcapability = function(name) {
      return (this.playerobject)?this.playerobject.checkcapability(name):false;
  }
  
  this.setcurrentposition = function(seconds) {
	if (this.playerobject) this.playerobject.setCurrentPosition(seconds);
  };
  
  this.setduration = function(seconds) {
	this.duration = seconds;  
  };

  this.jumpandplay = function(seconds) {
    this.setcurrentposition(seconds);
    this.play();
  };
  
  this.fastreverse = function() {
	if (this.playerobject) this.playerobject.fastreverse();	  
  };
  
  this.fastforward = function() {
	if (this.playerobject) this.playerobject.fastforward(); 
  };
  
  this.toggleplaypause = function() {
    if (this.playerobject) {
	  if (this.playerobject.getPlayState()==3) {
	    this.playerobject.pause();
      } else {
	    this.playerobject.play();
	  }
    }
  };

  this.setmute = function(state) {
	if (this.playerobject) this.playerobject.setMute((state==true));
  }

  this.togglemute = function() {
	if (this.playerobject) this.playerobject.setMute(!this.playerobject.getMute());
  }; 
  
  this.getmutestatus = function() {
	return (this.playerobject)?this.playerobject.getMute():false;  
  };
  
  this.play = function() {
	return (this.playerobject)?this.playerobject.play():false;
  }; 
  
  this.pause = function() {
	return (this.playerobject)?this.playerobject.pause():false;
  }; 

  this.stop = function() {
	return (this.playerobject)?this.playerobject.stop():false;
  };
  
  this.getplaystate = function() {
	return (this.playerobject)?this.playerobject.getPlayState():false;  
  };
  
  this.isplaying = function() {
	return (this.getplaystate()==3);  
  };
  
  this.getcurrentstatus = function() {
	var playstate = this.playerobject.getPlayState();
	if (isNaN(playstate)) return "";
    return statustext[playstate]?statustext[playstate]:"";		  
  };
  
  this.getcurrentposition = function() {
	return (this.playerobject)?this.playerobject.getCurrentPosition():0;  	  
  };
  
  this.setcurrentposition = function(time) {
	return (this.playerobject)?this.playerobject.setCurrentPosition(time):false;  	  
  }; 
  
  this.getduration = function(time) {
	return (this.playerobject)?this.playerobject.getDuration():false;  	  
  };

  this.getvolume = function() {
	return (this.playerobject)?this.playerobject.getVolume():false;  	  
  };
  
  this.setvolume = function(volume) {
	return (this.playerobject)?this.playerobject.setVolume(volume):false;  	  
  }; 

  this.getsecondsplayedbyfraction = function(frac) {
    return Math.round(this.getduration()*frac);
  };
  
  this.updatetime = function() {
    var lastplaystate = this.currentplaystate;

    if ((this.currentplaystate=this.getplaystate())!=lastplaystate) {
      if (window.updatestatusobjects) updatestatusobjects(this.currentplaystate);
    }
    var currentpos = this.getcurrentposition();
	
    if (window.updatetimeobjects) updatetimeobjects(currentpos);
    if (this.isplaying()) {
        this.totaltimeplayed+=(statusrefreshperiod/1000);
        timeline.processevents(currentpos);
    }
  };
  
  this.recordplayedtime = function() {	

    if (this.totaltimeplayed>0 && (this.recordtimeurl!=false)) {
	var totaltimeplayed = Math.floor(this.totaltimeplayed);
	var url = this.recordtimeurl+"&timeplayed="+totaltimeplayed+"&"+Math.random();
	var imgobj = new Image;
	imgobj.src = url;
    writedebug("Set time played :"+totaltimeplayed);		
    }
  };
}

function drawimage(imagename,width,height) {
	return "<img width=\""+width+"\" height=\""+height+"\" src=\""+imagepath+imagename+"\"/>";
}

function drawimagebutton(id,text,onclickevent) {
	return "<div id=\""+id+"\" class=\"imagebutton\" onclick=\""+onclickevent+";\"><div class=\"l\"></div><div class=\"m\">"+text+"</div><div class=\"r\"></div></div>";
}

function drawroundedframe(id,text) {
	var onclickevent = (arguments.length>=3)?"onclick=\""+arguments[2]+";\"":"";
	var style = (arguments.length==3)?"style=\"cursor:pointer;\"":"";	
	var out = "<div class=\"roundedframe\" "+onclickevent+" "+style+">";
	out += "<table class=\"frametable\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
	out += "<tr><td height=\"4\" width=\"4\" class=\"tl\">"+drawimage('spacer.gif',4,4)+"</td><td class=\"tm\" height=\"4\">"+drawimage('spacer.gif',4,4)+"</td><td width=\"4\" height=\"4\" class=\"tr\">"+drawimage('spacer.gif',1,1)+"</td></tr>";
	out += "<tr><td class=\"sl\">"+drawimage('spacer.gif',4,4)+"</td><td class=\"mid\"><div class=\"main\" width=\"100%\">"+text+"</div></td><td class=\"sr\">"+drawimage('spacer.gif',4,4)+"</td></tr>";	
	out += "<tr height=\"4\"><td class=\"bl\" height=\"4\" width=\"4\">"+drawimage('spacer.gif',4,4)+"</td><td class=\"bm\" height=\"4\">"+drawimage('spacer.gif',4,4)+"</td><td width=\"4\" height=\"4\" class=\"br\">"+drawimage('spacer.gif',4,4)+"</td></tr>";	
	out += "</table>";
	out += "</div>";
	return out;
}

function bttimelineevent(time,action,params) {
  this.time = time;
  this.action = action;
  this.params = params;
}

function bttimeline() {
  this.eventlist = new Array();
  this.lasteventidx = null;
  this.mediaobject = null;
	
  this.addevent = function(time,action,params) {
	//alert(time+":"+action);
    this.eventlist[this.eventlist.length] = new bttimelineevent(time,action,params);
	//if (slides) {
    //  eventParts = action.split("'");
    //  if (eventParts.length == 3 && eventParts[0] == 'slides.show(') {
    //    var sld = slides.findslide(eventParts[1]);
	//    sld.time = (this.eventlist.length-1);
	//  }
	//}
  }
  
  this.debug = function() {
  }

  this.processevents = function(currenttime) {
    for (var idx=(this.eventlist.length-1); idx>=0; idx--) {
	  //window.status = idx+":"+this.eventlist[idx].time+":"+currenttime;
      if (currenttime>=this.eventlist[idx].time) {
		this.executeevent(idx);
        break;
      }
    }
    return false;
  }
  
  this.executeevent  = function(idx) {
	if (this.lasteventidx !=idx) {
	  this.lasteventidx = idx;
	  eval(this.eventlist[idx].action);
	}
  }
  
  this.jumptoindex = function(idx) {
	if (this.eventlist[idx]) { 
	  if (this.mediaobject) {
	    this.mediaobject.setcurrentposition(this.eventlist[idx].time);
	  }
	}
  }
  
  this.setmediaobject = function(object) {  
	this.mediaobject = object;  
  }
}


function bttab(alias,title,contentobj,parentobj) {
  this.alias = alias;
  this.title = title;
  this.contentobject = contentobj;
  this.parentobject = parentobj;
  this.isactive = false;
  this.ishighlited = false;
  this.contentobject.parentobject = this; 
  this.className = 'bttab';
  this.uid = panels.register(this);   

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement('title');
        if (titleobj) titleobj.value = this.title;
  }
  
  this.drawtab = function() {
    document.write("<li id=\""+this.getelementid('tab')+"\" onclick=\"callpanel("+this.uid+",'clickedtab()');\"><a href=\"#\">"+this.title+"</a></li>");
  }
  
  this.drawpanel = function() {
    document.write("<div class=\""+this.contentobject.className+"\" style=\"display:"+(this.isactive?'block':'none')+";\" id=\""+this.getelementid('panel')+"\">");
    document.write(this.contentobject.render());
    document.write("</div>");	  
  }
  
  this.refreshpanel = function() {
	 var newcontent = this.contentobject.refresh(); 
	 if (newcontent) {
	   var panelObj = this.getelement('panel');
       if (panelObj) panelObj.innerHTML = newcontent;
     }
  }
  
  this.clickedtab = function() {  
	this.parentobject.clicktab(this);
  }
  
  this.active = function(on) {
	var tabObj = this.getelement('tab');
	if (tabObj) tabObj.className = (on)?"selected":"";
	this.displaypanel(on);
	this.isactive = on;
	this.ishighlited=false;
  }
  
  this.highlite = function(on) {
	if (this.isactive) return;
	var tabObj = this.getelement('tab');
	if (tabObj) tabObj.className = (on)?"highlite":"";
	this.ishighlighted = on;
  }
  
  this.refreshtab = function() {
	if (this.ishighlighted) {
	  this.highlite(true);
	} else {
	  this.active(this.isactive);	
	} 
  }
  
  this.displaypanel = function(show) {
	var panelObj = this.getelement('panel');
	if (panelObj) displayobject(panelObj,show);	
  }
  
  this.contentchanged = function(highliteon) {
	this.highlite(highliteon);	
	this.refreshpanel();
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  }   
}


function bttabs() {
  this.tablist = new Array();
  this.activetab = null;
  this.showtabs = true;
  this.className = 'bttabs';
  this.uid = panels.register(this);

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }  
   
  this.addtab = function(alias,title,contentobj) {
    newtab = new bttab(alias,title,contentobj,this);    
	if (this.activetab==null) {
	  this.activetab = newtab;
	  newtab.active(true);
	}
    this.tablist[this.tablist.length] = newtab;
  }
   
  this.clicktab = function(obj) {
	if (this.activetab == obj) return;
	this.activetab.active(false);
	this.activetab = obj;
	this.activetab.active(true);
  }
  
  this.highlite = function(alias,on) {
	 var tab = this.findtab(alias);
	 if (tab!=null) {
	    tab.highlite(on);
	 }
  }
  
  this.show = function(alias) {
	 var tab = this.findtab(alias);
	 if (tab!=null) {
		this.clicktab(tab); 
	 }
  }
  
  this.findtab = function(alias) {
	for (var idx=0;idx<this.tablist.length;idx++) {
       if (this.tablist[idx].alias==alias) return this.tablist[idx];
    }
	return null;
  }
  
  this.findtabindex = function(tabobj) {
	for (var idx=0;idx<this.tablist.length;idx++) {
       if (this.tablist[idx]==tabobj) return idx;
    }
	return null;  
  }
  
  this.nexttab = function() {
	  var currenttabidx = this.findtabindex(this.activetab);
	  if (currenttabidx!=null) {
		  currenttabidx++;
		  if (currenttabidx>=this.tablist.length) currenttabidx = 0;
		  this.clicktab(this.tablist[currenttabidx]);
	  }
  }
   
  this.drawtabs = function() {
    document.write("<ul class=\"tabs\">");
    for(var idx=0;idx<this.tablist.length;idx++) {
      tab = this.tablist[idx];
      tab.drawtab();
    }
    document.write("</ul>");
  }
  
  this.drawpanel = function() {
    document.write("<div class=\"tabbody\">");
    for (var idx=0;idx<this.tablist.length;idx++) {
      tab = this.tablist[idx];	
      tab.drawpanel();
    }
    document.write("</div>");
  }  
  
  this.refreshtabs = function() {
	for(var idx=0;idx<this.tablist.length;idx++) {	  
      tab = this.tablist[idx];
	  tab.refreshtab();
	}
  }
   
  this.draw = function() { 
  	document.write("<div id=\""+this.getelementid('tabpanel')+"\" class=\"tabpanel\">");	  
  	if (this.showtabs) this.drawtabs();	 	
  	this.drawpanel();
  	document.write("</div>");
  	this.refreshtabs();
  }   
  
  this.contentchanged = function(highliteon) {	
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  }  
}

function btslide(alias,imagesrc,title,time) {
  this.alias = alias;	
  this.title = title;
  this.imagesrc = imagesrc;
  this.image = null;
  this.index = null;
  this.className = "btslide";
  this.time = time;
  this.uid = panels.register(this);    
  this.eventobj = (this.time!=null)?timeline.addevent(time,"slides.show('"+this.alias+"')"):null;
  
  this.preload = function() {
    if (!this.image) {	
      this.image = new Image();
      this.image.src = imagesrc;
    }
    return true;
  }
}

function btslidelist() {
  this.title = "slides";
  this.slidelist = new Array();
  this.activeslide = null;
  this.showselector = true;
  this.slidepath = "";
  this.width = 640;
  this.height = 480;
  this.className = "btslidelist";   
  this.uid = panels.register(this);   
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }   

  this.settitle = function(text) {
    	this.title = text;
    	var titleobj = this.getelement("title");
    	if (titleobj) titleobj.value = this.title;
  }

  this.addslide = function(alias,imagesrc,title,time) {
	var newslide = new btslide(alias,this.slidepath+imagesrc,title,time);
	newslide.index = this.slidelist.length;
	this.slidelist[this.slidelist.length] = newslide;  
	//if (!this.activeslide) this.activeslide = newslide;
  }

  this.hasslides = function() {
	return (this.slidelist.length>0);  
  }
  
  this.render = function() {
        if (this.activeslide) {
          displayedslide = this.activeslide;
        } else {
          displayedslide = this.slidelist[0];
        }
	var out  = "<img id=\""+this.getelementid("slidebox")+"\" class=\"slidebox\" src=\""+displayedslide.imagesrc+"\" width=\""+this.width+"\" height=\""+this.height+"\">";  
    if (this.hasslides()) {
	  out += this.renderselector();
	}
    return out;
  }
  
  this.refresh = function() {
	this.updateslidebox();
	this.updateslideselect(); 
	return false;
  }  
  
  this.selectorchanged = function() {
	var selector = this.getelement("slideselect");
    if (selector) {
	  idx = selector.options[selector.selectedIndex].value;
	  slides.showbyindex(idx);
	  if (timeline) {
	    var slide = slides.getslidebyindex(idx);
	    if (slide && slide.time!=null) {
		  media.setcurrentposition(slide.time);
	    }
	  }	
    }
  }
  
  this.renderselector = function() {
	var out= "<div class=\"slidelistpanel\" id=\""+this.getelementid('slidelist')+"\">"; 
	out+= "<select id=\""+this.getelementid("slideselect")+"\" class=\"slideselector\" onchange=\"callpanel("+this.uid+",'selectorchanged()');\">"; 
    for(var i=0;i<this.slidelist.length;i++) {	
	  slide = this.slidelist[i];
	  out += "<option value=\""+i+"\" "+(i==0?"selected":"")+">"+(i+1)+". "+slide.title+"</option>";
	}
	out += "</select>";  
	out += "</div>";
	return out;
  }  
  
  this.findslide = function(alias) {
	for (var idx=0;idx<this.slidelist.length;idx++) {
       if (this.slidelist[idx].alias==alias) return this.slidelist[idx];
    }
	return null;
  }  
  
  this.getslidebyindex = function(idx) {
	if (idx>=0 && idx<=this.slidelist.length) {
          return this.slidelist[idx];
        }
	return false;
  }
  
  this.updateslidebox = function() {
	var slideboxobj = this.getelement("slidebox");
	if (slideboxobj) {
	   slideboxobj.src = this.activeslide.imagesrc;	   
	}
  }
  
  this.updateslideselect = function() {
	var slideselectobj = this.getelement("slideselect");
	if (slideselectobj) {
		slideselectobj.selectedIndex = this.activeslide.index;
	}
  }
  
  this.showbyindex = function(index) {
	if (index>=0 && index<this.slidelist.length+1) {
	  var newslide = this.slidelist[index];
	  if ((newslide!=null)  && (newslide!=this.activeslide)) {
	   this.activeslide = newslide;
	   this.contentchanged();
	  }
	}
  }

  this.preload = function() {
    for (var idx=0;idx<this.slidelist.length;idx++) {
       this.slidelist[idx].preload();
    }	  
  }
  
  this.show = function(alias) {
	var newslide = this.findslide(alias);
	if ((newslide!=null)  && (newslide!=this.activeslide)) {
	   this.activeslide = newslide;
	   this.contentchanged(true);
	}
	return newslide;
  }
  
  this.contentchanged = function(highliteon) {	
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  }  
}

function btfeedback(alias) {
  this.alias = alias;
  this.title = "Your Feedback";
  this.className = "btfeedback"; 	
  this.introtext = "Please give your feedback and then click submit";
  this.commentstext = "Your Comments";
  this.ratingtext = "Rating";
  this.responsetext = "Thank you for your feedback";
  this.showrating = true;
  this.email = "";
  this.rating = 0;
  this.buttontext = "Send Feedback";
  this.scorenames = Array("Unrated","Very Bad","Bad","Average","Good","Excellent");
  this.posturl = "../mod/post_feedback.php";
  this.useremail = "";  
  this.selectedpresenter = null;  
  this.uid = panels.register(this);      
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }  

  this.settitle = function(text) {
    	this.title = text;
    	var titleobj = this.getelement("title");
    	if (titleobj) titleobj.value = this.title;
  }

  this.setintrotext = function(text) {
	this.introtext = text;  
  }

  this.setresponsetext = function(text) {
	this.responsetext = text;  
  }

  this.setshowrating = function(on) {
	this.showrating = on;
  }
  
  this.requestrating = function(on) {
	this.showrating = (on==true); 
  }

  this.setbuttontext = function(text) {	
	this.buttontext = text;
  }
  
  this.setratingtext = function(text) {
	this.ratingtext = text;
	if (rtobj = this.getelement("ratingtext")) {
	  rtobj.innerHTML = this.ratingtext+" ("+this.scorenames[this.rating]+")";  
	}	  
  }
  
  this.setemailtext = function(text) {
	this.emailtext = text;
	if (rtobj = this.getelement("emailtext")) {
	  rtobj.innerHTML = this.emailtext;  
	}	  
  }  
  
  this.setemail = function(text) {
	this.email = text;
	if (rtobj = this.getelement("email")) {
	  rtobj.value = this.email;  
	}	  
  }    
  
  this.setrating = function(rating) {
	this.rating = rating;	
    var ratingobj = this.getelement("rating");	
	if (ratingobj) ratingobj.value = this.rating;
    if (this.showrating==true) {
	  for (i=1;i<=5;i++) {
		var ridimobj = this.getelement("ratingstar"+i);  
		if (ridimobj) {
		  var ratingstate = (this.rating==null)?"non":((this.rating>=i)?"off":"non");
          ridimobj.src = imagepath+"rating"+ratingstate+".gif";
        }
      }
      this.setratingtext(this.ratingtext);
	}	
  }

  this.setposturl = function(url) {
	this.posturl = url;
  }
  
  this.setcomments = function(text) {
	 var introtextobj = this.getelement("comments");
	 if (introtextobj) introtextobj.value = text;
  }
  
  this.getcomments = function() {
	 var commenttextobj = this.getelement("comments");
	 return (commenttextobj)?commenttextobj.value:"";
  }
  
  this.getemail = function() {
	 var emailtextobj = this.getelement("email");
	 return (emailtextobj)?emailtextobj.value:"";
  }  
  
  this.clickedsubmit = function() {
	var commentsobj = this.getelement('comments');
        if (this.selectedpresenter==null) {
          alert("Please select a presenter");
          return;
        }
        if (commentsobj.value=="") {
          alert("Please provide your comments");
          commentsobj.focus();
          return;
        }
	alert(this.responsetext);
	var formobj = this.getelement('form');
	if (formobj) formobj.submit();
	this.setcomments("");		
	this.setrating(0);	
  }

  this.clickpresenter = function(idx) {
     var radiobutton = this.getelement('presenterradio'+idx);
     radiobutton.checked = true;
     this.selectedoption = idx;
     this.selectedpresenter = idx;
  }
  
  this.render = function() {
    var out= "<div class=\"feedbackpanel\" id=\""+this.getelementid('feedback')+"\">"; 
    out += (this.title!="")?"<h1>"+this.title+"</h1>":"";
    out += "<div id=\""+this.getelementid("introtext")+"\" class=\"helptext\">"+this.introtext+"</div>";
    out += "<form id=\""+this.getelementid('form')+"\" method=\"post\" action=\""+this.posturl+"\" target=\""+this.getelementid('hiddenframe')+"\">";
    out += "<input name=\"eventguid\" type=\"hidden\" id=\""+this.getelementid("eventguid")+"\" value=\""+communication.id+"\" />";
    out += "<input name=\"userguid\" type=\"hidden\" id=\""+this.getelementid("userguid")+"\" value=\""+communication.userid+"\" />"
    out += "<input name=\"fbrating\" type=\"hidden\" id=\""+this.getelementid("rating")+"\" value=\""+this.rating+"\" />";	

    //out += "<div id=\""+this.getelementid("commentstext")+"\" class=\"helptext\">"+this.commentstext+"</div>";
    out += "<textarea name=\"comments\" class=\"comments\" id=\""+this.getelementid("comments")+"\"></textarea>";
    out += "<br/><br/>";

    out += "<div class=\"presenterselector\">";
    for(var idx=0;idx<overview.presenterlist.length;idx++) {
      var presenter = overview.presenterlist[idx];
      var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";
      text +="<tr>";
      text +="<td>"+presenter.name+"</td><td width=\"25\"><input type=\"radio\" id=\""+this.getelementid('presenterradio'+idx)+"\" name=\"presenterguid\" value=\""+presenter.assetid+"\"></td>";
      text +="</tr>";
      text +="</table>";
      out+= drawroundedframe(this.getelementid('presenters'),text,"callpanel("+this.uid+",'clickpresenter("+idx+")');");
    }
    out += "</div>";
    out += "<br/>";

    if (this.showrating==true) {
      out += "<div id=\""+this.getelementid("ratingtext")+"\" class=\"helptext\">"+this.ratingtext+" ("+this.scorenames[0]+")</div>";
      for (i=1;i<=5;i++) {
	var ratingstate = (this.rating==null)?"non":((this.rating>i)?"off":"non");
	out += "<img width=\"30\" height=\"30\" id=\""+this.getelementid("ratingstar"+i)+"\" alt=\""+this.scorenames[i]+"\" onclick=\"callpanel("+this.uid+",'setrating("+i+")');\" src=\""+imagepath+"rating"+ratingstate+".gif\">";
      }
      out += "<br/><br/>";	
    }
    out += drawimagebutton(this.getelementid('submit'),this.buttontext,"callpanel("+this.uid+",'clickedsubmit()')");		
    out += "</form>";
    out += "<iframe id=\""+this.getelementid('hiddenframe')+"\" name=\""+this.getelementid('hiddenframe')+"\" class=\"debugpostframe\"></iframe>";
    out += "</div>";
    return out;	  
  }
  this.refresh = function() {
  
  }  
  
  this.contentchanged = function(highliteon) {	
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  }  
}

function btpresenter(assetid,name,jobtitle,company,imageurl,description) {
  this.assetid = assetid;
  this.imageurl = imageurl;
  this.name = name;
  this.jobtitle = jobtitle;
  this.company = company;
  this.description = (description==false)?"":description;
  this.uid = panels.register(this);

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }
 
  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }
}

function btsponsor(assetid,name,url,imageurl) {
  this.assetid = assetid;
  this.imageurl = imageurl;
  this.name = name;
  this.url = url;
  this.uid = panels.register(this);

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }
  
  this.render = function() {
        return "<a href=\""+this.url+"\" target=\"_blank\" alt=\""+this.name+"\"><img class=\"sponsorimage\" src=\""+this.imageurl+"\"></a>";
  }
}

function btoverview() {
  this.className = "btoverview";
  this.presenterlist = new Array();
  this.sponsorlist = new Array();
  this.title = "Overview";
  this.uid = panels.register(this);

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }

  this.addpresenter = function(assetid,name,jobtitle,company,imageurl,description) {
        var newpresenter = new btpresenter(assetid,name,jobtitle,company,imageurl,description);
        this.presenterlist[this.presenterlist.length] = newpresenter;
        return newpresenter;
  }

  this.addsponsor = function(assetid,name,url,imageurl) {
        var newsponsor = new btsponsor(assetid,name,url,imageurl);
        this.sponsorlist[this.sponsorlist.length] = newsponsor;
        return newsponsor;
  }

  this.render = function() {
    var out = "<div class=\"presenterspanel\" id=\""+this.getelementid('details')+"\">";
    //out += (communication.title!="")?"<h1>"+communication.title+"</h1>":"";
    //out += (communication.description!="")?"<div class=\"description\">"+communication.description+"</div>":"";
    out += "<div class=\"presenters\">";
    for(var idx=0;idx<this.presenterlist.length;idx++) {
      var text = "<table width='100%' border='0' cellspacing='0' cellpadding='0'/>";
      text+= "<tr>";
      text+= "<td width='50' valign='top'><img src='"+this.presenterlist[idx].imageurl+"' width='39' height='45' class='pic'/></td>";
      text+= "<td valign='top'>";
      text+= "<div class='name'>"+this.presenterlist[idx].name+"</div>";
      text+= "<div class='jobtitle'>"+this.presenterlist[idx].jobtitle+"</div>";
      text+= "<div class='company'>"+this.presenterlist[idx].company+"</div>";
      text+= "<div class='description'>"+this.presenterlist[idx].description+"</div>";
      text+= "</td>";
      text+= "</tr>";
      text+= "</table>";
      out+= drawroundedframe(this.getelementid('file'),text);  			 
    }
    out += "</div>";
    if (this.sponsorlist.length>0) {
      out += "<div class=\"sponsorsboxtitle\">Event Sponsored By</div>";
      out += "<div class=\"sponsorsbox\">";
      out += "<table class=\"sponsortable\">";
      out += "<tr>";
      for(var idx=0;idx<this.sponsorlist.length;idx++) {
        var sponsor = this.sponsorlist[idx];
        out += "<td>";
        out += sponsor.render();
        out += "</td>";
      }
      out += "</tr>";
      out += "</table>";
      out += "</div>";
    }
    out += "</div>";
    return out;
  }

  this.draw = function() {
         document.write(this.render);
  }

  this.refresh = function() {

  }

  this.contentchanged = function(highliteon) {
        if (this.parentobject) this.parentobject.contentchanged(highliteon);
  }
}




function btfile(assetid,link,title,description,mimetype) {
  this.assetid = assetid;
  this.link = link;
  this.title = title;
  this.mimetype = mimetype;
  this.description = (description==false)?"":description;
  this.openinwindow = false;
  this.windowwidth = 0;
  this.windowheight = 0;
  this.posturl = "../mod/update_stats.php";
  this.uid = panels.register(this);    

  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }

  this.settitle = function(text) {
    	this.title = text;
    	var titleobj = this.getelement("title");
    	if (titleobj) titleobj.value = this.title;
  }
  
  this.actioncall = function(action) {
	return "callpanel("+this.uid+",'"+action+"')"; 
  }
  
  this.clickedfile = function() {
    var url = this.posturl+"?communication_id="+communication.id;
    url+="&asset_id="+this.assetid;
    url+="&name="+this.title;
    url+="&description="+this.description;
    url+="&player_id="+communication.playerid;
    url+="&player_name="+communication.playername;  
    url+="&type=Download";
    var imgobj = new Image;
    imgobj.src = url;
  }

  this.render = function() {
	var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";		
	text +="<tr>";
	text +="<td>";
	text +="<div class=\"title\"><a class=\"file\" href=\""+this.link+"\" target=\"_blank\">"+this.title+"</a></div>";
	if (this.description) text +="<div class=\"description\">"+this.description+"</div>";
	text +="</td><td width=\"25\" valign=\"top\" align=\"right\"><a class=\"file\" href=\""+this.link+"\" target=\"_blank\"><img class=\"icon "+this.mimetype+"\" src=\""+imagepath+"spacer.gif\"></a></td>";
	text +="</tr>";	  
	text +="</table>";	  
	return drawroundedframe(this.getelementid('file'),text);  			 
  }
  
  this.refresh = function() {
  
  }  
}

function btdownloads() {
  this.className = "btdownloads"; 
  this.filelist = new Array();  
  this.title = "Downloads";
  this.description = "Please click a file to download";  
  this.uid = panels.register(this);      

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  

  this.addfile = function(assetid,link,title,description,mimetype) {
	var newfile = new btfile(assetid,link,title,description,mimetype);
	this.filelist[this.filelist.length] = newfile;  
	return newfile;
  }
  
  this.render = function() {
	var out = "<div class=\"downloadspanel\" id=\""+this.getelementid('downloads')+"\">";	  
    out += (this.title!="")?"<h1>"+this.title+"</h1>":"";
    out += (this.description!="")?"<div class=\"description\">"+this.description+"</div>":"";	
    out += "<div class=\"filelist\">";
    for(var idx=0;idx<this.filelist.length;idx++) {
	   out += this.filelist[idx].render();
	}
	out += "</div>"; 
	out += "</div>"; 
	return out;
  }
  
  this.draw = function() {
	 document.write(this.render);  
  }
  
  this.refresh = function() {
  
  }  
  
  this.contentchanged = function(highliteon) {
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  } 
}


function btchapter(time,description) {
  this.time = time;
  this.description = description;
  this.parent = null;  
  this.className = "btchapter";   
  this.uid = panels.register(this);    

  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }    
  
  this.actioncall = function(action) {
	return "callpanel("+this.uid+",'"+action+"')"; 
  }
  
  this.clickedchapter = function() {
	if (media) {
	   media.jumpandplay(this.time);	   
	}
  }

  this.render = function() {;
	var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";		
	text +="<tr>";
	text +="<td>"+this.description+"</td><td width=\"25\" valign=\"top\" align=\"right\"><img class=\"icon\" src=\""+imagepath+"spacer.gif\"></td>";
	text +="</tr>";	  
	text += "</table>";	  
	return drawroundedframe(this.getelementid(''),text,this.actioncall('clickedchapter()'));  
  }
  
  this.refresh = function() {
  
  }  
}


function btchapters() {
  this.className = "btchapters"; 
  this.chapterlist = new Array();  
  this.title = "Chapters";
  this.parent = null;  
  this.uid = panels.register(this);

  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }     
  
  this.addchapter = function(time,description) {
	var newchapter = new btchapter(time,description);
	newchapter.parent = this;
	this.chapterlist[this.chapterlist.length] = newchapter;  
  }
  
  this.render = function() {
	var out = "<div class=\"chapterspanel\" id=\""+this.getelementid('chapters')+"\">";		  
    out += (this.title!="")?"<h1>"+this.title+"</h1>":"";
    out += "<div class=\"chapters\">";	
    for(var idx=0;idx<this.chapterlist.length;idx++) {
	  out += this.chapterlist[idx].render();
	}
    out += "</div>";	
    out += "</div>";		
	return out;
  }
  
  this.draw = function() {
	 document.write(this.render);  
  }
  
  this.refresh = function() {
  
  }  
  
  this.contentchanged = function(highliteon) {
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  } 
}



function btformfield(type,title) {
	this.title = title;
	this.type = type;
    this.uid = panels.register(this);    
    this.className = "btformfield";	
	

	this.getelementid = function(name) {
		return this.className+this.uid+name;
	}
  
	this.getelement = function(name) {
		return document.getElementById(this.getelementid(name));  
	}	
	
	this.getvalue = function() {
		var formelement = this.getelement(this.type);
		
	}
	
	this.render = function() {
		var id = this.getelementid(this.type);
		switch(type) {
			case 'txtBox':
			   return "<div class=\"formfield\">" + this.title +"<br><input id=\""+id+"\" class=\"textfield\" name=\""+id+"\" type=\"text\"/></div>";
			break;
			
			case 'chkBoxOn': 
			  return "<div class=\"formfield\"><input class=\"checkbox\" id=\""+id+"\" name=\""+id+"\" type=\"checkbox\" checked/>"+this.title+"</div>";			
			break;

			case 'chkBoxOff': 
			  return "<div class=\"formfield\"><input class=\"checkbox\" id=\""+id+"\" name=\""+id+"\" type=\"checkbox\" />"+this.title+"</div>";			
			break;
		}
	}
}


function btform() {
  this.title = null;
  this.formfields = Array();
  this.posted = false;
  this.uid = panels.register(this);    
  this.className = "btform";

  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }
  
  this.post = function() {
	this.posted = true;
  }
  
  this.addfield = function(type,title) {
	 this.formfields[this.formfields.length] = new btformfield(type,title); 
  }
  
  this.render = function() {
	var out = "<div class=\"formpanel\" id=\""+this.getelementid('formpanel')+"\">";
	for(var i=0;i<this.formfields.length;i++) {
	  out += this.formfields[i].render();
	}
	out += "</div>";
	return out;
  }
}

function bttestquestion(alias,questiontext,selectmultiple)  {
  this.parent = null;
  this.alias = alias;
  this.questiontext = questiontext;
  this.className = "bttestquestion";  
  this.selectmultiple = selectmultiple;
  this.options = new Array();
  this.selectedoptions = new Array();
  this.answered = false;
  this.iscorrect = false;
  this.submitted = false;
  this.marked = false;
  this.uid = panels.register(this);    
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }    
  
  this.setparent = function(parentobj) {
	this.parent = parentobj;  
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  
	
  this.addoption = function(text) {  
    this.selectedoptions[this.selectedoptions.length] = text;	
  }
  
  this.deselectall = function() {
    for(var idx=0;idx<this.selectedoptions.length;idx++) {
	   this.selectedoptions[idx] = false;
	}
  }
  
  this.isselected = function(idx) {
	return this.selectedoptions[idx]; 
  }
 
  this.selectoption = function(idx) {
	this.selectedoptions[idx] = true;
  }
  
  this.deselectoption = function(idx) {
	this.selectedoptions[idx] = false;
  }
  
  this.getinputvalue = function() {
	var input = "";
    for(var idx=0;idx<this.selectedoptions.length;idx++) {
	   if (this.selectedoptions[idx]) input+=idx+",";
	}
	return (input.substring(0,input.length-1));
  }
  
  this.checkboxes = function() {
    for(var idx=0;idx<this.selectedoptions.length;idx++) {
	  var checkboxobj = this.getelement('checkbox'+idx);
	  if (checkboxobj) checkboxobj.checked = this.isselected(idx);
	}	  
  }
  
  this.clickanswer = function(idx) {
	if (this.selectmultiple) {
	  this.selectedoptions[idx] = !this.isselected(idx);
	} else {
	  this.deselectall();
	  this.selectedoptions[idx] = true;
	}	
	this.checkboxes();
  }
  
  
  this.submit = function() {
	if (this.selectedoptions.length<1) {    
	  alert("Please choose from the selection");
	  return false;
	}
	//submit here
	//alert("submitting answer : "+this.getinputvalue());
	return true;
  }
  
  this.renderbutton = function(idx) {
	  var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";		
	  text +="<tr>";
	  text +="<td>"+this.getoptionletter(idx)+") "+this.options[idx].text+"</td><td width=\"25\"><input type=\"checkbox\" id=\""+this.getelementid('checkbox'+idx)+"\" name=\"Q01\" value=\""+this.options[idx].alias+"\" "+(this.isselected[idx]?"checked":"")+"></td>";
	  text +="</tr>";	  
	  text += "</table>";	   
	  return drawroundedframe('123',text,"callpanel("+this.uid+",'clickanswer("+idx+")');");	
  }
  
  this.renderaskquestion = function() {
	  
  }
  
  this.rendershowanswer = function() {
	  
  }

  this.render = function() {  
	var out = "<div class=\"question\" id=\""+this.getelementid('question')+"\">";
	out += "<div class=\"questionnumber\">Question "+this.parent.currentquestionnumber()+" of "+this.parent.gettotalquestions()+"</div>";
	out += this.questiontext;
	out += "</div>";
    out += "<div class=\"helptext\" id=\""+this.getelementid('helptext')+"\">";
	if (this.selectmultiple) {
      out += "Please select the correct answers below";
	} else {
	  out += "Please select one option from below";
	}
    out += "</div>";	
	for(var idx=0;idx<this.options.length;idx++) {
		out+=this.renderbutton(idx);
	}
	return out;
  }  
  
  this.getoptionletter = function(letternum) {
    return String.fromCharCode(65+letternum);
  }   
}

function bttest(alias) {
  this.alias = alias;	
  this.title = "Test";
  this.description = null;
  this.onchange = null;	
  this.className = "bttest";
  this.questionlist = new Array();
  this.viewanswers = 0;
  this.registrationform = new btform();
  this.currentquestion = null;
  this.passmessage = "You passed";
  this.failmessage = "Sorry. You didn't pass";
  this.registered = false;
  this.viewanswers = false;
  this.passmark = null;
  this.uid = panels.register(this);    
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }  

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  
  
  this.setdescription = function(text) {
        this.description = text;
        var descriptionobj = this.getelement("description");
        if (descriptionobj) descriptionobj.value = this.description;
  }  
  
  this.setpassmessage = function(message) {
  	this.passmessage = message;
  }
  
  this.setfailmessage = function(message) {
	  this.failmessage = message;
  }

  this.setpassmark = function(mark) {
	  this.passmark = mark;
  }
  
  this.setattempts = function(attempts) {
	this.attempts = attempts;  
  }
  
  this.setviewanswers = function(view) {
	  
  }
  
  this.getpanelcall = function(call) {
	return "callpanel("+this.uid+",call)";
  }
  
  this.currentquestionnumber = function() {
	for(var idx=0;idx<this.questionlist.length;idx++) {
	  if (this.currentquestion==this.questionlist[idx]) return (idx+1);
	}
	return -1;
  }
  
  this.gettotalquestions = function() {
	return  this.questionlist.length;
  }

  this.addquestion = function(alias,questiontext,numanswers) {
	var question = new bttestquestion(alias,questiontext,numanswers);
	for(i=3;i<arguments.length;i++) {
	  question.addoption(arguments[i]);
 	}
	question.parent = this;
	this.questionlist[this.questionlist.length] = question;
	if (this.currentquestion == null) this.currentquestion = question;
  }
  
  this.addregistrationfield = function(type,title) {
	this.registrationform.addfield(type,title);  
  }

  this.refresh = function() {
	return this.render();
  }
  
  this.submit = function() {
	if (!this.registrationform.posted) {
	  this.registrationform.post();
	  var questionareaobj = this.getelement('questionarea');
	  if (questionareaobj) questionareaobj.innerHTML = this.currentquestion.render();
	} else {
	  if (this.currentquestion.submit()) {
		//get next question  
	  }
	}
  }
  
  this.getquestionindex = function(questionobj) {
	for (var idx=0;idx<this.questionlist.length;idx++) {
       if (this.questionlist[idx]==questionobj) return idx;
    }
	return null;	  
  }  

  this.movequestion = function(amount) {
	var questioncount = this.questionlist.length;
	var currentquestionidx = this.getquestionindex(this.currentquestion);
	var newquestionindex = currentvoteidx+amount;
	if (newquestionindex<0) newquestionindex=0;
	if (newquestionindex>=questioncount) newquestionindex=questioncount-1;
	this.currentquestion = this.questionlist[newquestionindex];
	this.contentchanged();
  }

  this.getnextquestion = function() {
	  
  }
  
  this.renderregistration = function() {
	  
  }
  
  this.render = function() {
	var out = "<div class=\"testpanel\" id=\""+this.getelementid('test')+"\">";		  
    out += (this.title!="")?"<h1>"+this.title+"</h1>":"";	
	out += "<div class=\"questionarea\" id=\""+this.getelementid('questionarea')+"\">";
	if (this.registrationform.posted) {
	  out += this.currentquestion.render();		
	} else {
	  if (this.description) out += "<div class=\"description\" id=\""+this.getelementid('description')+"\">"+this.description+"</div>";
	  out += this.registrationform.render();
	}
	out += "</div>";
	out += drawimagebutton(this.getelementid('submit'),"Next","callpanel("+this.uid+",'submit()')");	
	out += "</div>";
	return out;
  }

  this.contentchanged = function(highliteon) {
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  } 
}

function btvoteoption(alias,text) {
  this.alias = alias;
  this.text = text;
  this.className = "btvoteoption";
  this.percentage = 0;   
  this.uid = panels.register(this);    
  this.parent = null;

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }

  this.renderresult = function() {
    out ="<div class=\"voteresult\">"+this.text+" (<span id=\""+this.getelementid("percent")+"\">"+this.percentage+"</span>%)</div>";
    out +="<div class=\"votebarbox\" >";
    out +="<div class=\"votebar\" id=\""+this.getelementid("graphbar")+"\" style=\"width:"+this.percentage+"%;\"></div>";
    out +="</div>";
    return out;
  }

  this.renderquestion = function() {
    var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";
    text +="<tr>";
    text +="<td>"+this.options[idx].text+"</td><td width=\"25\"><input type=\"radio\" id=\""+this.getelementid('radio')+"\" name=\""+this.getelementid('radio')+"\" value=\""+this.options.alias+"\" "+((this.selectedoption==idx)?"checked=\"true\"":"")+"></td>";
    text +="</tr>";
    text += "</table>";
    return drawroundedframe('123',text,"callpanel("+this.uid+",'clickanswer()');");

  }

  this.updategraph = function() {
    slidebarto(this.getelementid("graphbar"),this.percentage,20);
    //var votebarobj = this.getelement("graphbar");
    //if (votebarobj) votebarobj.style.width = this.percentage+"%";
    var votepercentobj = this.getelement("percent");
    if (votepercentobj) votepercentobj.innerHTML = this.percentage;
  }
  
  this.setpercentage = function(percentage) {
     this.percentage = percentage;
     this.updategraph();
  }
}

function slidebarto(id,targetpercentage,steps) {
  var votegraphbar = document.getElementById(id);
  if (votegraphbar) {
    //votegraphbar.style.width = this.percentage+"%";
    //return;
    var currentwidth = getElementWidth(votegraphbar);
    var container = votegraphbar.parentNode;
    if (container) {
      var containerwidth = getElementWidth(container);
      var currentpercentage = Math.floor((currentwidth/containerwidth)*100);
      var percentagechange = targetpercentage-currentpercentage;
      var changethisstep = Math.ceil(percentagechange/steps);
      var newwidth = Math.floor(currentpercentage+changethisstep);
      if ((changethisstep>0 && newwidth>targetpercentage) || (changethisstep<0 && newwidth<targetpercentage))  newwidth=targetpercentage;
      if (Math.abs(percentagechange)>0) {
        votegraphbar.style.width = newwidth+"%";
        steps--;
        if (steps>0) {
          setTimeout("slidebarto('"+id+"',"+targetpercentage+","+steps+")",20);
          return;
        }
        writedebug(id+":"+newwidth);
      }
    }
  }
}

function getElementWidth(obj) {
	xPos = obj.offsetWidth;
	return xPos;
}

function btvote(alias) {
  this.alias = alias;
  this.title = "";   
  this.response = null;
  this.options = new Array();  
  this.parent = null;
  this.resultsonly = false;
  this.className = "btvote";   
  this.onchange = null; 
  this.privatevote = false;
  this.responsemessage = "Your vote has been submitted.";
  this.haveresults = false;
  this.currentlevels = null;
  this.submitted = false;
  this.selectedoption = -1;
  this.uid = panels.register(this);    
  this.displayresults = false;
  this.posturl = "../mod/post_vote.php";
  this.closed = false;
  this.starttime = 0;
  this.active = false;
  
  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }

  this.setstarttime = function(starttime) {
	if (this.starttime<starttime ) {
          this.reset();
        }
        this.starttime = starttime;
  }

  this.setstatus = function(status) {
    if (this.active != (status=='active')) {
      this.active = (status=='active');
      this.contentchanged(true);
    }
  }
 
  this.isactive = function() {
    return this.active;
  }

  this.reset = function() {
    	this.submitted=false;
        this.haveresults = false;
	this.contentchanged(true);
  }

  this.setposturl = function(url) {
	this.posturl = url;
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  
 
  this.closevote = function() {
	this.closed = true;
  }
  
  this.addoption = function(alias,text) {  
    var voteoption = new btvoteoption(alias,text);
    voteoption.parent = this;
    this.options[this.options.length] = voteoption;
  }

  this.setsubmitted = function(submitted) {
    this.submitted = submitted;
  }
  
  this.refresh = function() {
	return this.render();
  }
  
  this.clickanswer = function(idx) {
	var radiobutton = this.getelement('radio'+idx);
	radiobutton.checked = true;
    this.selectedoption = idx;
  }
  
  this.submit = function() { 
     if (communication.userid==0) {
       alert('You must be a registered member to take part in this vote');
       this.submitted=true;
       this.showresults(true);
       this.contentchanged(false);
       return;
     }
     if (this.selectedoption < 0) {
		alert("You must choose an option");
		return false;
	 }
	 if (!this.submitted) {
	   var submitform = this.getelement("hiddenframe");
	   if (submitform) {
		  var submiturl = this.posturl+"voteguid="+this.alias+"&optionguid="+this.options[this.selectedoption].alias+
		  	      '&eventguid=' + communication.id +
			      '&viewingid=' + communication.viewingid; 
                  writedebug("submitting vote - "+submiturl);
                  submitform.src = submiturl;
		  this.submitted=true;
		  this.showresults(true);
		  this.contentchanged(false);
	   }
	 }
	 return false;  
  }
  
  this.showresults = function(on) {
	var questionobj = this.getelement('question');
	var resultobj = this.getelement('result');
	var responseobj = this.getelement('responsemessage');	
	if (questionobj) questionobj.style.display = (on?'none':'block');	
	if (resultobj) resultobj.style.display = (!on?'none':'block');	
	if (responseobj) responseobj.style.display = 'block';	
  }

  this.showquestions = function() {
	var questionobj = this.getelement('question');
	var resultobj = this.getelement('result');
	var responseobj = this.getelement('responsemessage');	
	if (questionobj) questionobj.style.display = 'block';	
	if (resultobj) resultobj.style.display = 'none';	
	if (responseobj) responseobj.style.display = 'none';	
  }
  
  this.renderform = function() {
	var out = "<div id=\""+this.getelementid("question")+"\" style=\"display:"+((this.resultsonly && !this.submitted)?"none":"block")+";\">";
	out += "<div class=\"helptext\">Please choose an option below and click 'Submit'.</div>";	
	out += "<div class=\"voteoptions\">";	
	for(var idx=0;idx<this.options.length;idx++) {
		var text = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"options\">";		
		text +="<tr>";
		text +="<td>"+this.options[idx].text+"</td><td width=\"25\"><input type=\"radio\" id=\""+this.getelementid('radio'+idx)+"\" name=\""+this.getelementid('radio')+"\" value=\""+this.options[idx].alias+"\" "+((this.selectedoption==idx)?"checked=\"true\"":"")+"></td>";
		text +="</tr>";	  
		text += "</table>";	  
		out += drawroundedframe('123',text,"callpanel("+this.uid+",'clickanswer("+idx+")');");		  		
	}
        out += "</div>";
	out += drawimagebutton(this.getelementid('submitvote'),"Submit Vote","callpanel("+this.uid+",'submit()')");		
    out += "<iframe id=\""+this.getelementid("hiddenframe")+"\" class=\"debugpostframe\"></iframe>";	
	out += "</div>";
	return out;
  }
  
  this.renderresults = function() {
	var out = "<div id=\""+this.getelementid("result")+"\" class=\"voteresultpanel\">";	
	  if (!this.resultsonly && (communication.userid!=0) && (media.live)) out += "<div id=\""+this.getelementid("responsemessage")+"\" class=\"responsemessage\">"+this.responsemessage+"</div>";
	if (!this.privatevote) {	
		out += "<div id=\""+this.getelementid("graph")+"\" class=\"votegraph\" style=\"display:"+(this.haveresults?"block":"none")+";\">";
	        out += "<div class=\"votegraphs\">";	
		for(var idx=0;idx<this.options.length;idx++) {
                   out += this.options[idx].renderresult();
		}
		out += "</div>";		
		out += "</div>";		
	}	  
	out += "</div>";		
	return out;
  }
  
  this.render = function() {
	var out = "<div class=\"votequestion\">"+this.title+"</div>";	
	if (!this.submitted && !this.resultsonly) {
		out += this.renderform();
	} else {
		out += this.renderresults();
	}
	return out;	  
  }
  
  this.countresults = function() {
	var total = 0;
	for(var idx=0;idx<this.results.length;idx++) total+=this.results[idx];
	return total;
  }
  
  this.setresponsemessage = function(text) {
	  if (text!='') this.responsemessage = text;
	  var responsemessageobj = this.getelement("responsemessage");
	  if (responsemessageobj) responsemessageobj.innerHTML = this.responsemessage;
  }
  
  this.updateresults = function(resultarray) {
    if (resultarray.length==this.options.length) {
      for(var idx=0;idx<this.options.length;idx++) {
        this.options[idx].setpercentage(resultarray[idx]);
      }
      var graphobj = this.getelement("graph");
      if (graphobj) graphobj.style.display = 'block';
      this.haveresults = true;
    }
  }
  
  this.getquestionno = function(letternum) {
    return String.fromCharCode(65+letternum);
  }  
  
  this.contentchanged = function(highliteon) {
	if (this.parent) this.parent.contentchanged(highliteon); 
  } 
}


function btvotes() {	
  this.onchange = null;
  this.title = "vote";
  this.votelist = new Array();
  this.displayedvote = null;
  this.className = "btvotes"; 
  this.optnumformat = 0;
  this.parent = null;  
  this.novotemessage = "There is no active vote at this time.";
  this.uid = panels.register(this);    
  this.updateurl = false;
  this.updateperiod = 5000;
  this.updatetimeout = null;

  this.getelementid = function(name) {
	return this.className+this.uid+name;
  }
  
  this.getelement = function(name) {
	return document.getElementById(this.getelementid(name));  
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  

  this.setupdateurl = function(updateurl) {
	this.updateurl = updateurl;
	if (this.updateurl) this.updatepoll();
  }

  this.updatepoll = function() {
	if (this.updateurl && this.updateperiod>0) {
		refreshscript(this.getelementid("pollscript"),this.updateurl+"?"+Math.random());
		this.updatetimeout = setTimeout("callpanel("+this.uid+",'updatepoll()')",this.updateperiod); 
        return;
	} 
	clearTimeout(this.updatetimeout);
	this.updatetimeout = null;
  }
  
  this.addvote = function(vote) {
	if (this.voteexists(vote.alias)) return false;
	vote.parent = this;
	this.votelist[this.votelist.length] = vote;
        if (!media.live) {
          vote.submitted = true;
          vote.setstatus('active');
          if (this.displayedvote==null) this.displayedvote=vote;
        }
	this.contentchanged();
	return vote;
  }
 
  this.findvote = function(alias) {
	for (var idx=0;idx<this.votelist.length;idx++) {
       if (this.votelist[idx].alias==alias) return this.votelist[idx];
    }
	return null;
  } 
  
  this.getvoteindex = function(voteobj) {
	for (var idx=0;idx<this.votelist.length;idx++) {
       if (this.votelist[idx]==voteobj) return idx;
    }
	return null;	  
  }
  
  this.voteexists = function(alias) {
	for (var idx=0;idx<this.votelist.length;idx++) {
       if (this.votelist[idx].alias==alias) return true;
    }
	return false;
  }      
  
  this.show = function(alias) {
	vote = this.findvote(alias);
	if (vote) {
	  this.displayedvote = vote;
	  this.contentchanged(); 	  
	}
  }
  
  this.hide = function() {
	this.displayedvote = null;
	this.contentchanged(); 	
  }
  
  this.refresh = function() {
        if (media.live) {
          this.displayedvote = this.getactivevote();
        }
        return this.render();
  }

  this.getactivevote = function() {
	for (var idx=0;idx<this.votelist.length;idx++) {
		if (this.votelist[idx].isactive()) return this.votelist[idx];
	}
	return null;
  }
  
  this.movevote = function(amount) {
	var votecount = this.votelist.length;
	var currentvoteidx = this.getvoteindex(this.displayedvote);
	var newvoteindex = currentvoteidx+amount;
	if (newvoteindex<0) newvoteindex=0;
	if (newvoteindex>=votecount) newvoteindex=votecount-1;
	this.displayedvote = this.votelist[newvoteindex];
	this.contentchanged(true);
  }
  
  this.updatenavigation = function() {
        if (!media.live) {
	  var votecount = this.votelist.length;
	  var currentvoteidx = this.getvoteindex(this.displayedvote);	
	  var navigationobj = this.getelement("navigation");	  
	  var navpreviousobj = this.getelement("navprevious");
	  var navnextobj = this.getelement("navnext");
	  var navtextobj = this.getelement("navtext");	
	  if (navigationobj) navigationobj.style.display=((votecount<=1)?'none':'block');
	  if (navnextobj) navnextobj.style.visibility=(currentvoteidx>=(votecount-1))?'hidden':'visible';
	  if (navpreviousobj) navpreviousobj.style.visibility=(currentvoteidx==0)?'hidden':'visible';
	  if (navtextobj) navtextobj.innerHTML="&nbsp;"+(currentvoteidx+1)+" of "+votecount+"&nbsp;";	
        }
  }

  this.getcurrentvotenumber = function() {
    return this.getvoteindex(this.displayedvote)+1;
  }
  
  this.next = function() {
    this.movevote(1);  
  }
  
  this.previous = function() {
	this.movevote(-1);  
  }
  
  this.render = function() {
    var out = "<div class=\"votespanel\" id=\""+this.getelementid('votes')+"\">";		  
    out += (this.title!="")?"<h1>"+this.title+"</h1>":"";
    out += "<div id=\""+this.getelementid("votearea")+"\" class=\"votearea\" >";
    if (this.displayedvote) {
      out += this.displayedvote.render();
	} else {
	  out += "<div class=\"votequestion\">"+this.novotemessage+"</div>";
	}
	out += "</div>";
        if (!media.live) {
	  out += "<div id=\""+this.getelementid("navigation")+"\" class=\"navigation\" style=\"display:"+((this.votelist.length>1)?"block":"none")+";\">";
          out += "<img align=\"absmiddle\" src=\""+imagepath+"previoussmall.gif\" onclick=\"callpanel("+this.uid+",'previous()');\" id=\""+this.getelementid("navprevious")+"\"/>";
          out += "<span id=\""+this.getelementid("navtext")+"\"></span>";
          out += "<img align=\"absmiddle\" src=\""+imagepath+"nextsmall.gif\" onclick=\"callpanel("+this.uid+",'next()');\" id=\""+this.getelementid("navnext")+"\"/>";
          out += "</div>";
        }
	out += "</div>";
	return out;
  }
  
  this.contentchanged = function(highliteon) {
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
        this.updatenavigation();
  } 
}

function bttext() {
  this.onchange = null;	
  this.content=null;	
  this.className = "bttext";   
  this.uid = panels.register(this);      
  this.panelid = "text"+this.uid;

  this.getelementid = function(name) {
        return this.className+this.uid+name;
  }

  this.getelement = function(name) {
        return document.getElementById(this.getelementid(name));
  }

  this.settitle = function(text) {
        this.title = text;
        var titleobj = this.getelement("title");
        if (titleobj) titleobj.value = this.title;
  }  

  this.setcontent = function(content) {
	this.content = content;   
  }
	
  this.render = function() {
	return "<div id =\""+this.panelid+"\" class=\"textpanel\">"+this.content+"</div>";
  }
  
  this.refresh = function() {
  
  }  
  
  this.contentchanged = function(highliteon) {
	if (this.parentobject) this.parentobject.contentchanged(highliteon); 
  } 
}

function setStyle(obj, property, value) { 
  if (!obj) return;
  if (!obj.style) return;
  var styleObj = obj.style;
  //if (!styleObj[property]) return;
  //if (styleObj) styleObj[property] = value;
  try {
    eval("obj.style."+property+"=value");
  }
  catch(e) {
  }
} 

function formatms(timeseconds) {
  var totalseconds = Math.floor(timeseconds);
  if (timeseconds >0) {
    hours = ((totalseconds/3600)>1)?Math.floor(totalseconds/3600)+":":"";;
    minutes = padstring(Math.floor((totalseconds%3600)/60));
    seconds = padstring(Math.floor(totalseconds%60));
    return hours + minutes + ":" + seconds;
  }
  return "00:00";
}

function padstring(instring) {
  if (instring.slice) {
    return ('00' + instring).slice(-2);
  } else {
    instring = '' + instring;
    while (instring.length < 2) {
      instring = '0' + instring;
    }
    return instring;
  }
}

function goURL(daURL) {
    if(window.location.replace) {
	window.location.replace(daURL);
    } else {
	window.location = daURL;
    }
    return;
}

function openFeatureWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName);
  document.MM_returnValue = false;
}

function openPopWinOnce(windowname, theURL, winwidth, winheight){
  if (!getcookie(windowname+"pop")) {
    var winleft = (screen.width-winwidth)/2;
    var wintop = (screen.height-winheight)/2;
    features = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,left='+winleft+',top='+wintop+',width='+winwidth+',height='+winheight;
    window.open(theURL,windowname,features);
    setcookie(windowname+"pop","1",1);
  }
}

function getexpirydate( nodays){
  var UTCstring;
  Today = new Date();
  nomilli=Date.parse(Today);
  Today.setTime(nomilli+nodays*24*60*60*1000);
  UTCstring = Today.toUTCString();
  return UTCstring;
}

function setcookie(name,value,duration){
  document.cookie = name+"="+escape(value)+";EXPIRES="+getexpirydate(duration);
}

function getcookie(name) {
  var oCookies = document.cookie;
  var index = oCookies.indexOf(name + "=");
  if (index == -1) return null;
  index = oCookies.indexOf("=", index) + 1;
  var endstr = oCookies.indexOf(";", index);
  if (endstr == -1) endstr = oCookies.length; // last character
  return unescape(oCookies.substring(index, endstr));
}

function resetform(formname) {
  formObj = document.getElementById("form"+formname);
  if (formObj) formObj.reset();
}

function refreshscript(scriptid,filepath){
  var scriptTag = document.getElementById(scriptid);
  if (scriptTag) { 
    scriptTag.src = filepath;
    return;
  }
  var head = document.getElementsByTagName('head').item(0)
  script = document.createElement('script');
  script.src = filepath;
  script.type = 'text/javascript';
  script.id = scriptid;
  head.appendChild(script);
}

function writepanelcontent(panelid,htmlcontent) {
  panelObj = document.getElementById(panelid);
  if (panelObj) {
    panelObj.innerHTML = htmlcontent;
  }
}

function setInnerHTML(id,html) {
  var obj = document.getElementById(id);
  if (obj) obj.innerHTML = html;
}

function displayobject(obj,show) {
  if (obj) {
	obj.style.display=(show)?'block':'none';
  }	  
}

function setslidebyindex(index) {
  if (slides) {
	if (slides.showbyindex) slides.showbyindex(index);
  }
}	

function pagerefresh() {
    window.location.href = unescape(window.location.pathname);
}

function loadpage(url) {
	window.location.href = url;
}



function handlescriptcommand(sType,sParam) {
  //if (!media.live) return;
  req = new String(sParam);
  pos = req.indexOf(" ");
  com = req.substring(0, pos);
  com = com.toLowerCase();
  arg = req.substring(pos+1, req.length);
  writedebug("Script command : "+sType+" - "+sParam+" - "+arg);
  switch(com) {
	case "slide" :
		slides.show(arg);
	break;

	case "slideindex" :
		setslidebyindex(parseInt(arg,10));
	break;	

	case "tabshow" :
		if (tabs) tabs.show(arg);
	break;
	
	case "tabhighlight" :
		if (tabs) tabs.highlite(arg,true);
	break;
	
	case "tabhighlightoff" :
		if (tabs) tabs.highlite(arg,false);
	break;	
	
	case "closewindow" :
		window.close();
	break;
	
	case "refresh" :
		pagerefresh();
	break;
	
	case "url" :
		pageload(url);
	break;
	
    default:
		writedebug("Ignored ("+sType+") : " + " " + sParam);
	break;
  }
}

function loadheader() {
  return;
  switch(media.mediatype) {
    case "WIMP" : 
	  document.writeln("<scr"+"ipt type=\"text/javascript\" src=\""+scriptpath+"/mswimp.js\"></scr"+"ipt>");
	break;
    case "QUICKTIME" : 	
      document.writeln("<scr"+"ipt type=\"text/javascript\" src=\""+scriptpath+"/quicktime.js\"></scr"+"ipt>");					
    break;
	case "REAL" :
      document.writeln("<scr"+"ipt type=\"text/javascript\" src=\""+scriptpath+"/real.js\"></scr"+"ipt>");		
    break;
	case "STREAMLESS" :
      document.writeln("<scr"+"ipt type=\"text/javascript\" src=\""+scriptpath+"/streamless.js\"></scr"+"ipt>");		
	break;
	default :
	  alert("Unsupported Media Format");
	break;
  }
  document.title = (communication)?communication.title:"BrightTALK Communication"; 
}

function sendtimeupdates() {
  media.recordplayedtime();
  setTimeout("sendtimeupdates()", 10000);
}

function checkctrlkeys(e) {
	var keyevent = (window.event)?window.event:e; 
	if (keyevent.shiftKey  && keyevent.ctrlKey) {
		var keycode = (window.event)?keyevent.keyCode:keyevent.which-64;
		switch(keycode) {
			case 20 : if (tabs) tabs.nexttab();break;		
			case 24 : if (window.runtestcode) runtestcode(); break;			
			case 25 : toggledebug();break;
		}
	}
}

function initialise() {
  if (browserdata) {
    var d = new Date();
    var imgobj = new Image;  
    imgobj.src = ("../mod/update_time.php?viewID="+communication.viewingid+"&"+browserdata+"&t="+d.getTime());  
  }
  communication.pollforupdates();
  sendtimeupdates();
  slides.preload();
  document.onkeypress = checkctrlkeys;
  initialised = true;
}

window.onload=initialise;
window.onbeforeunload=media.recordplayedtime;
