// <?php

/**
  * @package javascript
  * Contains both the pbloader functions and the teabag xhr object.  To use the
  * loader call the loadpackage function with whatever package you want.
  *
  * loadpackage('swfupload');
  *
*/

if (! PBLOADER) {
  var PBLOADER = 1;

/**
  * Just a faster getElementById call
  */
function getE(elementName) {
  element = document.getElementById(elementName);
  return element;
}

/**
  * Loads a js or css file via XHR and/or appending HEAD tags
  * @param string filename Relative URL of file to load
  * @param string filetype Either js or css for filetype
  */
function loadjscssfile(filename, filetype) {
  if (filetype == "js"){ // if filename is a external JavaScript file
    /*
      We are going to use a syncronous call, little bit dangerous but should
      be fine.  Grab the .js file throw a <script> tag around it and parse it
    */
  
    try {
      loaderXHR = new teabag();
      loaderXHR.parseJS = false; // Doing it manually
      loaderXHR.async = false;   // Have to wait because there is code needing this
      loaderXHR.url = filename;
      loaderXHR.run();
      if (loaderXHR.response) {
        /*
          causes errors for js files with <script> tags in them - don't think this is needed anyway
        */
        //loaderXHR.parse_javascript('<' + 'script type="text/javascript">' + loaderXHR.response + '<' + '/script>');
        var oScript = document.createElement('script');
        oScript.text = loaderXHR.response;
        document.getElementsByTagName("head").item(0).appendChild(oScript);
      }
    } catch (e) {
      //Load via append
      alert('appending' + filename);
      var fileref = document.createElement('script')
      fileref.setAttribute("type","text/javascript")
      fileref.setAttribute("src", filename)
      document.getElementsByTagName("head")[0].appendChild(fileref);
    }

  } else if (filetype=="css"){
    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);
    document.getElementsByTagName("head")[0].appendChild(fileref);
  }
}

var filesadded = "" //list of files already added

/*
  Used for loading specific files i.e. if there isn't a package defined
*/
function loadfile(filename, filetype) {

  if (filesadded.indexOf("["+filename+"]") == -1) {
    loadjscssfile(filename, filetype)
    filesadded += "[" + filename + "]" //List of files added in the form "[filename1],[filename2],etc"
  }
}

var packagesloaded ="" //list of files already added

/**
  * Load a JavaScript package but only one time per document
  * Your choices are lightbox, teabag (loaded on default), transitions,
  * swfupload, checkbox_width, multifile, initializeme
  *
  * @author Dustin Butler <dustin@intrcomm.net>
  * @param package What package do you want to load
  */
function loadpackage(package) {
  var debug = {
    "js" : ['/pb/lib/js/debug.js'],
    "css" : []
  };

  var lightbox = {
    "js" : ['/pb/lib/lightbox/lightbox.js'],
    "css" : ['/pb/lib/lightbox/lightbox.css']
  };

  var teabag = {
    "js" : ['/pb/lib/teabag/teabag.js'],
    "css" : []
  };

  var transitions = {
    "js" : ['/pb/lib/js/transitions.js'],
    "css" : []
  };


  var swfupload = {
    "js" : ['/pb/lib/swfupload/2.5.0/swfupload_fp10/swfupload.js','/pb/lib/swfupload/handlers.js'],
    "css" : []
  };

  var set_checkbox_width = {
    "js" : ['/pb/lib/js/set_checkbox_width.js'],
    "css" : []
  };

   var multifile = {
    "js" : ['/pb/lib/js/multifile.js'],
    "css" : []
  };

  var initializeme = {
    "js" : ['/pb/lib/js/initializeMe.js'],
    "css" : []
  };

  var dojo_file_list = {
    "js" : ['/pb/lib/js/dojo_file_list.js'],
    "css" : []
  };

  var ckeditor = {
    "js" : ['/pb/lib/ckeditor/ckeditor.js'],
    "css" : []
  };

  if (packagesloaded.indexOf("[" + package + "]") == -1) {

    eval("loadme = " + package + ";");
    for (i=0; i<loadme.js.length; i++) {
      loadjscssfile(loadme.js[i], 'js');
    }
    for (i=0; i<loadme.css.length; i++) {
      loadjscssfile(loadme.css[i], 'css');
    }
    packagesloaded += "[" + package + "]"; //List of packages already loaded in the form "[filename1],[filename2],etc"
  }
}


