/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* �2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {

		var xmlhttp=false;
 
		try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
		xmlhttp = false;
		}
		}
		
		if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
			try {
				xmlhttp = new XMLHttpRequest();
			} catch (e) {
				this.failed = true;
			}
		}
		if (!xmlhttp && window.createRequest) {
			try {
				xmlhttp = window.createRequest();
			} catch (e) {
				xmlhttp=false;
			}
		}
		this.xmlhttp = xmlhttp;
		/*try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}*/
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						 this.xmlhttp.overrideMimeType('text/html');
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}


var enableCache = true;
var jsCache = new Array();
var mode=0;
var currentpage=0;

var dynamicContent_ajaxObjects = new Array();

function ajax_showContent(divId,ajaxIndex,url)
{
	document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;
	if(enableCache){
		jsCache[url] = 	dynamicContent_ajaxObjects[ajaxIndex].response;
	}
	dynamicContent_ajaxObjects[ajaxIndex] = false;
}

function ajax_loadContent(divId,url)
{
	if(enableCache && jsCache[url])
	{
		//document.getElementById(divId).innerHTML = "lhafdklakljdklfa alka";
		document.getElementById(divId).innerHTML = jsCache[url];
		return;
	}
	
	var ajaxIndex = dynamicContent_ajaxObjects.length;
	document.getElementById(divId).innerHTML = '<span style="font-size:12pt;text-algin:center;">Loading ...<img src="/_img/loading.gif"></span>';
	dynamicContent_ajaxObjects[ajaxIndex] = new sack();
	dynamicContent_ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
	dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url); };	// Specify function that will be executed after file has been found
	dynamicContent_ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function	
	
	
}
function la(divID,myURL)
{
	Stamp = new Date();
	ajax_loadContent(divID,myURL + '&stamp=' + Stamp.getHours() + '' + Stamp.getMinutes() + '' +  Stamp.getSeconds());
}
function al(divID,URL)
{
		Stamp = new Date();
		
		ajax_loadContent(divID,'/_user/loader.php?module='+URL + '&timestamp=' + Stamp.getHours() + '' + Stamp.getMinutes() + '' +  Stamp.getSeconds());
}

  var http_request = false;
   function makePOSTRequest(url, parameters,fp) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      //http_request.onreadystatechange = alertContents;
      http_request.onreadystatechange = fp;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('middle').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
    function middleContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('panel_body').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   function mylogin(obj) {
      var poststr = "username=" + document.getElementById("username").value +
      				"&password=" + encodeURI( document.getElementById("password").value ) +
          			"&module=auth";
      makePOSTRequest('_user/loader.php', poststr,middleContents);
   }
   
   function get(obj) {
      var poststr = "cid=" + document.getElementById("cid").value +
      				"&cgroup=" + encodeURI( document.getElementById("cgroup").value ) +
      				"&cname=" + encodeURI( document.getElementById("cname").value ) +
                    "&ctext=" + encodeURI( document.getElementById("ctext").value );
      makePOSTRequest('updatepage.php', poststr,alertContents);
   }
   function goto_page(ex,pn,pid)
   {
   			Stamp = new Date();
   			la('pcont','getpage.php?e='+ ex + '&p=' +pid + '&pn=' +pn + '&stamp=' + Stamp.getHours() + '' + Stamp.getMinutes() + '' +  Stamp.getSeconds() );
   			document.getElementById('pageno').innerHTML='Page '+ pn;
   			document.getElementById('page' + currentpage).style.borderBottom="0";
   			document.getElementById('page' + pn).style.borderBottom="5px solid black";
   			currentpage=pn;
	}
	function goto_pager(ex,pn,pid)
   {
   			Stamp = new Date();
   			la('pcont','getpager.php?e='+ ex + '&p=' +pid + '&pn=' +pn + '&stamp=' + Stamp.getHours() + '' + Stamp.getMinutes() + '' +  Stamp.getSeconds() );
   			document.getElementById('pageno').innerHTML='Page '+ pn;
   			document.getElementById('page' + currentpage).style.borderBottom="0";
   			document.getElementById('page' + pn).style.borderBottom="5px solid black";
   			currentpage=pn;
	}
   function goto_sample(g)
   {
   			Stamp = new Date();
   			la('pcont','getpagews.php?g='+ g +'&stamp=' + Stamp.getHours() + '' + Stamp.getMinutes() + '' +  Stamp.getSeconds() );   			
	}

	function select_option(a,b,ex,qn)
	{
				document.getElementById('q' + a + '1').style.background='#FFF';
					document.getElementById('q' + a + '2').style.background='#FFF';
								document.getElementById('q' + a + '3').style.background='#FFF';
										document.getElementById('q' + a + '4').style.background='#FFF';
		document.getElementById('q' + a + '' + b).style.background='#DDD';
					document.getElementById('q' + a + '' + b).style.textDecoration='none';
		la('buffer','answer.php?e=' + ex + '&q=' + a + '&a=' + b + '&qn=' + qn);
		
	}
	function st(a,b)
	{
			if(document.getElementById('q' + a + '' + b).style.textDecoration=='line-through')
			{
				document.getElementById('q' + a + '' + b).style.textDecoration='none';
			}else
			{
				document.getElementById('q' + a + '' + b).style.textDecoration='line-through';
			}
	}
	
var timerID = 0;
var tStart  = null;
var duration = 0;
var wsample=0;
var wsample_page=1;

