/* <?php require_once('main_js.php'); ?> */
/**
 * Utilities
 *
 * Note that DOCTYPE setting affects the _gimme_mouse_x_y() routine
 *
 *
 * @author    Glen
 * @copyright 2006 flickaway.com
 * @version   $Id: utils.js 2045 2009-05-12 06:57:05Z glen $
 */


if (typeof FA == "undefined" || !FA)
{
  FA = {};                                  // Flickaway namespace
                                            // --------------------------------------------------------------------------------------------------
  FA.T = {};                                // TMP  namespace  - used to hold temporary global references to classes that need inline callbacks
  FA.M = {};                                // MODE namespace - all MODE CLASSES defined here
}

//==========================================================================================
//
// GLOBAL ROUTINES to make long-winded JS stuff less winded
//
//==========================================================================================

//$GE = document.getElementById;
//
// why doesn't the above work for firefox ??
//
function $GE(e)
{
  return document.getElementById(e);
}



FA.Utils = function()
{}

p = FA.Utils.prototype;


FA.Utils.prototype.isset = function(v)
{
  var t = typeof(v);
  return (t != 'undefined' && t != 'function');
}



//==========================================================================================
// Adapted from prototype.js
//
// These routines manipulate class names of DOM elements, like:
//
//  <div class="box highlight"> ... </div>
//
// it is very handy to apply more than one class name to an element, so manipulating them
// in JS isn't quite as easy as just setting them.  String manipulation must be done.
//==========================================================================================
FA.Utils.prototype.has_class_name = function(e, name)
{
  var e_name = e.className;
  return (e_name.length > 0 && (e_name == name || new RegExp("(^|\\s)" + name + "(\\s|$)").test(e_name)));
}

FA.Utils.prototype.add_class_name = function(e, name)
{
  if (!this.has_class_name(e, name))
  {
    e.className += (e.className ? ' ' : '') + name;
  }
}

FA.Utils.prototype.remove_class_name = function(e, name)
{
  e.className = e.className.replace(new RegExp("(^|\\s+)" + name + "(\\s+|$)"), ' ').replace(/^\s+/, '').replace(/\s+$/, '');
}

FA.Utils.prototype.toggle_class_name = function(e, name)
{
  return this[this.has_class_name(e, name) ? 'remove_class_name' : 'add_class_name'](e, name);
}

FA.Utils.prototype.replace_class_name = function(e, old_name, new_name)
{
  this.remove_class_name(e, old_name);
  this.add_class_name(e, new_name);
}


FA.Utils.prototype.is_a_child_of = function(parent, child)
{
  if (parent === child)
  {
    return false;
  }
  while (child && child !== parent)
  {
    child = child.parentNode;
  }
  return (child === parent);
}


/**
 * Generic routine to calculate the x, y, width, height of an element
 *
 *--------------------------------------------------------------------------------------------------
 * WARNING:
 *--------------------------------------------------------------------------------------------------
 *
 * Browsers (IE in particular) have problems using this routine as the DOM is being layed-out, due
 * to the browser window being resized etc.  This routine should not be used within the callback
 * of a onboardresize event, for example.  Rather, you should use setTimeout and call this in a
 * delayed manner.  Also, make sure you clear the accumulating timeouts.
 *
 *--------------------------------------------------------------------------------------------------
 *
 * @param {Object} elem
 */
FA.Utils.prototype.gimme_elem_x_y = function(elem)
{
  var x = 0, y = 0, width, height;

  if (elem.offsetWidth)
  {
    width  = elem.offsetWidth;
    height = elem.offsetHeight;
  }
  else
  {
    width   = elem.clientWidth;
    height  = elem.clientHeight;
  }

	if (elem.offsetParent)
	{
		while (elem.offsetParent)
		{
			x += elem.offsetLeft;
			y += elem.offsetTop;
			elem = elem.offsetParent;
    }
	}
	else if (elem.x)
	{
		x += elem.x;
		y += elem.y;
	}

  return [x, y, width, height];
}

/*
Gets teh window size (visible? not including scrollbars??) .. not sure

FROM: http://www.bobbyvandersluis.com/swfobject/testsuite_2_1/test_dynamic_fullbrowserflash_adv.html

		function getViewportSize() {
			var size = [0, 0];
			if (typeof window.innerWidth != "undefined") {
				size = [window.innerWidth, window.innerHeight];
			}
			else if (typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
				size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
			}
			else {
				size = [document.getElementsByTagName("body")[0].clientWidth, document.getElementsByTagName("body")[0].clientHeight];
			}
			return size;
		}
*/


/**
 * This works for HTML DOCTYPE only - XHTML DOCTYPE needs a different implementation
 * @param {Object} event
 */
FA.Utils.prototype.gimme_mouse_x_y = function(event)
{
  if (!event)
  {
    event = window.event;
  }
  var x = 0;
  var y = 0;
  if (event.pageX || event.pageY)           // for Mozilla
  {
    x = event.pageX;
    y = event.pageY;
  }
  else if (event.clientX || event.clientY)  // for IE
  {
    x = event.clientX + document.body.scrollLeft;       // For XHTML doctype - you need to replace body with documentElement!!!!
    y = event.clientY + document.body.scrollTop;        // For XHTML doctype - you need to replace body with documentElement!!!!
  }

  return [x, y];
}



