// $Id: general.js,v 1.27 2009/01/16 17:33:14 allan Exp $
// Added functionality for javascript

function huxGetWindowSize(){
	var window_width, window_height;
	if (self.innerHeight) {	// all except Explorer
		window_width = self.innerWidth;
		window_height = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		window_width = document.documentElement.clientWidth;
		window_height = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		window_width = document.body.clientWidth;
		window_height = document.body.clientHeight;
	}	
	return [window_width, window_height];
}
function huxShowLoading() {
  // get the size of the page using greybox funcs
  var window_size = huxGetWindowSize();

  // setup the overlay
  $('huxloading_overlay').style.width = window_size[0]+"px";
  $('huxloading_overlay').style.height = window_size[1]+"px";
  $('huxloading_gif').style.marginLeft = ((window_size[0] - 300) /2) + "px";
  $('huxloading_gif').style.marginTop = ((window_size[1] - 200) /2) + "px";
  
  window.setTimeout('$(\'huxloading_overlay\').style.display = \'block\';', 50);
}

/* Date/Time Format v0.2; MIT-style license
By Steven Levithan <http://stevenlevithan.com> */

Date.prototype.format = function(mask) {
	var d = this; // Needed for the replace() closure
	
	// If preferred, zeroise() can be moved out of the format() method for performance and reuse purposes
	var zeroize = function (value, length) {
		if (!length) length = 2;
		value = String(value);
		for (var i = 0, zeros = ''; i < (length - value.length); i++) {
			zeros += '0';
		}
		return zeros + value;
	};
	
	return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMs])\1?|TT|tt|[lL])\b/g, /* " fix font lock */ function($0) {
		switch($0) {
			case 'd':	return d.getDate();
			case 'dd':	return zeroize(d.getDate());
			case 'ddd':	return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];
			case 'dddd':	return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()];
			case 'm':	return d.getMonth() + 1;
			case 'mm':	return zeroize(d.getMonth() + 1);
			case 'mmm':	return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
			case 'mmmm':	return ['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];
			case 'yy':	return String(d.getFullYear()).substr(2);
			case 'yyyy':	return d.getFullYear();
			case 'h':	return d.getHours() % 12 || 12;
			case 'hh':	return zeroize(d.getHours() % 12 || 12);
			case 'H':	return d.getHours();
			case 'HH':	return zeroize(d.getHours());
			case 'M':	return d.getMinutes();
			case 'MM':	return zeroize(d.getMinutes());
			case 's':	return d.getSeconds();
			case 'ss':	return zeroize(d.getSeconds());
			case 'l':	return zeroize(d.getMilliseconds(), 3);
			case 'L':	var m = d.getMilliseconds();
					if (m > 99) m = Math.round(m / 10);
					return zeroize(m);
			case 'tt':	return d.getHours() < 12 ? 'am' : 'pm';
			case 'TT':	return d.getHours() < 12 ? 'AM' : 'PM';
			// Return quoted strings with the surrounding quotes removed
			default:	return $0.substr(1, $0.length - 2);
		}
	});
};

// adapted from
// http://weblogs.asp.net/skillet/archive/2006/03/23/440940.aspx
function dumpObj(obj, name, indent, depth) {
    var MAX_DUMP_DEPTH = 10;
    if(name == null){
        name = (obj.name == null) ? '*undefined*' : obj.name;
    }
    var indent = (indent == null) ? '' : indent;
    var depth  = (depth  == null) ? 0 : depth;
    if (depth > MAX_DUMP_DEPTH) {
        return indent + name + ": <Maximum Depth Reached>\n";
    }
    if (typeof obj == "object") {
        var child = null;
        var output = indent + name + "\n";
        indent += "\t";
        for (var item in obj){
            try {
                child = obj[item];
                } catch (e) {
                    child = "<Unable to Evaluate>";
                }
                if (typeof child == "object") {
                    output += dumpObj(child, item, indent, depth + 1);
                } else {
                    output += indent + item + ": " + child + "\n";
                }
        }
        return output;
    } else {
        return obj;
    }
}


function print_r(theObj) {
   if (theObj.constructor == Array || theObj.constructor == Object) {
      document.write("<ul>")
      for (var p in theObj) {
         if(theObj[p].constructor == Array || theObj[p].constructor == Object) {
            document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
            document.write("<ul>")
            print_r(theObj[p]);
            document.write("</ul>")
         } else {
            document.write("<li>["+p+"] => "+theObj[p]+"</li>");
         }
      }
      document.write("</ul>")
   }
}

// quick check for email addresses
// NOTE this is incomplete, The real regex is hideously large
// see http://www.regular-expressions.info/email.html
function isReasonableEmail( email ){
    if( /^[-_a-z0-9]+(\.[-_a-z0-9]+)*@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]{2,6}$/i.test( email ) ){
        return true;
    }
    return false;
}

