
// GA_UTIL_CLASS is a container for GeneAssist Utility functions

var GA_UTIL_CLASS = Class.create();
//*--- Main ---*
GA_UTIL_CLASS.prototype = {
  
  // The constructor for this class:
  initialize: function() {
    
    // This hash will hold JSONP style AJAX callbacks:
    this.callbacks = $H({});
    
    // This counter will help ensure that all getUID() results are unique:
    this.UIDsuffix = 0;
  },
    
  // This function returns the value of an URL parameter:
  getURLParam: function(name)
  {
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;
    var results = regex.exec( tmpURL );
    if( results == null )
      return "";
    else
      return results[1];
  },
  
  // A function to retrieve a cookie value:
  getCookieVal: function(cookieName)
  {
    var nameEQ = cookieName + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
      {
        var result = c.substring(nameEQ.length,c.length);
        return unescape(result);
      }
    }
    return null; // if not found
  },
  
  // A function to set a persistent cookie (helps on IE?)
  setCookieVal: function(cookieName, cookieVal, quantity, time_unit) {
  
    var expire_date = new Date ();
   
    if (quantity == null)   quantity = 1;
    if (time_unit == null)  time_unit = 'days';

    switch (time_unit.toLowerCase()) {
      case "years":
        var year = expire_date.getYear();
        // Note some browsers give only the years since 1900, and some since 0.
        if (year < 1000) year = year + 1900;
        expire_date.setYear(year + quantity);
        break;
      case "months":
        expire_date.setMonth(expire_date.getMonth() + quantity);
        break;
      case "days":
        expire_date.setDate(expire_date.getDate() + quantity);
        break;
      case "hours":
        expire_date.setHours(expire_date.getHours() + quantity);
        break;
      case "minutes":
        expire_date.setMinutes(expire_date.getMinutes() + quantity);
        break;
      default:
        alert ("Invalid time_unit for setCookie():"+unit);
        break;
    }
    
    document.cookie = escape(cookieName ) + "=" + escape(cookieVal) +
                     "; expires=" + expire_date.toGMTString() + "; path=/";
  },
  
  // The following method uses JSON-P for AJAX calls.
  // The server must support JSON-P!
  jsonPRequest: function(url, params, callback)
  {
    // Create a self-destructing callback to be called by the AJAX result:
    var uid = this.getUID();//(new Date()).getTime();
    
    this.callbacks[uid] = function(my_data){
      delete this.callbacks[uid];
      if (callback != null) callback(my_data);
    }.bind(this);
    
    // Tack on JSON-P padding to call the callback upon loading:
    var jsonp = 'jsonp='+encodeURIComponent('GA_UTIL.callbacks['+uid+']');
    params += '&'+jsonp;
    
    // Create the script tag which fetches the JSON:
    var node = document.createElement('SCRIPT');
    node.type = 'text/javascript';
    node.src = url + '?' + params;

    var head = document.getElementsByTagName('HEAD')[0];
    head.appendChild(node);
  },
  
  // The following method loads and executes a javascript:
  loadJavascript: function(filenames, callback)
  {
    // If there's no file to load, just call the callback
    if (filenames.size() == 0)
    {
      if (callback !== null)
      {
        return callback();
      }
    }
    // In production, this js_loader/bundler may be great for performance:
    if (!this.debug)
    {
      // Since js_loader runs from /shared/lib, prepend ../ to each filename (HACK!):
      var altered_filenames = $A(filenames).collect(function(filename){
          return '../'+filename;
      });
      var filenames_json = "files="+$A(altered_filenames).toJSON();
      return this.jsonPRequest('../shared/lib/js_loader.php', filenames_json, callback);
    }
    else
    {
      // In development, load the files one at a time, for ease of debugging:
      var filename = filenames.shift();// get the first script
      //filename += '?'+GA_UTIL.getUID();// thwart cache // Nah, disable cache in Developer in FF

      // append the script to the page:
      document.getElementsByTagName("head")[0].appendChild(
        new Element("script", { src: filename, type: "text/javascript", language: "javascript" })
      );
      
      //Load the remaining file(s) after a slight delay (to promote order):
      if (filenames.length > 0) {
        this.loadJavascript.bind(this).delay(0.2,filenames, callback);
      } else {
        if (callback) callback();// no more files? call the callback
      }
    }
  },
  
  // An UID generator based on seconds-since-epoch:
  getUID: function(prefix)
  {
    if (prefix == null)
      prefix = '';
    // Keep a counter in case we get >1 request within a Date.now() value:
    this.UIDsuffix += 1;
    // Removed to allow more then 10 UIDs to be generated upon getUID request. tylermb -02/27/09
    // if (this.UIDsuffix > 9) this.UIDsuffix = 0; // Keep it single-digit
    var seconds = ''+Number(new Date());
    
    return (prefix + seconds + this.UIDsuffix); 
  },
  
  // This is a simple string obfuscation function:
  obfuscate_string: function(in_str) 
  {
    var coded_str = escape(in_str);
    var num_out = "";
    for(i = 0; i < coded_str.length; i++) {
    num_out += coded_str.charCodeAt(i) - 23;
    }
    
    return num_out;
  },

  // This is the reverse of the obfuscation function:
  un_obfuscate_string: function(in_str) 
  {
    var str_out = "";
    for(i = 0; i < in_str.length; i += 2) {
    num_in = parseInt(in_str.substr(i,[2])) + 23;
    num_in = unescape('%' + num_in.toString(16));
    str_out += num_in;
    }
    return unescape(str_out);
  },
  
  get_script_path: function(script_name)
  {
    var reg_exp = new RegExp(script_name);
    var myScript = null;
    $$('script').each(function(script){
      if (script.src.match(reg_exp)) 
      {
        myScript = script.src;
      }
    });
    return myScript; // If not found
  },
  
  show_lightbox: function(content, callback) {
    var lightbox_html = '<div class="ga_lightbox_content">'+content+'</div>'+
    '<div class="ga_lightbox_shadow"></div>';
     var container = $div({id:"ga_lightbox"});
    
    document.body.appendChild(container);
    container.innerHTML = lightbox_html;
    
    // Save this callback and let's have the hide function call it:
    this.lightbox_callback = callback;
  },

  show_lightbox_at: function(v, h, content, callback) {
	//DL added 2/18/09 - to allow positioning the lightbox as needed.
	var style = 'style="', bStyle = false;
	if (v) {
		style += 'top:' + v + ';';
		bStyle = true;
	}
	if (h) {
		style += 'left:' + h + ';';
		bStyle = true;
	}
	if (bStyle){
		style += '"';
	} else {
		style = '';
	}
	
    var lightbox_html = '<div class="ga_lightbox_content" ' + style + '>'+content+'</div>'+
    '<div class="ga_lightbox_shadow"></div>';
     var container = $div({id:"ga_lightbox"});
    
    document.body.appendChild(container);
    container.innerHTML = lightbox_html;
    
    // Save this callback and let's have the hide function call it:
    this.lightbox_callback = callback;
  },
	  
  hide_lightbox: function() {
    if ($("ga_lightbox") != null) $("ga_lightbox").remove();
    if (this.lightbox_callback != null) {
      this.lightbox_callback();
      this.lightbox_callback = null;
    }
  }
  
};

// Create an instance of the class, to be used wherever...
GA_UTIL = new GA_UTIL_CLASS();
