/************************************************/

function getBrowserType(){
    if (navigator.userAgent.toLowerCase().indexOf("safari") != -1){
        return "safari";
    }
    if (navigator.appName.indexOf("Microsoft") != -1){
        return "ie";
    }
    // default
    return "mozilla";
}

/************************************************/
function isSafari(){
    return (getBrowserType() == 'safari');
}

/***********************************************/
function isIE6(){
    return (Browser.Engine.trident
            && Browser.Engine.version == 4);
}

function isIE(){
    return (getBrowserType() == 'ie');
}

/************************************************/

function getScrollX(win){
    switch (getBrowserType()){
    case "ie":
        if (win.document.documentElement
            && win.document.documentElement.scrollLeft){
            return win.document.documentElement.scrollLeft;
        }
        return win.document.body.scrollLeft;
  
        break;
    case "mozilla":
    default:
        return win.pageXOffset;
    }
}

/************************************************/

function getScrollY(win){
    switch (getBrowserType()){
    case "ie":
        if (win.document.documentElement
            && win.document.documentElement.scrollTop){
            return win.document.documentElement.scrollTop;
        }

        return win.document.body.scrollTop;
        break;
    case "mozilla":
    default:
        return win.pageYOffset;
    }
}

function getRadioValue(group){
    for(var i = 0; i < group.length; i++){
        var radio = group[i];
        if (radio.checked) return radio.value;
    }
    return null;
}

/**
 *
 **/

function printLog(text){
    var win = window.open("", "_blank");
    text = text.replace(/</g, "&lt;");
    text = text.replace(/>/g, "&gt;");
    win.document.write("<body><pre>" + text + "\n\n</pre></body>");
}

function printObj(object, level, printFunctions){
    var output = "";
    for(var i in object){
	for(var j = 0; j < level; j++){
	    output += " ";
	}
	if (typeof object[i] == 'object'){
	    output += i + ":\n" + printObj(object[i], level + 1, printFunctions);
	}
	else if (printFunctions == true
		 || typeof object[i] != 'function'){
	    output += i + ": " + object[i] + "\n";
	}
    }
    if (level == 0){
	var win = window.open("", "_blank");
	if (win){
	    win.document.write("<body><pre>" + output + "\n\n</pre></body>");
	}
	
    }
    return output;
}    

/**
 * getTopPos
 **/
function getTopPos(obj){
    var top = obj.offsetTop; 
    if (obj.offsetParent != null){
	top += getTopPos(obj.offsetParent);
    }
    return top;
    
}

/**
 * getLeftPos
 **/
function getLeftPos(obj){
    var left = obj.offsetLeft;
    if (obj.offsetParent != null){
	left += getLeftPos(obj.offsetParent);
    }
    return left;
}

/**
 * getHeight
 **/
function getHeight(obj){
    return obj.offsetHeight;
}

/**
 * getWidth
 **/
function getWidth(obj){
    return obj.offsetWidth;
}

/**
 * would prefer to do this as a Node.prototype but IE sucks.
 **/
function childOf(childNode, testNode){
    var parentNode = childNode;
    while(parentNode
	  && parentNode.parentNode){
	parentNode = parentNode.parentNode;
	if (parentNode == testNode) return true;
    }
    return false;
}

/**
 * rgb2hex
 **/

function rgb2hex(rgb){
    var regEx = new RegExp("rgb\\(([0-9]*)\\s*,\\s*([0-9]*)\\s*,\\s*([0-9]*)", "i");
    var matches = regEx.exec(rgb);
    
    if (matches){
	var hex = '#' + padNum(parseInt(matches[1]).toString(16), 2)
	    + padNum(parseInt(matches[2]).toString(16), 2)
	    + padNum(parseInt(matches[3]).toString(16), 2);
	return hex.toUpperCase();
    }
    return rgb;
}

function padNum(value, digits){
    for(var i = 0; i < digits - value.length; i++){
	value = '0' + value;
    }
    return value;
}

function alertObj(obj, level){
    var padding = "";
    var output = "";
    for(var j = 0; j < level; j++){
	padding += " ";
    }
    for(var i in obj){
	var data = obj[i];
	if (!(data instanceof Object)){
	    output += padding + i + ": " + data + "\n";
	}
	else if (!(data instanceof Function)){
	    output += padding + i + ":" + "\n"
		+ alertObj(data, level + 1);
	}
    }
    
    if (level == 0){
	alert(output);
	return;
    }
    else {
	return output;
    }
    
}

