/**
* 
* Helper.js
* 
* Basic Javascript and helpful functions.
* 
* This file should be part of every page's standard include.
*
* Remember to update version history with any new methods or changes.
* 
*******************************************************************************
*  DEPENDANCIES:
*  - jquery.js - sendAjax uses.  Try to limit jQuery in this file.
* 
*******************************************************************************
*  DEPENDANTS:
*  - Login.js
* 
*******************************************************************************
*  VERION HISTORY:
*      v1 - Initial Version.
* 
*/

var Helper = (function (parent) {
   
  /**
   * This is the AJAX success handler for most web services.
   * 
   * Executes a given Javascript method.
   */    
  parent.execJS = function (data) {
    if(data.d) {
      // Used if we are calling a namespaced function such as 'IUAA.ui.displayError'
      var fnPath = data.d.method.split('.'),
          fn;
      
      switch(fnPath.length) {
        case 1:
          fn = window[fnPath[0]];
          break;
        case 2:
          fn = window[fnPath[0]] [fnPath[1]];
          break;
        case 3:
          fn = window[fnPath[0]] [fnPath[1]] [fnPath[2]];
          break;
        case 4:
          fn = window[fnPath[0]] [fnPath[1]] [fnPath[2]] [fnPath[3]];
          break;
      }
      
      // Make sure the callback is actually a function and call it.
      if(typeof(fn) === 'function') {
        if(data.d.parameters) {
          fn(data.d.parameters);
        } else {
          fn();
        }
      }
    }
  };
	
	/**
	*	Force https
	*/
	parent.forceHttps = function() {
		if(window.location.protocol == 'http:') {
			window.location.href = 'https://' +location.host + location.pathname;
		}
	};
  
  /**
   * Refreshes the current page.
   */
  parent.refreshPage = function() {
    location.reload(true);
  };
  
  /**
   * Redirects to a given page on the current domain.
   * 
   * Note: This is not a full redirect, the page parm should
   * be something like "/magazine/index.php".  Not a full URL.
   * 
   * Will there be an issue with only redirection to https?
   */
  parent.redirectToPage = function(page) {
    page = page || '';
    page = page.replace(/%2f/gi, "/");  //%2f will cause problems in the URI.
    document.location = "https://" + document.domain + page;
  };
  
  /**
   * **Depreciating - use getUrlVariable() instead. 
   * 
   *
   * Mimicks PHP's $_GET function for accessing GET vars.
   */
  parent.$_GET = function(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return decodeURIComponent(results[1].replace(/\+/g, " "));
  };  
  
	parent.getUrlVariables = function () { // method to get data from url querystring
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

		for (var i = 0; i < hashes.length; i++)
		{ hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; }

		return vars;
	};

	parent.getUrlVariable = function (name){
		return Helper.getUrlVariables()[name];
	};
	
  /**
   * General wrapper for the .ajax call.
   * 
   * Requires serviceUrl and data.
   */
  parent.sendAjax = function(serviceUrl, data, callback, errorCallback) {
    $.ajax({
      type: "POST",
      url: serviceUrl,
      contentType: "application/json",
      dataType: "json",
	  jsonp: null,
	  jsonpCallback: null,
      data: JSON.stringify(data || {}),
      success: callback || Helper.execJS,
      error:  errorCallback || function(request) { 
        //var r = $.parseJSON(request.responseText);
        // Usually access denied.
        //alert(r.Message);
      }
    });
  };
  
  /**
   * Makes a syncronous ajax call to get the 
   * conents of an html file.  This means 
   * that the browser will be locked up until the 
   * XML is recieved and returned.  Best for small 
   * non dynamic files.
   */
   parent.getXml = function(filename){
    var returnXml;
     
    $.ajax({
      type: 'GET',
      url: filename,
      dataType: 'xml',
      async: false,
      success: function(data){         
        returnXml = data;
      }
    });
     
    return returnXml;    
  };  
    
  /**
   * An include function for pulling in JS
   */
  parent.include = function(destination) {
    var e=window.document.createElement('script');
    e.setAttribute('src', destination);
    e.setAttribute('type', 'text/javascript');
    window.document.body.appendChild(e);
  };

  /**
   * Makes a syncronous ajax call to get the 
   * conents of an html file.  This means 
   * that the browser will be locked up until the 
   * HTML is recieved and returned.
   */
  parent.getHtml = function(filename){
    var returnHTML;
     
    $.ajax({
      type: 'GET',
      url: filename,
      dataType: 'html',
      async: false,
      success: function(html){         
        returnHTML = html;
      }
    });
     
    return returnHTML;    
  };    
  
  /**
   * Returns the value of a cookie specified by name.
   */
  parent.readCookie = function(name) {
    var nameEQ = name + "=",
        ca = document.cookie.split(';'),
        i, c;
        
    for(i = 0; i < ca.length; i++) {
      c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    
    return null;
  };


  /**
   * Shuffles an array.  Based on code at:
   * http://jsfromhell.com/array/shuffle
   */
   parent.shuffle = function(v) {
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
   };
   
  return parent; 
  
}(Helper || {}));