function UpdateTimer(d) {
   if(timerID) {
      clearTimeout(timerID);
      clockID  = 0;
   }

   if(!tStart)
      tStart   = new Date();

   var   tDate = new Date();
   var   tDiff = tDate.getTime() - tStart.getTime();

   tDate.setTime(tDiff);
 var m = tDate.getMinutes();
 var s = tDate.getSeconds();
 
 m = d - (m + 1);
 s = 60 - s;
 if(m==0 && s==1)
   {
	   	if(wsample==1)
	   	{
	   		if(wsample_page==1)
	   		{   			
	   			location='wsresults.php';
	   		}else
	   		{	   				
	   				goto_sample(currentpage,2);
	   		}   		   		
	   	}else
	   	{
			location='results.php';   			   			
	   	}   	
   }    
   
 if(m < 10)
 {
 	m = '0' + m ;
 }
 if(s < 10)
 {
 	s = '0' + s ;
 }
 document.getElementById('timekeeper').innerHTML = "" 
                                   + m + ":" 
                                   + s;
   timerID = setTimeout("UpdateTimer("+d+")", 1000);
}

function Start(d) {
	duration=d;
   tStart   = new Date();

   document.getElementById('timekeeper').innerHTML = "" + duration + ":00";

   timerID  = setTimeout("UpdateTimer("+d+")", 1000);
	if(mode==0){ 
	mode=1; 
	document.getElementById('startexam').innerHTML = "Finish (submit exam)";
	//goto_page(a,b,c);	
	}
	
}

function Startws(g,num,d) {
	duration = d;
   tStart   = new Date();

      document.getElementById('timekeeper').innerHTML = "Time Left " + duration + ":00";

   timerID  = setTimeout("UpdateTimer("+d+")", 1000);
	if(mode==0){ 
	mode=1; 
	document.getElementById('startexam').innerHTML = "";
		goto_sample(g);
	}else { 
		location='submitessay.php';	
	}
	
}

function Stop() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }

   tStart = null;
}

function Reset() {
   tStart = null;

   document.getElementById('timekeeper').innerHTML = "Exam Duration  00:00";
}

	function gofullscreen(URL,num)
		{
			window1=window.open(URL,"FS"+num,"scrollbars=Yes,width=700,height=500,status=yes,fullscreen=yes").focus();
		}
		function gopopup(URL,num,w,h)
		{
			window1=window.open(URL,"FS"+num,"scrollbars=Yes,pageXoffset=0,pageYoffset=0,width="+w+",height="+h+",status=no").focus();
		}
		function goexams(num,dur,check)
	{	
		if (check!=4)
		{
			window1=window.open("http://www.mcat-prep.com/oldmcat/viewexam.php?examID="+num+"&duration="+dur,"examwindows"+num,"scrollbars=Yes,width=700,height=500,status=yes,fullscreen=yes").focus();
		}else
		{
			window1=window.open("http://www.mcat-prep.com/oldmcat/wsexam.php?examID="+num+"&duration="+dur,"examwindows"+num,"scrollbars=Yes,width=700,height=500,status=yes,fullscreen=yes").focus();
		}
	}
	function gocbt(examID,examtype,dur,g)
	{			
		document.getElementById('panel_body').innerHTML='';
		if(examtype==1)
		{
			la('panel_body','cbt.php?e='+examID + '&d=' + dur + '&g=' + g + '&examtype=' + examtype);
		}else
		{
			la('panel_body','wsample.php?e='+examID + '&d=' + dur + '&g=' + g + '&examtype=' + examtype);
				
		}
		
		initSlideLeftPanel(false,'dhtmlgoodies_leftPanel');	
		check_selection();	
	}
	function gocbtr(examID,examtype,dur,g)
	{			
		
			la('panel_body','cbtr.php?e='+examID + '&d=' + dur + '&g=' + g + '&examtype=' + examtype);		
			initSlideLeftPanel(false,'dhtmlgoodies_leftPanel');	
			//check_selection();	
	}
	function gocbtws(examID,nextexam,dur,g)
	{			
		document.getElementById('panel_body').innerHTML='';
		
			la('panel_body','wsample.php?e='+examID + '&d=' + dur + '&g=' + g + '&nextexam=' + nextexam);								
		initSlideLeftPanel(false,'dhtmlgoodies_leftPanel');		
	}
	function load_exams(num)
	{	
		la('lexams','listexams.php?examID='+num);
		document.getElementById('lpages').innerHTML='';
		document.getElementById('lquestions').innerHTML='';
	}
	function load_pages(num)
	{	
		la('lpages','listpages.php?examID='+num);		
		document.getElementById('lquestions').innerHTML='';
		
	}
	function load_questions(num)
	{	
		la('lquestions','listquestion.php?pageno='+num);
		
	}
	
	function submit_essay()
	{		
		essay =  encodeURI(document.getElementById('essaybox').value);		
		location = 'submitessay.php?essay=' + essay;
				
	}

	function show_pt()
	{
		win=window.open("http://www.mcat-prep.com/admin/images/pTable.gif","pt","scrollbars=Yes,width=700,height=500,status=yes").focus();
	}
	function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
	function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
	var down=0;
	var lastselection="";
	function check_selection()
	{
	 
	  if(window.getSelection()!='')	  
	  {	
	  		if(lastselection!=window.getSelection())
	  		{
	  			overlib(window.getSelection(),FIXX, 400,FIXY, 200,BGCOLOR,'white',FGCOLOR,'YELLOW',STICKY);
	  		}
	  		lastselection= window.getSelection() + '';
	  }else{
	  	if(lastselection!='')
	  	{
	  		highlight(lastselection);
		}
	 	nd(); 
	}	  	
	  //lastsearch=window.getSelection();		
	  setTimeout("check_selection()", 500);	
	}