function clearTable(table, skip){
    if (!skip || (typeof skip) == 'undefined') skip = 0;
    while(table.rows.length > skip){
	table.deleteRow(-1);
    }
}

/**
 *
 **/
function getRandString(length){
    var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    
    var randString = '';
    for(var i = 0; i < length; i++){
	randString += chars.charAt([Math.floor(Math.random() * chars.length)]);
    }
    return randString;
}

/**
 * like PHP function
 **/

function inArray(needle, haystack){
    for(var i = 0; i < haystack.length; i++){
	if (haystack[i] == needle) return true;
    }
    return false;
}

function getElementRow(el){
    while(el.nodeName != 'TR'){
        if (el.parentNode){
            el = el.parentNode;
        }
        else {
            alert("Couldn't find Element Row.");
            return false;
        }
    }
    return el;
}

function getRowTable(row){
    var element = row;
    while(element.nodeName != 'TABLE'){
        if (element.parentNode){
            element = element.parentNode;
        }
        else {
            alert("Couldn't find Row Table.");
            return false;
        }
    }
    return element;
}

function getRowIndex(row){
    var table = getRowTable(row);
    if (table){
	for(var i = 0; i < table.rows.length; i++){
	    if (table.rows[i] == row) {
		return i;
	    }
	}
    }
    return -1;
}

function getParent(el, nodeName, upLevels){
    nodeCount = 0;
    while(nodeCount < upLevels){
	if (el.parentNode){
	    el = el.parentNode;
	}
	else {
	    alert("Couldn't find Element Parent " + nodeName + ".");
	    return false;
	}

	while(el.nodeName != nodeName){
	    if (el.parentNode){
		el = el.parentNode;
	    }
	    else {
		alert("Couldn't find Element Parent " + nodeName + ".");
		return false;
	    }
	}
	nodeCount++;
    }
    return el;
}
    
function stopBubble(e){
    (new Event(e)).stopPropagation();
}

function isDBKey(val){
    return val.match(/^[0-9]+$/);
}

function lpad(value, length){
    while(value.length < length){
	value = '0' + value;
    }
    return value;
    
}
function openWindow(url, target, param) {
    if (isIE()){
        var newWindow = window.open('',target,param);
        if (newWindow){
            newWindow.location.href = url;
        }
    } 
    else {
        var newWindow = window.open(url,target,param);
    }
  
    if (newWindow){
        newWindow.focus();
    }
    else {
        alert("There was a problem opening the new window.  You may need to disable popup blocking for this site.");
    }
}

function catchReturn(e, toDo){
    var ev = new Event(e);

    if (ev.key == 'enter'){
        ev.stop();
        
        if (toDo){
            toDo.call();
        }

        return false;
    }
    return true;
}

function setOptionsArray(select, options, selectVals, skip){
    if (skip){
        select.options.length = skip;
    }
    else {
        select.options.length = 0;
    }
    options.each(function(option){
            select.options[select.options.length] = new Option(option, option);
            if (selectVals && selectVals.contains(option)){
                select.options[select.options.length - 1].selected = true;
            }
        });
}

// assoc
function setOptionsObject(select, options, selectVals){
    select.options.length = 0;
    $each(options, function(option, key){
            select.options[select.options.length] = new Option(option, key);
            if (selectVals && selectVals.contains(option)){
                select.options[select.options.length - 1].selected = true;
            }
        });
}

function setSelectValue(select, value){
    $A(select.options).each(function(option, index){
            if (option.value == value){
                select.selectedIndex = index;
            }
        });
    
}


/**
 * el needs to have height/width set in pixels
 * and position should be fixed
 **/
function center(el){
    winSize = window.getSize();
    var height = el.getStyle('height');
    height = height.substring(0, height.length - 2);
    
    var width = el.getStyle('width');
    width = width.substring(0, width.length - 2);
    
    var x = Math.max(((winSize.x - width) / 2));
    var y = Math.max(0, ((winSize.y - height) / 2));
    
    el.setStyles({left: x,
                top: y
                });

    return el;
}

function isEnter(event){
    if (!event) return false;
    return (event.keyCode == 13);
}

function unknownError(){
    alert("Unknown Error.");
}