/**
* @fileoverview

*
* This file contains all the more interesting functions supporting the "onramp" page for 

* Beyond  Reader.
*/


/**

* This function does an animated height transition.  It is written so that the change in height is linear.

* In other words, I don't think it slowly reduces its speed.  But I don't care.

*

* @param   targetElement  The element whose height should be modified.

* @param   newHeight         The new height the element should eventually grow/shrink to.

* @param   units                    "px" or "em" or whatever.

* @param   endOfTweenFunction  This can be null.  If it is not null, it is the function 

*                                                            that will  be called once the tween has ended.

*/

function doHeightTween ( targetElement, newHeight, units, endOfTweenFunction ) {

   	

	regexp = new RegExp ( "[\-0-9]+" );

	

	currHt = regexp.exec ( targetElement.style.height );

	

 



	var thread2 = new Object ();

	thread2.currHt = Number(currHt);

	thread2.newHt = Number(newHeight);

	if ( thread2.currHt > thread2.newHt ) {

	 thread2.increment = -5;

	} else {

	 thread2.increment = 5;

	}

			      

	thread2.tick = Number(0);

	thread2.totalticks = Number(20);

	thread2.target = targetElement.style;

	



	thread2.prop = "height";

	thread2.id = setInterval ( 

	function () {

	   var remainingDistance = Number(thread2.newHt - thread2.currHt);

	     var elapsedMS = Number(thread2.tick);

	     var msInThisTick =  Number(1); 

	     thread2.tick++;

	     var remainingTime = thread2.totalticks - elapsedMS;

	     var requiredSpeed = (remainingDistance/remainingTime);

	     var extraSpeed = requiredSpeed * (4 * remainingTime)/thread2.totalticks; 

	   var totalSpeed = (requiredSpeed + extraSpeed) * msInThisTick;

	

	       thread2.currHt += totalSpeed;

	     thread2.target[thread2.prop] = thread2.currHt + units;

	     

	   

		  

	

	   if ( thread2.increment < 0 ) {

		   if ( thread2.currHt <= thread2.newHt ) {

		       clearInterval ( thread2.id );

		       if ( endOfTweenFunction ) {

			  endOfTweenFunction ();

		       }

		   }

	   } else {

		   if ( thread2.currHt >= thread2.newHt ) {

		       clearInterval ( thread2.id );

		       if ( endOfTweenFunction ) {

			  endOfTweenFunction ();

		       }

		       

		   }

	   }

	    }  ,  50 ); 

   

 }



/**
* Hashtable with URL query string information.
* This is populated by the parseQueryString() function.
* @type String[]
*/
var gQuery = [];


function getActiveArgs(){
	var noshow = document.getElementById("form_noshow");
	var args;
	
	args = "?platform=" + gQuery['platform'] + "&lang=" + gQuery['lang'] + "&prod_id=" + gQuery['prod_id'] + "&start_meeting=" + gQuery['start_meeting'] + "&go_online=" + gQuery['go_online'] + "&dont_show=" + (noshow.checked ? "1" : "0");
	
	return args;
}

/**
* Parses the URL query string into 
* the global hash variable gQuery
*/
function parseQueryString(){

	var query;

	
	if(document.location.search){
		query = document.location.search.slice(1);


		// Parse the query string
		query = query.split("&");
		for(var i = 0; i < query.length; i++){
			query[i] = query[i].split("=");
			
			// URL decode
			if(query[i].length > 1){
				query[i][1] = query[i][1].replace(/\+/g, " ");
				query[i][1] = unescape(query[i][1]);
			}
			else{
				query[i][1] = true;
			}
			
			gQuery[query[i][0]] = query[i][1];
		}
	}
	
	// "Don't Show" checkbox
	var noshow = document.getElementById("form_noshow");
	if(noshow && gQuery['dont_show'] && gQuery['dont_show'] == 1){
		noshow.checked = true;
	}
	
	var a = document.getElementById("link");
	if (a)
	{
		a.href += getActiveArgs();
	}
}