/**
  * teabag AJAX object used for making XHR calls WITHOUT Dojo.  The idea here
  * is to provide a simple un-obfusicated method for XHR callbacks as a base.
  *
  * Based on SACK (Simple AJAX Code-Kit)
  * �2005 Gregory Wild-Smith
  * www.twilightuniverse.com
  *
  * Difference between GET and POST
  *
  * GET sends the params i.e. ?var=value&foo=bar as part of the URL and sends
  * null in the open method.  POST params in the open method
  *
*/
function teabag () {
	this.xmlhttp = null;
  this.url = null;            // URL to call may have GET vars on it
  this.async = true;
  this.setElement = null;     // Automatically set innerHTML in this element
  this.querystring = null;    // Store name=value&foo=bar
  this.parseJS = true;        // Parse the javascript returned by XHR
  this.loading = null;        // innerHTML to apply before loading
  this.method = 'GET';        // Default to GET method
  this.vars = new Object();   // Store param name=>value pairs
  this.encode = false;        // Should we encode the value part of name=value?
  this.responseStatus = new Array(2);

  // Store a name=>value pair and if it's marked as encoded
	this.setVar = function(name, value, encoded){
    if (encoded == undefined) {
      encoded = false;
    }
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value) {
    // Don't think we need to encode names ever
		this.vars[name] = Array(encodeURIComponent(value), true);

	}

  /*
    Can we determine is the URL string is encoded or not?  How about looking
    for a % char which is usually an indication.

    This takes an existing URL string and processes it into our this.vars
    object name=>value pairs
  */
	this.processURLString = function(string, encode) {
    if (encode == undefined) {
      encode = false;
    }

    // Separated by & or an encoded &
		encoded = encodeURIComponent('&');
		regexp = new RegExp("&|" + 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]);
			}
		}
	}

  /*
    Makes a URL string from our parameters that have been set
  */
	this.createURLString = function() {

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

    // Do one pass and encode any vars
    if (this.encode) {
      for (key in this.vars) {
        if (! $this.vars[key][1]) {
          this.encVar(key, this.vars[key][0]);
        }
      }
    }

    // Put all the vars together with = and join with &
		tmp = new Array();
		for (key in this.vars) {
      tmp[tmp.length] = key + '=' + this.vars[key][0];
		}

    this.querystring = tmp.join('&');
    return this.querystring;
	}

  this.run = function() {
    // This errors in IE, not sure what it's for anyway.
    //self = this;

    // Show that something is loading
    if (this.setElement && this.loading) {
      document.getElementById(this.setElement).innerHTML = this.loading;
    }

    this.createURLString();


    if (this.method == 'GET') {
      if (this.url.indexOf('?') != -1) {
        request = this.url + '&' + this.querystring;
      } else {
        request = this.url + '?' + this.querystring;
      }
      this.xmlhttp.open('GET', request, this.async);
    } else {
      this.xmlhttp.open('POST', this.url, this.async);
      this.xmlhttp.setRequestHeader("Content-length", this.querystring.length);
      this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    }
    this.xmlhttp.setRequestHeader("Connection", "close");

    var self = this;
    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.setElement) {
            self.elementObj = document.getElementById(self.setElement);
					  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(self.response);
					} else {
					  self.onError();
					}

          if (self.parseJS) {
            self.parse_javascript(self.response);
          }

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

    if (this.method == 'POST') {
      self.xmlhttp.send(this.parameters);
    } else {
      this.xmlhttp.send(null);
    }

    //  We've been waiting for this text haha non async
    if (! this.async) {
      this.response = this.xmlhttp.responseText;
    }
  };

  this.parse_javascript =  function(content) {
    var search = content;
    var script;

    while( script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i)) {
      search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);

      if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break;

      block = search.substr(0, search.indexOf(RegExp.$1));

      search = search.substring(block.length + RegExp.$1.length);

      var oScript = document.createElement('script');
      oScript.text = block;

      document.getElementsByTagName("head").item(0).appendChild(oScript);
    }
  };

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

  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.url = null;            // URL to call may have GET vars on it
    this.async = true;
    this.setElement = null;     // Automatically set innerHTML in this element
    this.querystring = null;
    this.parseJS = true;        // Parse the javascript returned by XHR
    this.loading = null;        // innerHTML to apply before loading
    this.method = 'GET';        // Default to GET method
    this.vars = new Object();   // Store param name=>value pairs
  };


  this.createAJAX = function() {
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
      this.xmlhttp = new window.XMLHttpRequest();
      if (this.xmlhttp.overrideMimeType) {
        // set type accordingly to anticipated content type
        //file_uploadXHR.overrideMimeType('text/xml');
        this.xmlhttp.overrideMimeType('text/html');
      }
    } else if (window.ActiveXObject) { // IE
      try {
        this.xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
      } catch(e) {
        try {
          this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          try {
            this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
        }
      }
    }
    if (! this.xmlhttp) {
      this.failed = true;
      return false;
    }
  };

	this.resetAll();
	this.createAJAX();
}

}