/**
 * Returns an array of elements of a certain class
 *
 * @param {String}  searchClass  - class name to look for
 * @param {Element} node         - inside a certain parent element
 * @param {String}  tag          - of a particular tag type (e.g. "a" for anchor)
 */
FA.Utils.prototype.getElementsByClass = function(searchClass, node, tag)
{
	var classElements = [];
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


FA.Utils.prototype.utc_to_mid_str = function(utc, time_flag)
{
  var m_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  var d = new Date();
  var diff = d.getTimezoneOffset() * 60 *1000;
  d.setTime((parseInt(utc)*1000)-diff);
  var ret = m_names[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
  if (time_flag)
  {
    ret += ' ' + d.getHours() + ':' + d.getMinutes();
  }
  return ret;
}


/**
 * This code was written by Tyler Akins and has been placed in the
 * public domain.  It would be nice if you left this header intact.
 * Base64 code from Tyler Akins -- http://rumkin.com
 *
 * Note: I moved routines into one to save on bytes...
 *
 * -- IMPORTANT --
 * I changed the keyStr below to show  ...9-_=" instead of ...9+/=
 * to avoid these chars in URLs.  PHP side of things has been adapted
 * likewise.
 */
FA.Utils.prototype.encode64 = function(input) { return this._64code(1, input);}
FA.Utils.prototype.decode64 = function(input) { return this._64code(0, input);}

//------------------------------------------------------------------------------------
//
//                                -- IMPORTANT --
//
// I changed the keyStr below to show  ...9-_=" instead of ...9+/=
// to avoid these chars in URLs.  PHP side of things has been adapted
// likewise.
//------------------------------------------------------------------------------------
FA.Utils.prototype._64code = function(encode, input)
{
  var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;

  if (encode)
  {
    //-----------------------------------------------------
    // ENCODE
    //-----------------------------------------------------
    do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
    } while (i < input.length);
  }
  else
  {
    //-----------------------------------------------------
    // DECODE
    //-----------------------------------------------------
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) { output = output + String.fromCharCode(chr2); }
      if (enc4 != 64) { output = output + String.fromCharCode(chr3); }
    } while (i < input.length);
  }

  return output;
}



/**
 * Redirect to given URL and HASH
 *
 * @param {Object} to_url
 * @param {Object} to_hash
 */
FA.Utils.prototype.redirect = function(to_url, to_hash, hash_var)
{

/*
  var form_div = document.createElement("div");

  var str = '';
  str+='<form name="redirect_form" action="/redirect.html" enctype="multipart/form-data" method="POST" autocomplete="off">';
  str+=' <input type="hidden" name="redir" value="' + to_url + '" />';
  if (to_hash)
    str+=' <input type="hidden" name="hash" value="' + to_hash + '" />';
  str+='</form>';

  g_trace.log("form is " + str);
  form_div.innerHTML = str;
  document.body.appendChild(form_div, 0);

  g_trace.log("after innerHTML");
  //setTimeout(function(){document.redirect_form.submit();}, 1000);
  document.redirect_form.submit();

  g_trace.log("after submit");
*/


  if (to_hash)
  {
    g_trace.log("Redirecting now to " + to_url + "#" + to_hash);
    location.href = '/redirect.html?redir=' + to_url + '&hash=' + to_hash + '&hash_var=' + hash_var;
  }
  else
  {
    g_trace.log("Redirecting now to " + to_url);
    location.href = '/redirect.html?redir=' + to_url;
  }
}

FA.Utils.prototype.redirect_to_sign_in = function()
{
  //---------------------------------------------------------------------------------------
  // window.location.href     = "https://www.fa.com/settings.html?menu=ae"
  // window.location.protocol = "https:"

  var redir = g_utils.encode64(window.location.href);
  //var minus_http = window.location.href.substr(window.location.protocol.length + 2);
  //var redir = g_utils.encode64(minus_http.substr(minus_http.search('/')));
  window.location = "<?php echo Url::P_SIGN_IN; ?>?goto=" + redir;
}


FA.Utils.prototype.cursor_to_drag = function(el_name)
{
  $GE(el_name).style.cursor = 'url("/i/fa/o/hand_open.cur"), move';
}


FA.Utils.prototype.cursor_dragging = function(el_name)
{
  $GE(el_name).style.cursor = 'url("/i/fa/o/hand_closed.cur"), move';
}


FA.Utils.prototype.cursor_auto = function(el_name)
{
  $GE(el_name).style.cursor = 'auto';
}


FA.Utils.prototype.preload_drag_cursors = function()
{
  var tmp = new Image();
  tmp.src = "/i/fa/o/hand_open.cur";
  tmp.src = "/i/fa/o/hand_closed.cur";
}

//==== Utils GLOBALS ==========================================

var gu = g_utils = new FA.Utils();