// http://kevin.vanzonneveld.net
function file_get_contents( url ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Legaev Andrey
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes. 
    // %        note 1: To avoid browser blocking issues's consider using jQuery's: $('#divId').load('http://url') instead.
    // *     example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
 
    var req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) throw new Error('XMLHttpRequest not supported');
    
    req.open("GET", url, false);
    req.send(null);
    
    return req.responseText;
} // file_get_contents()

function require( filename ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Force Javascript execution to pause until the file is loaded.
    //                  Usually causes failure if the file never loads. ( Use sparingly! )
    // -    depends on: file_get_contents
    // *     example 1: require('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: 2
 
    var js_code = file_get_contents(filename);
    var script_block = document.createElement('script');
    script_block.type = 'text/javascript';
    var client_pc = navigator.userAgent.toLowerCase();
    if((client_pc.indexOf("msie") != -1) && (client_pc.indexOf("opera") == -1)) {
        script_block.text = js_code;
    } else {
        script_block.appendChild(document.createTextNode(js_code));
    }
 
    if(typeof(script_block) != "undefined") {
        document.getElementsByTagName("head")[0].appendChild(script_block);
 
        // save include state for reference by include_once and require_once()
        var cur_file = {};
        cur_file[window.location.href] = 1;
 
        if (!window.php_js) window.php_js = {};
        if (!window.php_js.includes) window.php_js.includes = cur_file;
 
        if (!window.php_js.includes[filename]) {
            window.php_js.includes[filename] = 1;
        } else {
            // Use += 1 because ++ waits until AFTER the original value is returned to increment the value.
            return window.php_js.includes[filename] += 1;
        }
    }
} // require()

function require_once(filename) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // -    depends on: require
    // *     example 1: require_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
    // *     returns 1: true
 
    var cur_file = {};
    cur_file[window.location.href] = 1;
 
    // save include state for reference by include_once and require_once()
    if (!window.php_js) window.php_js = {};
    if (!window.php_js.includes) window.php_js.includes = cur_file;
    if (!window.php_js.includes[filename]) {
        if (require(filename)) {
            return true;
        }
    } else {
        return true;
    }
} // require_once()

// http://www.quirksmode.org/js/cookies.html
// the name and value of the cookie and the number of days it stays active
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    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) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
  if (obj!=null && obj.options!=null) { return true; }
  return false;
}

// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
  var o = new Array();
  if (!hasOptions(obj)) { return; }
  for (var i=0; i<obj.options.length; i++) {
    o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
  }
  if (o.length==0) { return; }
  o = o.sort( 
    function(a,b) { 
      if ((a.text+"") < (b.text+"")) { return -1; }
      if ((a.text+"") > (b.text+"")) { return 1; }
      return 0;
    } 
  );
  
  for (var i=0; i<o.length; i++) {
    obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  }
}

function dhmToSecs(days, hours, mins) {
  var secs = 0;
  secs += days * 86400;
  secs += hours * 3600;
  secs += mins * 60;
  return secs;
}

function secsToDHM(secs) {
  var dhm = new Array();
  dhm['days'] = Math.floor(secs / 86400);
  var secsRemaining = secs - (dhm['days'] * 86400);
  dhm['hours'] = Math.floor(secsRemaining / 3600);
  secsRemaining = secsRemaining - (dhm['hours'] * 3600);
  dhm['mins'] = Math.floor(secsRemaining / 60);
  return dhm;
}


/* Moves the selected option from one select to another */
function moveSelectedOption(from, to) {
  if (from.selectedIndex != -1) {
    to_move = from.options[from.selectedIndex];
    MochiKit.DOM.appendChildNodes(to, to_move);
    return true;
  }
  return false;
}

function findSelectOptionIdByValue(elem, value) {
  for (i = 0; i < elem.options.length; i++) {
    if (elem.options[i].value == value) {
      return i;
    }
  }
  return false;
}

function makeScrollTable(id, width, height) {
  divElem = document.getElementById(id);
  tableElem = getElementsByTagAndClassName('table', null, id)[0];
  tbodyElem = getElementsByTagAndClassName('tbody', null, id)[0];

  setElementClass(divElem, 'scrollTableContainer');
  divElem.style.width = width+'px';
  if (!(window.ie == undefined)) {
    tableElem.style.width = (width - 18)+'px';
    divElem.style.height = height+'px';
  } else {
    tableElem.style.width = width+'px';
    tbodyElem.style.overflow = 'auto';
    tbodyElem.style.height = (height-30)+'px';
    tbodyElem.style.overflowX = 'hidden';
  }

  setElementClass(tableElem, 'dataTable');
  divElem.style.display = 'block';
  divElem.style.visibility = 'visible';
}
