
YAHOO.Dom = YAHOO.util.Dom;
YAHOO.Event = YAHOO.util.Event;

function $id(id) {
    return document.getElementById(id);
}

function $parent(elem,tagn) {
	while ((elem=elem.parentNode)!=null && elem.tagName.toLowerCase()!=tagn)
		;
		
	return elem;
}

function instantiateWidgets(list) {
	wlist = [];
	for (var id in list) {
		wlist.push($id(list[id]));
	}
}

function $className(classn,tagn,parent) {
    return arpt.getElementsByClass(classn,parent,tagn);
}

function $new(tag) {
    var e = document.createElement(tag);
	return e;
}

String.prototype.ucwords = function(){
     return this.toLowerCase().replace( /\w+/g, function(s){return s.charAt(0).toUpperCase()+s.substr(1);} );
}

function html_escape(s) {
	return s ? s.replace(/[<>&"]/g, function(r) {
		if (r=='<') return '&lt;';
		else if (r=='>') return '&gt;';
		else if (r=='"') return '&quot;';
		else return '&amp;'; } ) : null;
}

OKOBE = { };
OKOBE.widgets = { };

arpt = {
	widget_map: [],

	init: function() {
		// Call onLoad functions.
		//
		for (var i=0; i!=_onload_fns.length; i++) {
			_onload_fns[i]();
		}
	},
	
	onLoad: function(fn) {
		_onload_fns.push(fn);
	},
	
	confirmDeleteAction: function(ev,msg) {
		arpt.confirmAction(ev,"Are you sure that you want to delete this item?");
	},
	
	confirmAction: function(ev,msg) {
		if (!confirm(msg)) {
			YAHOO.Event.preventDefault(ev);
		}
	},

	setTextContent: function(node,text) {
		while(node.firstChild) {
			node.removeChild(node.firstChild);
		}
		node.appendChild(document.createTextNode(text));
	},
	
	getTextContent: function(node) {
		var t = "";
    	if (node == null) { return t; }
      	for (var i=0; i<node.childNodes.length; i++) {
        	switch (node.childNodes[i].nodeType) {
            	case 1: case 5:
                	t += arpt.getTextContent(node.childNodes[i]);
                    break;
                    
				case 3: case 2: case 4: 
                	t += node.childNodes[i].nodeValue;
                    break;
           }
        }
        return t;
	},
	
	getElementsByClass: function(searchClass,node,tag) {
		var elems = new Array();
		if (node == null)
			node = document;
		if (tag == null)
			tag = '*';
		
		var els = node.getElementsByTagName(tag);
		
		if (searchClass) {
			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) ) {
					elems[j++] = els[i];
				}
			}
			return elems;
		} else {
			return els;
		}
	},
		
	getEventTarget: function(evt) {
		//	Returns the target of an event
		var t = (evt.srcElement ? evt.srcElement : (evt.target ? evt.target : null));
		while((t)&&(t.nodeType!=1)){ t = t.parentNode; }
		return t;	//	HTMLElement
	},
		
	preventDefault: function(evt) {
    	if (evt.preventDefault) {
        	evt.preventDefault();
        } else {
            evt.returnValue = false;
        }
    },
		
	highlightErrors: function(formId,errorFields) {

		var form = $id(formId);
		if (form) {		
			for (var i in errorFields) {
				this.highlightField( form[errorFields[i]] );
			}
	    }
    },

	highlightField: function(field) {
		if (field) {
			var label = YAHOO.Dom.getPreviousSibling(field);
			if (label)
				YAHOO.Dom.addClass(label, 'labelInvalid');
	
			YAHOO.Dom.addClass(field, 'fldInvalid');
		}
	},
	    
	/** Opens a simple popup window in the browser using window.open.
	 * status is set to 0 by default. The window is opened in the center of the
	 * desktop.	 
	 * @returns Nothing is returned so that the function can be used directly
	 * in the href of an anchor.	 	 	
	 */	
	openSimplePopup: function(url,wdt,hgt,opts) {
		var winl = (screen.width - wdt) / 2;
	    var wint = (screen.height - hgt) / 2;
	
		if (opts) opts=","+opts;
		var popup = window.open(url,'name',
			'status=0,height='+hgt+',width='+wdt+',left='+winl+',top='+wint+opts );
	
		popup.focus();
	},
	
	showDialog: function( name, options ) {
		if (options.buttons==null) {
			options.buttons = [];
		
			if (options.btn_ok) 
				options.buttons.push( { text:"OK", handler:options.btn_ok, isDefault:true } );
			
			if (options.btn_cancel) 
				options.buttons.push( { text:"Cancel", handler:options.btn_cancel } );
		}
	
		var btns = options.buttons;
		delete options.buttons;
		var icon = options.icon;
		delete options.icon;
	
		var dlg = new YAHOO.widget.SimpleDialog( name, options );
		dlg.setHeader(options.header);
		dlg.setBody(options.body);
		dlg.cfg.queueProperty("icon",icon);
		dlg.cfg.queueProperty("buttons", btns);
		dlg.render(document.body);
	},

	_cal_error: function(msg) {
		alert(msg);
		return null;
	},
	
	// time parsing function
	//
	parseTimeStr: function(strTime, date) {
		if (!date) return null;
		var time = String(strTime ? strTime : '').split(':');

		var RE_NUM = /^\-?\d+$/;
		
		if (!time[0]) 
			date.setHours(0);
		else if (RE_NUM.exec(time[0]) && time[0]<24)  
			date.setHours( time[0] );
		else 
			return arpt._cal_error ("Invalid hours value: " + strTime);
		
		if (!time[1]) 
			date.setMinutes(0);
		else if (RE_NUM.exec(time[1]) && time[1] < 60) 
			date.setMinutes(time[1]);
		else 
			return arpt._cal_error ("Invalid minutes value: " + strTime);

		if (!time[2]) 
			date.setSeconds(0);
		else if (RE_NUM.exec(time[2]) && time[2] < 60) 
			date.setSeconds(time[2]);
		else
			return arpt._cal_error ("Invalid seconds value: " + strTime);
	
		return date;
	},
	
	getDateStr: function(date) {
	    return( date.getFullYear() + "-"
        		 + (date.getMonth() < 9 ? '0' : '') + (date.getMonth()+1) + "-"
        		 + (date.getDate() < 10 ? '0' : '') + date.getDate());
	},
	
	formatTime: function(time) {
		return  (time.getHours() < 10 ? '0' : '') + time.getHours() + ":"
			  + (time.getMinutes() < 10 ? '0' : '') + time.getMinutes();
	},
	
	// This little trick reloads the page. Better than using history.go(0) because Firefox will reset form 
	// field values to the original values.
	//
	reloadPage: function() {
		location.href = location.href;
	},

	// Same as browsers back button.
	//	
	goBack: function() {
		history.go(-1);
	},
	
	getWidget: function(id) {
		return arpt.widget_map[id];
	},

	putWidget: function(id, obj) {
		arpt.widget_map[id] = obj;
	},

	widgets: {
		spinner: function(ctrl,value) {
			var input = value==-1 ? ctrl.nextSibling : ctrl.previousSibling;
			var v = value + input.value*1;
			var min = 1 * input.getAttribute("minValue");
			var max = 1 * input.getAttribute("maxValue");
			if (v >= min && v <= max) {
				input.value = v;
			}
		}
	}
};

_onload_fns = [];
window.onload = arpt.init;
