/**	
	@author			nathaniel skulic <nate@skulic.name>
	@copyright 		Copyright 2007, Nathaniel Skulic. All Rights Reserved.
	@fileOverview	
*/

oil.utility = {};
if(!GUI) var GUI = {};
if(!GUI.Utility) GUI.Utility = {};

oil.utility.number_names = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty' ];

GUI.Utility.get_form_values = function(form, validation_handler){

    var str = "";
    var valueArr = null;
    var val = "";
    var cmd = "";

    for(var i = 0;i < form.elements.length;i++){
        switch(form.elements[i].type){
            case "hidden":
            case "textarea":
            case "input":
            case "text":{
                if(validation_handler){
                    //use single quotes for argument so that the value of
                    //fobj.elements[i].value is treated as a string not a literal
                    cmd = valFunc + "(" + 'form.elements[i].value' + ")";
                    val = eval(cmd)
                }

                str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";

                break;
            }
            case "select-one":{
                str += form.elements[i].name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
                break;
            }
        }
    }

    str = str.substr(0,(str.length - 1));

    return str;

}


GUI.Utility.get_scrollbar_width = function() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}



function toRadix(N,radix) {
 var HexN="", Q=Math.floor(Math.abs(N)), R;
 while (true) {
  R=Q%radix;
  HexN = "0123456789abcdefghijklmnopqrstuvwxyz".charAt(R)+HexN;
  Q=(Q-R)/radix; if (Q==0) break;
 }
 return ((N<0) ? "-"+HexN : HexN);
}

GUI.Utility.convert_to_radix  = toRadix;

/* Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
} */

/** Returns a copy of this object as a new array
*/
/* Object.prototype.return_copy = */


 function array_copy(array) {
    var realArray = [];
    for (var idx = 0; idx < array.length; idx++){
        realArray.push(array[idx]);
    }
    return realArray;
};

Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    __method.apply(object, arguments);
  }
}

Function.prototype.periodical= function(interval, bind, args){
	var fn = bind || this;
	
	var returns = function(){
		return fn.apply(this, args);
	};
			
	return setInterval(returns, interval);
	
}


function periodical(base, interval, bind, args){
	
	var returns = function(){
		return base.apply(bind, args);
	};
			
	return setInterval(returns, interval);
	
}

/* Cross-Browser Split v0.1; MIT-style license
By Steven Levithan <http://stevenlevithan.com>
An ECMA-compliant, uniform cross-browser split method */
String.prototype.xsplit = function(separator, limit) {
    var flags = "";

    /* Behavior for separator: If it's...
    - Undefined: Return an array containing one element consisting of the entire string
    - A regexp or string: Use it
    - Anything else: Convert it to a string, then use it */
    if (separator === undefined) {
        return [this.toString()]; // toString is used because the typeof this is object
    } else if (separator === null || separator.constructor !== RegExp) {
        // Convert to a regex with escaped metacharacters
        separator = new RegExp(String(separator).replace(/[.*+?^${}()|[\]\/\\]/g, "\\$&"), "g");
    } else {
        flags = separator.toString().replace(/^[\S\s]+\//, "");
        if (!separator.global) {
            separator = new RegExp(separator.source, "g" + flags);
        }
    }

    // Used for the IE non-participating capturing group fix
    var separator2 = new RegExp("^" + separator.source + "$", flags);

    /* Behavior for limit: If it's...
    - Undefined: No limit
    - Zero: Return an empty array
    - A positive number: Use limit after dropping any decimal value (if it's then zero, return an empty array)
    - A negative number: No limit, same as if limit is undefined
    - A type/value which can be converted to a number: Convert, then use the above rules
    - A type/value which cannot be converted to a number: Return an empty array */
    if (limit === undefined || +limit < 0) {
        limit = false;
    } else {
        limit = Math.floor(+limit);
        if (!limit) return []; // NaN and 0 (the values which will trigger the condition here) are both falsy
    }

    var match,
        output = [],
        lastLastIndex = 0,
        i = 0;

    while ((limit ? i++ <= limit : true) && (match = separator.exec(this))) {
        // Fix IE's infinite-loop-resistant but incorrect RegExp.lastIndex
        if ((match[0].length === 0) && (separator.lastIndex > match.index)) {
            separator.lastIndex--;
        }

        if (separator.lastIndex > lastLastIndex) {
            /* Fix IE to return undefined for non-participating capturing groups (NPCGs). Although IE
            incorrectly uses empty strings for NPCGs with the exec method, it uses undefined for NPCGs
            with the replace method. Conversely, Firefox incorrectly uses empty strings for NPCGs with
            the replace and split methods, but uses undefined with the exec method. Crazy! */
            if (match.length > 1) {
                match[0].replace(separator2, function(){
                    for (var j = 1; j < arguments.length - 2; j++){
                        if (arguments[j] === undefined) match[j] = undefined;
                    }
                });
            }

            output = output.concat(this.substring(lastLastIndex, match.index), (match.index === this.length ? [] : match.slice(1)));
            lastLastIndex = separator.lastIndex;
        }

        if (match[0].length === 0) {
            separator.lastIndex++;
        }
    }

    return (lastLastIndex === this.length)
        ? (separator.test("") ? output : output.concat(""))
        : (limit ? output : output.concat(this.substring(lastLastIndex)));
};


function isset(varname){
  return(typeof(window[varname])!='undefined');
}

function adjust_link_to_hash(link){
	currentvalue = link.pathname;
	base = '';
	/* if(link.baseURI)
		base = link.baseURI.split('#')[1]; */
	if(currentvalue.substring(0,1) != '/'){
		currentvalue = currentvalue.replace(window.location.pathname, '');
		link.href = '#'+currentvalue; 
	}
	else{}
	//link.href = '#'+base+currentvalue.replace(PATH_ROOT, '');//.replace(window.location.pathname, '');
	link.href = '#'+currentvalue;
}
function strip_path(string){
	
	//return string.replace(path.substring(0,path.lastIndexOf('/')), '' )
	return path;
}

function get_path(){
	path = window.location.pathname;
	return path.substring(0,path.lastIndexOf('/'));

}

// TODO: print an array of strings
function print_array(array){
}

GUI.Utility.fix_input_classes = function(){
/* var els = document.getElementsByTagName('input');
var elsLen = els.length;
var i = 0;
for ( i=0;i<elsLen;i++ )
{
if ( els[i].getAttribute('type') )
{
if ( els[i].getAttribute('type') == "text" )
els[i].className += ‘ text’;
else
els[i].className += ‘ button’;
}
} */
}

function $defined(obj){
	return (obj != undefined);
};

function $pick(obj, picked){
	return $defined(obj) ? obj : picked;
};



function typeOf(object) {
  var type = typeof object;
  switch (type) {
    case "object":
      return object === null ? "null" : typeof object.call == "function" || _MSIE_NATIVE_FUNCTION.test(object) ? "function" : type;
    case "function":
      return typeof object.call == "function" ? type : "object";
    default:
      return type;
  }
};



function format(string) {
  // Replace %n with arguments[n].
  // e.g. format("%1 %2%3 %2a %1%3", "she", "se", "lls");
  // ==> "she sells sea shells"
  // Only %1 - %9 supported.
  var args = arguments;
  var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
  return String(string).replace(pattern, function(match, index) {
    return args[index];
  });
};
function copy(object) {
  var fn = function(){};
  fn.prototype = object;
  return new fn;
};






function intval( mixed_var, base ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
 
    var tmp;
 
    if( typeof( mixed_var ) == 'string' ){
        tmp = parseInt(mixed_var);
        if(isNaN(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if( typeof( mixed_var ) == 'number' ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}