function goOnlineOrNot(){
	if(gQuery['go_online'] == "1"){ 

	

	   /**

	    * Do this to make the "go online" button be invisible by the time the screen comes up.

	    */

	   var goonlinebutton = document.getElementById ( "goonlinebutton" );

	   goonlinebutton.style.height = "1 px"; 

	   goonlinebutton.style.display="none"; 

	   

	   

	   doConnect (); // Do the connect.
		// go('connecting.html'+ getActiveArgs());
	}

	/*
	else{ 
		//go('go_online.html'+ getActiveArgs());

		go('onramp.html'+ getActiveArgs());
	}

	*/
}


/**
* Send the user to url
* @param {String} url
*/
function go(url){
	document.location.href = url;
}

/**
* Update don't show value
*/
function updateDontShow(){
	var noshow = document.getElementById("form_noshow");
	
	if(noshow.checked) 
		go('DOWNTOWN__DONTSHOW__1'); 
	else 
		go('DOWNTOWN__DONTSHOW__0')
}


/**
* Directs the user to either the remote or static content
*/
var Controller = {
	
	base : "https://readeronline.adobe.com/",
	locale : "en-us",
	request : null,
	
	
	/**
	* Load the xmlHttpRequest object 
	* and sets it to this.request
	* @returns {boolean}
	*/
	getRequestObj : function(){
		
		if(this.request){
			return true;
		}
		
		// IE
		if(window.ActiveXObject){
			try{
				this.request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e){
				try{
					this.request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e){ 
					return false;
				}
			}
		}
		// All other STANDARD browsers
		else {
			this.request = new XMLHttpRequest();
		}
		
		if(this.request){
			return true;
		}
		return false;
	},

	

	/**

	* Listeners for events.  Cheezey but it works.

	*

	* This is a hashtable.  Each key is an event type -- such as "error".  Each item associated

	* with a key is a function into which an event object is passed.  An event object has an "eventType" attribute and

	* may have others as well.

	*/

	listeners :  new Object(),

	

        /**

	* Add a listener for an event.  ONLY 1 per event type please!

	*/

	addEventListener : function ( eventType, listener ) {

	   this.listeners[eventType] = listener;

	},

	

        /**

	* Remove a listener.

	*/

	removeEventListener : function ( eventType, listener ) {

	   if ( this.listeners[eventType] != null ) {

	      delete this.listeners[eventType];

	   }

	},

	

	/**

	* Fire an event to a listener.  The passed-in object is the event object

	* that is sent to the listener function.  The event object should have an 

	* "eventType" property - indicating  which type of event it is and ergo

	* which listener to invoke.

	*/

	fireEvent : function ( eventObject ) {

	   var listener = this.listeners[eventObject.eventType];

	   if ( listener ) {

	      listener(eventObject);

	   }

	},



        /**

	* This exists so that we don't have any mixups such as our internal timer timing out and then

	* showing an error screen but then later an Ajax error occurs so another instance of the error

	* message is shown.  Or worse is: timeout happens, an error message shows, but then the Ajax

	* call succeeds and the screen switches to the "Beyond..." screen!!!

	*

	* So this flag saves the day.

	*/

	erredOut : Boolean = false,


        /**

	* Called if our timeout timer expires.  This basically sets the appropriate flag and fires an event

	* to the listener.  The listener (the onramp.html page's JS) will then do the right thing -- such as

	* show the "error..." message and allow the user to retry accessing the beyond reader content.

	*/

	timeOutAjaxRequest : function () {

	  

	   /**

	    * If the timer expired and no other Ajax errors occured, shut this attempt down and fire an error 

	    * event to the listener.

	    */

	   if ( Controller.erredOut == false ) {

	      Controller.erredOut = true;

	      Controller.request.abort ();

	      Controller.fireEvent ( { eventType:"error", message:"Timed out"  } );

	   }

	},

	

	/**

	* The name of the page to load (usually is "Beyond").  This is set by "startLoadThread" and read by "execLoadMethod".

	* The reason we do this is to provide a smooth user experience where they briefly see the "connecting..." message and are

	* then brought to the beyond reader page.  If we didn't do this, there is a jumpy flashing as the "connect" page switches to

	* the Beyond Reader page in less than 1 second but more than 0 seconds.  By smoothing the transition out, the end user

	* can brethe a sigh of relief.

	*/

	m_pageName : "",

	

	/**

	* See above comment.  This is preferred to callilng "load" directly  (which would result in flashy/jumpyness when the Beyond Reader

	* page is less than 1 second away on the network).

	*/

        startLoadThread : function (pageName) {

	   m_pageName = pageName;

	   setTimeout("Controller.execLoadMethod()", 10000);

	},

	

	/**

	* This is called after the user has seen the "connecting..." message for a second or so.  This method calls "load".  Once "load" is called the

	* Beyond Reader content could show up very quickly.

	*/

	execLoadMethod : function () {

	   Controller.load(m_pageName);

	},

	
	/**
	* Load the page from cache or online content
	* @param {String{ page The name of the page to load
	*/
	load : function(page){

	

	  /**

	   *  Clear the "i got an error" flag.

	   */

	   Controller.erredOut = false;
		

		var url = "";


		// Construct URL
		if(gQuery && gQuery['lang']){
			this.locale = gQuery['lang'];
		}


		url = this.base + this.locale +"/"+ page +"/default.html" + getActiveArgs();
		

		//url = "http://interface/candy/BeyondReader/ENU/Beyond/default2.html";

		

		// Timeout (10 seconds -- was 1.5 seconds, but that isn't enough time.)
		setTimeout("Controller.timeOutAjaxRequest()", 10000);
		

		/**

		* Get the AJAX object.  If it isn't present (which should  never happen) fire an error event back to the onramp.html page.

		*/
		if(this.getRequestObj()){
		
			try{
								
				var req = this.request;
				this.request.onreadystatechange = function() {
					

                                        /**

					* If the state is "4", then either we've downloaded the page into the browser's cache (so when we 

					* do this " document.location.href = url; " the page shows that instant) or we've encountered an 

					* error.  

					*

					* No error corresponds to an HTTP response status of 200.  Note that even if we get a 200 if we

					* previously timed out, the "Controller.erredOut" flag will be "true" and we will have already sent an

					* error event to the onramp.html JS code.  So in that case, we don't assign the downloaded page to the

					* browser.   Instead, we do nada.

					*/
					if(req.readyState == 4){
						if(req.status == 200 && ( Controller.erredOut == false ) ) {
							document.location.href = url;
						} else {

						

						   /**

						    * If we got here, there was an HTTP error.  Now check if we timed out prior to this.  If not,

						    * then it is ok to send an error event to onramp.html's JS code.

						    */

						   if ( Controller.erredOut == false ) {

						        Controller.erredOut = true;

						        Controller.fireEvent ( { eventType:"error", message:"HTTP Error, Status=" + req.status  } );

						   }
							

						}
					}
				};
				

				/**

				* We do a GET here.  What that does is 2 things: 1) it proves our URL exists and the content is there for us;

				* and 2) it downloads the page into the browser's cache.  Then when we execute the following line of JS,

				* the page shows up immediately (without having to be downloaed into the browser):

				*

				*  document.location.href = url;

				*

				* This is the way we download the page "in the background" while the "connecting..." message is showing.

				*/
				this.request.open("GET", url, true ); 
				this.request.send("");
				
			} catch(e){ 

  

                                 /**

			           * We should never get here.  You'd land here if there was some runtime bug that happened while using the AJAX object

			           * or while assigning the URL to the "document.location.href" property.

			           *

				 * Anyhow, if we land here, we'll only report an error to the onramp page's JS in the event that no prior  errors have occured.

			           */

                                if ( Controller.erredOut == false ) {

				   Controller.erredOut = true;

                                   Controller.fireEvent ( { eventType:"error", message:"AJAX Exception: " + e } );

				}
				
			}
			
		}
		else{

		

                    /**

		     * We land here in the unlikely event that there is no AJAX object available for us to use to get the content.

		     */

		    Controller.fireEvent ( { eventType:"error", message:"No AJAX object available" } );
		}
	}
}
