// JavaScript Document
// Last updated 2009-09-09 - Edited registerActiveSearchForm
// Last updated 2009-09-15 - Edited screenDimLoading to allow stop of hiding
// Last updated 2009-10-20 - Added function filterOptions

var GabeUtil = {};

GabeUtil.homepageUrl = 'http://www.directcomplaint.com/';
GabeUtil.loadingImage = GabeUtil.homepageUrl + 'images/loadingAnimation.gif';

GabeUtil.scDim = null;
GabeUtil.scDimLoading = null;

GabeUtil.filterOptions = function(sear, opts) {
	sear = (sear).replace(" ", "");
	var arr = sear.split(/(.{1,3})/);
	var arr2 = new Array();
	for(var i = 0; i < arr.length; i++) {
		if(arr[i] != '') {
			arr2.push(arr[i]);	
		}
	}
	var pattern = "(" + arr2.join('|') + ")";
	var regex = new RegExp(pattern, "ig");
	jQuery.each($(opts), function(i, val) {
		var opval = ($(val).html()).replace(" ", "");
		if(regex.test(opval) == true) {
			$(val).show();
			$(val).attr('selected', true);
		} else {
			$(val).hide();
		}
	});
}

GabeUtil.ajaxForm = function(aform, aoption) {
	
	var submits = $("input[type='submit']", $(aform));
	
	if(!aoption) {
		aoption = {};	
	}
	if(!aoption.success) {
		aoption.success = function(response) {};	
	}
	if(!aoption.beforeSubmit) {
		aoption.beforeSubmit = function(odata, oform, opt) {
			return true;	
		}	
	}
	if(!aoption.dataType) {
		aoption.dataType = null;	
	}
	
	var option = {};
	option.dataType = aoption.dataType;
	option.beforeSubmit = function(odata, oform, opt) {
		if(aoption.hideSubmit) {
			$(submits).attr('disabled', true);
		}
		return aoption.beforeSubmit(odata, oform, opt);
	}
	option.success = function(response) {
		if(aoption.hideSubmit) {
			$(submits).attr('disabled', false);
		}
		aoption.success(response);
	}
	
	$(aform).ajaxForm(option);
	
	
}

GabeUtil.ajaxFormJson = function(aform, aoption) {
	if(!aoption) {
		aoption = {};	
	}
	aoption.dataType = 'json';
	GabeUtil.ajaxForm(aform, aoption);
}

GabeUtil.ajaxFormHtml = function(aform, aoption) {
	if(!aoption) {
		aoption = {};
	}
	GabeUtil.ajaxForm(aform, aoption);
}


GabeUtil.getDayOfWeek = function(index) {
	index = index + '';
	var days = {	'1' : 'Monday',
					'2' : 'Tuesday',
					'3' : 'Wednesday',
					'4' : 'Thursday',
					'5' : 'Friday',
					'6' : 'Saturday',
					'7' : 'Sunday'
					};
	return days[index];
}

GabeUtil.wrapRoundBorder = function(selector) {
	var html = "<div><div class='gensmpan-tl'><div class='gensmpan-tr'><div class='gensmpan-tc'></div></div></div><div class='gensmpan-ml'><div class='gensmpan-mr'><div class='gensmpan-mc'><!-- CONTENTHERE --></div></div></div><div class='gensmpan-bl'><div class='gensmpan-br'><div class='gensmpan-bc'></div></div></div></div>";
	jQuery.each($(selector), function(i, val) {
		if($(val).parent().hasClass('gensmpan-mc')) {
			return;
		}
		$(val).before(html);
		$(".gensmpan-mc", $(val).prev()).append(val);
	});
}

GabeUtil.registerToggleButtons = function(selector, option) {
	/*
		toggle buttons contain the targetdiv metadata that they toggle
	*/
	
	if(!option) {
		option = {};	
	}
	
	if(typeof option.autohide == 'undefined') {
		option.autohide = true;
	}
	
	if(typeof option.hide == 'undefined') {
		option.hide = true;
	}
	
	var lastchosen = null;
	
	jQuery.each($(selector), function(i, val) {
		var targetdiv = $(val).metadata().targetdiv;
		var targetdivclass = $(val).metadata().targetdivclass;
		if(!targetdiv) {
			return;
		}
		if(targetdiv.indexOf('.') === -1 && targetdiv.indexOf('#') === -1) {
			// assume that it's an ID
			targetdiv = '#' + targetdiv;
		}
		if(option.autohide) {
			$(targetdiv).hide();
		}
		$(val).click(function(event) {
			
			event.preventDefault();
			
			if(targetdivclass) {
				$(targetdivclass).hide('normal');
			}
			
			if(option.hide == true) {
				if(lastchosen == targetdiv) {
					lastchosen = null;
					return;
				}
			}
			
			$(targetdiv).toggle('normal');
			lastchosen = targetdiv;
		});
	});
	
	if(option.defaultpanel) {
		$(option.defaultpanel).show();
	}
}

GabeUtil.ajaxRequest = function(method, url, option, datatype, params) {
	/*
		for option
		on<STATUS> = callback function for status message
		onLoad = if not json
		confirm = confirmation message
		if confirm is set, ask for the confirmation
	*/
	
	if(!option) {
		option = {};
	}
	
	if(!params) {
		params = {};
	}
	
	if(!datatype) {
		datatype = null;
	}
	
	if(option.confirm) {
		var conf = confirm(option.confirm);
		if(!conf) {
			return false;
		}
	}
	
	jQuery.get(url, {}, function(response) {
	
		if(datatype == 'json') {
			if(response.message) {
				alert(response.message);
			}
			if(response.status) {
				if(option['on' + response.status.toUpperCase()]) {
					option['on' + response.status.toUpperCase()](response);
					return;
				}
			}
		}
		
		if(option.onLoad) {
			option.onLoad(response);
		}
		
	}, datatype);
	
}

GabeUtil.htmlDecode = function(val) {
	return val.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
}

GabeUtil.padding = function(val, length, padding) {
	
	if(!length) {
		length = 2;	
	}
	
	if(!padding) {
		padding = '0';	
	}
	
	val = val + '';
	var numpads = length - val.length;
	var pads = '';
	for(var i = 0; i < numpads; i++) {
		pads += padding;
	}
	
	return pads + val;
	
}

GabeUtil.getArgs = function() {
    var args = new Object( );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}

GabeUtil.registerActiveSearchForm = function(form, result, option) {
	
	if(typeof form == 'string') {
		form = document.getElementById(form);
	}	
	
	if(typeof result == 'string') {
		result = document.getElementById(result);
	}
	
	if(!option) {
		option = {};	
	}
	
	if(!option.successCallback) {
		option.successCallback = function(response) {
			
		}	
	}
	
	if(!option.beforeCallback) {
		option.beforeCallback = function(oform) {	
			return true;
		}	
	}
	
	if(!option.enableRetry && !option.allowRetry) {
		// by default, don't let the client resubmit the form while it's pulling data
		option.enableRetry = false;
	}
	
	if(option.allowRetry) {
		option.enableRetry = true;
	}
	
	var accessing = false;

	var triggerSubmit = function() {
		//alert($("input[name='currPage']", $(form)).val());
		
		var submitbuttons = null;
		
		if(option.hideSubmit) {
			var submitbuttons = {};
		
			jQuery.each($("input[type='submit']", $(form)), function(i, val) {
				submitbuttons['btn' + i] = $(val).val();
				$(val).val('Loading...');
				$(val).attr('disabled', true);
			});
		}
		
		
		$(form).ajaxSubmit({
			beforeSubmit : function(adata, aform, opt) {
				if(!option.enableRetry && accessing == true) {
					return false;	
				}
				$(result).html("<center><img src='" + GabeUtil.loadingImage + "' /><br />" + "Loading your request...<br />Please wait...</center>");
				if(option.beforeCallback) {
					var res = option.beforeCallback(aform);
					if(res == false) {
						return false;
					}
				}
				// currently pulling the data
				accessing = true;
				return true;
			},
			success : function(response) {
				accessing = false;
				if(submitbuttons && option.hideSubmit) {
					jQuery.each($("input[type='submit']", $(form)), function(i, val) {
						$(val).val(submitbuttons['btn' + i]);
						$(val).attr('disabled', false);
					});
				}
				$(result).html(response);
				GabeUtil.registerActivePages(form, result, triggerSubmit);
				option.successCallback(response);
			}
		});		
	}
	
	$(form).submit(function(event) {
		event.preventDefault();
		$("input[name='currPage']", $(form)).val('1');
		triggerSubmit();
	});
	
	return triggerSubmit;
	
}

GabeUtil.registerActivePages = function(form, container, callback) {
	
	$("a.pagPageLink", $(container)).click(function(event) {
		event.preventDefault();
		var currPage = ($(this).attr('href').match(/currPage=([0-9]+)/i));
		currPage = currPage[1];
		//alert(currPage);
		$("input[name='currPage']", $(form)).val(currPage);
		callback($(this));
	});
	
	$("a.orderbyLink").click(function(event) {
		event.preventDefault();
		var currPage = ($(this).attr('href').match(/currPage=([0-9]+)/i));
		if(currPage == null) {
			currPage = 1;	
		} else {
			currPage = currPage[1];
		}	
		$("input[name='currPage']", $(form)).val(currPage);
		var orderBy = ($(this).attr('href').match(/order_by=([^&]+)/i));
		//alert($(this).attr('href'));
		orderBy = orderBy[1];
		//alert(orderBy);
		$("input[name='order_by']", $(form)).val(orderBy);
		callback($(this));
	});
	
	$("select[name='recPerPage']", $(container)).change(function(event) {
		$("input[name='recPerPage']", $(form)).val($(this).val());
		$("input[name='currPage']", $(form)).val('1');
		callback($(this));
	});
	
}

GabeUtil.screenDimLoadingIntId = 0;

GabeUtil.updateDimLoading = function(callback) {
	callback();
	GabeUtil.centerElementToWindow(GabeUtil.scDimLoading);
}

GabeUtil.screenDimLoadingStopClose = false;
GabeUtil.screenDimLoadingSetStopClose = function(bool) {
	GabeUtil.screenDimLoadingStopClose = bool;
}

GabeUtil.screenDimLoading = function(activate, element, callback) {
	
	if(!callback) {
		callback = function(div) {}
	}
	
	if(!element) {
		element = null;	
	}
	
	clearInterval(GabeUtil.screenDimLoadingIntId);	
	
	if(GabeUtil.scDimLoading === null) {
		GabeUtil.scDimLoading = document.createElement("div");
		//GabeUtil.scDimLoading.style.width = '600px';
		GabeUtil.scDimLoading.id = "gabeUtilScDimLoading";
		GabeUtil.scDimLoading.style.border = "#cccccc 5px solid";
		GabeUtil.scDimLoading.style.backgroundColor = "#ffffff";
		GabeUtil.scDimLoading.style.padding = "10px";
		GabeUtil.scDimLoading.style.position = "absolute";
		GabeUtil.scDimLoading.style.left = "0px";
		GabeUtil.scDimLoading.style.display = "none";
		GabeUtil.scDimLoading.style.zIndex = 100;
		GabeUtil.scDimLoading.style.minWidth = '300px';
		GabeUtil.scDimLoading.style.minHeight = '150px';
		//GabeUtil.scDimLoading.style.maxHeight = '600px';
		GabeUtil.scDimLoading.style.overflow = 'auto';

		document.body.appendChild(GabeUtil.scDimLoading);
		
	}
	
	var scLoad = GabeUtil.scDimLoading;
	
	if(activate == true) {
		
		GabeUtil.scDimLoading.style.width = 'auto';
		
		var opac = 0;
		GabeUtil.setOpacity(scLoad, opac);
		
		scLoad.className = '';
		
		if(element === null) {
			element = "<center><img src='/templates/vwztemplates/images/loadingAnimation.gif' /><br />Processing your Request...<br />Please wait...</center>";
		}
		
		if(element == 'same') {
			// Just display again with same content
		} else if(typeof element == 'string') {
			scLoad.innerHTML = element;
			//GabeUtil.scDimLoading.innerHTML = element;
		} else {
			scLoad.innerHTML = '';
			scLoad.appendChild(element);
			//GabeUtil.scDimLoading.innerHTML = '';
			//GabeUtil.scDimLoading.appendChild(element);
		}
		
		var scrollTop = $(document).scrollTop();
		var screenWidth = $(document.body).outerWidth();
		
		//alert(screenWidth);
		GabeUtil.scDimLoading.style.top = (scrollTop + 5) + "px";
			
		var showScreenDim = function(scDim) {
		
			GabeUtil.scDimLoading.style.display = "block";
			//alert(callback);
			callback(scLoad);
			GabeUtil.scDimLoading.scrollTop = 0;
			
			var myWidth = $(GabeUtil.scDimLoading).outerWidth();
			
			//alert(myWidth);
			//alert(screenWidth);
			GabeUtil.scDimLoading.style.left = (screenWidth / 2 - myWidth / 2) + "px";
			//scLoad.style.width = scLoad.scrollWidth + "px";
			GabeUtil.setOpacity(scLoad, 1);
			
			GabeUtil.scDimLoading.style.width = myWidth + 'px';
			
			/*
			GabeUtil.screenDimLoadingIntId = setInterval(function() {
										opac += .30
										//alert(opac);
										if(opac > 1) {
											clearInterval(GabeUtil.screenDimLoadingIntId);
										}
										GabeUtil.setOpacity(scLoad, opac);
										}, 1);*/
			
		}
		
		showScreenDim();
		GabeUtil.screenDim();
		
		
	} else {
		
		if(GabeUtil.screenDimLoadingStopClose) {
			return scLoad;	
		}
		
		clearInterval(GabeUtil.screenDimLoadingIntId);
		GabeUtil.stopScreenDim();
		GabeUtil.scDimLoading.style.display = "none";
		//alert(GabeUtil.scDimLoading.style.display);
		
	}
	
	return scLoad;
	
}

GabeUtil.screenDim = function(callback) {
		
	if(!callback) {
		callback = function(div) {}
	}
	
	var dim = .70;
	if(GabeUtil.scDim === null) {
		var div = document.createElement("div");
		div.id = "gabeUtilScreenDim";
		div.style.backgroundColor = "#000000";
		div.style.opacity = dim;
		div.style.filter = "alpha(opacity=" + (dim * 100) + ")";
		div.style.position = "absolute";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.zIndex = 90;
		GabeUtil.scDim = div;
		GabeUtil.scDim.style.display = 'none';
		document.body.appendChild(GabeUtil.scDim);
	}
	
	var height = ($(document.body).outerHeight());
	var width =  ($(document.body).outerWidth());
	
	var height = document.body.scrollHeight;
	var width =  document.body.scrollWidth;
	
	//GabeUtil.scDim.style.height = '0px';
	GabeUtil.scDim.style.width = width + "px";
	GabeUtil.setOpacity(GabeUtil.scDim, dim);	
	GabeUtil.scDim.style.height = height + 'px';
	GabeUtil.scDim.style.display = 'block';
	
	/*
	var intId = null;
	var oheight = 0;
	var opac = .10;
	GabeUtil.scDim.style.height = height + 'px';
	GabeUtil.scDim.style.display = 'block';
	intId = setInterval(function() {
									GabeUtil.setOpacity(GabeUtil.scDim, opac);			 
									opac += parseFloat(opac) + .10;
									if(opac > 1) {
										clearInterval(intId);
										callback(GabeUtil.scDim);
									}
								 }, 1);
	*/
	
	
	
	//alert('ok!');
	/*

	intId = setInterval(function() {
								oheight += 30;
								//alert(oheight);
								GabeUtil.scDim.style.height = oheight + 'px';
								if(oheight > height) {
									clearInterval(intId);
									callback(GabeUtil.scDim);
								}
								}, 1);
	*/
}

GabeUtil.stopScreenDim = function(opts) {
	if(!opts) {
		opts = {};	
	}	
	if(GabeUtil.scDim !== null) {
		GabeUtil.scDim.style.display = 'none';
	}
	
}

GabeUtil.attachFieldToCheckboxes = function(fieldId, chkName) {
	$("input[type='checkbox'][name='" + chkName + "']").click(function(event) {
		var values = new Array();
		jQuery.each($("input[type='checkbox'][name='" + chkName + "']:checked"), function(i, val) {
			values.push($(val).val());
		});
		document.getElementById(fieldId).value = values.join();
	});
}

GabeUtil.checkAll = function(elements, check) {
	if(typeof check == 'undefined') {
		check = true;	
	}
	for(var i = 0; i < elements.length; i++) {
		elements[i].checked = check;
	}
	return;
}


GabeUtil.floatingDivs = new Array();

GabeUtil.addFloatingDiv = function(div) {
	GabeUtil.floatingDivs.push(div);
}

GabeUtil.removeFloatingDivs = function() {
	for(var i = 0; i < GabeUtil.floatingDivs.length; i++) {
		GabeUtil.floatingDivs[i].parentNode.removeChild(GabeUtil.floatingDivs[i]);
	}
	return;
}

GabeUtil.removeFloatingDiv = function(div) {
	var temp = new Array();
	for(var i = 0; i < GabeUtil.floatingDivs.length; i++) {
		if(div === GabeUtil.floatingDivs[i]) {
			GabeUtil.floatingDivs[i].parentNode.removeChild(GabeUtil.floatingDivs[i]);
		} else {
			temp.push(GabeUtil.floatingDivs[i]);	
		}
	}
	GabeUtil.floatingDivs = temp;
}

GabeUtil.elementsPopulated = function(name, form) {
	var elements = form.elements;
	var len = elements.length;
	for(var i = 0; i < len; i++) {
		if(elements[i].value == '' && name == elements[i].name) {
			return false;
		}
	}
	return true;
}


GabeUtil.inArray = function(array, key) {
	for(var i = 0; i < array.length; i++) {
		if(array[i] == key) {
			return i;
		}
	}
	return false;
}

GabeUtil.isChecked = function(buttons) {
	for(var i = 0; i < buttons.length; i++) {
		if(buttons[i].checked) {
			return true;
		}
	}
	return false;
}

GabeUtil.getRadioValue = function(name) {
	var elements = document.getElementsByName(name);
	for(var i = 0; i < elements.length; i++) {
		if(elements[i].checked == true) {
			return elements[i].value;
		}
	}
	return false;
}

GabeUtil.limitWords = function(text, limit) {
	var texts = text.split(" ");
	var newt = texts.slice(0, limit);
	return newt.join(" ");
}

GabeUtil.getElementsByName = function(parent, name) {
	
	if(typeof parent == 'undefined') {
		parent = document.body;
	}
	
	var children = parent.childNodes;
	var len = children.length;
	var matches = new Array();
	for(var i = 0; i < len; i++) {
		if(children[i].name == name) {
			matches.push(children[i]);
		}
	}
	
	return matches;
}

GabeUtil.setMaxLength = function(field, maxlen, callback) {
	
	if(typeof callback != 'function' || typeof callback == 'undefined') {
		callback = function(remaining) {
		}
	}
	
	var len;
	var handle = function(e) {
		len = field.value.length;
		//field.value = field.value.substr(0, maxlen);
		var rem = maxlen - len;
		callback(rem);
	}
	
	GabeUtil.addEventListener(field, "keyup", handle, false);
	
}

GabeUtil.sliderHorizontal = function(parent, width, height, increment, groupObj, leftImg, rightImg) {

	var innerTable = document.createElement("table");
	innerTable.cellSpacing = '0px';
	innerTable.cellPadding = '0px';
	innerTable.border = '0px';
	var innerTbody = document.createElement("tbody");
	var innerRow = document.createElement("tr");
	innerTable.appendChild(innerTbody);
	innerTbody.appendChild(innerRow);
	var innerTd = document.createElement("td");
	innerTd.appendChild(groupObj);
	innerRow.appendChild(innerTd);
	
	var div = document.createElement("div");
	div.style.width = width + "px";
	div.style.height = height + "px";
	div.style.border = "#000000 1px solid";
	div.style.overflow = "hidden";
	div.appendChild(innerTable);
	
	var leftIcon = new Image();
	leftIcon.src = leftImg;
	var rightIcon = new Image();
	rightIcon.src = rightImg;
	
	var table = document.createElement("table");
	table.width = (leftIcon.width + rightIcon.width + width) + "px";
	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	var row = document.createElement("tr");
	var leftTd = document.createElement("td");
	var centerTd = document.createElement("td");
	var rightTd = document.createElement("td");
	tbody.appendChild(row);
	row.appendChild(leftTd);
	row.appendChild(centerTd);
	row.appendChild(rightTd);
	
	leftTd.appendChild(leftIcon);
	centerTd.appendChild(div);
	rightTd.appendChild(rightIcon);
	
	parent.appendChild(table);
	
	var lastCopy = innerTd;
	
	leftIcon.onclick = function(e) {
		if(div.scrollLeft == 0) {
			var origWidth = div.scrollWidth;
			var copy = innerTd.cloneNode(true);
			lastCopy = innerRow.insertBefore(copy, lastCopy);
			var diff = div.scrollWidth - origWidth;
			div.scrollLeft = diff;
		}
		
		var countIncrement = 0;
		var intId = setInterval(	function() {
										countIncrement++;
										//alert(div.scrollLeft);
										div.scrollLeft -= 1;
										if(countIncrement == increment) {
											clearInterval(intId);
										}					
									},
									2
		);
	}
	
	rightIcon.onclick = function(e) {
	
		if(div.scrollWidth == (div.scrollLeft + width)) {
			var copy = innerTd.cloneNode(true);
			innerRow.appendChild(copy);
		}
		
		var countIncrement = 0;
		var intId = setInterval(	function() {
										countIncrement++;
										//alert(div.scrollLeft);
										div.scrollLeft += 1;
										if(countIncrement == increment) {
											clearInterval(intId);
										}					
									},
									2
		);
	}
	return table;
}

GabeUtil.getInputElement = function(type, value, name, id) {
	
	if(typeof name == "undefined") {
		name = '';	
	}
	
	if(typeof id == "undefined") {
		id = '';	
	}
	
	var element = document.createElement("input");
	element.type = type;
	element.value = value;
	element.name = name;
	element.id = id;
	return element;
	
}

GabeUtil.getFloatingDiv = function(e, width, height, className) {
	
	e = GabeUtil.getEvent(e);
	var pos = GabeUtil.getMousePos(e);
	var widthOffset = 30;
	var top = 0;

	var div = document.createElement("div");
	div.style.height = "10px";
	div.style.width = "10px";
	div.style.position = "absolute";
	div.style.zIndex = 9;
	div.style.overflow = "hidden";
	div.style.display = 'none';
	document.body.appendChild(div);
	
	if(typeof className != "undefined") {
		div.className = className;	
	}
	
	div.displayDiv = function() {
		
		// The content has already been set.  Now it's time to display the div.
		
		div.style.display = 'block';
		
		if(	(height == null) || 
			(typeof height == "undefined")
			) {
			height = div.scrollHeight;
		}
		
		if(	(width == null) || 
			(typeof width == "undefined")
			) {
			width = div.scrollWidth;
		}
		
		top = (pos.y - height + 30);
		if(top < 10) {
			top = 20;
		}
		div.style.top = top + "px";
		div.style.left = (pos.x - widthOffset) + "px";
		
		GabeUtil.slideRight(div, width);
		GabeUtil.slideDown(div, height);
		
	}
	
	return div;
	
}

GabeUtil.imagePreloader = function(parent, imageUrl, preloaderUrl) {
	
	var myDate = new Date();
	var preloaderImg = new Image();
	preloaderImg.src = preloaderUrl;
	parent.appendChild(preloaderImg);
	
	var text = document.createTextNode("Loading...");
	parent.appendChild(text);
	
	var aimage = new Image();
	aimage.src = imageUrl + "?ts=" + myDate.getTime();
	aimage.onload = function(e) {	
		parent.removeChild(preloaderImg);
		parent.removeChild(text);
		parent.appendChild(aimage);
	}
	
}

GabeUtil.registerSlideDown = function(button, element, minHeight, maxHeight, closed) {
	
	if(typeof closed == 'undefined') {
		closed = true;
		element.style.overflow = 'hidden';
	}
	//alert(button);
	button.onclick = function(e) {
		if(closed == true) {
			element.style.overflow = 'hidden';
			GabeUtil.slideDown(element, maxHeight, function() {
																closed = false;
																element.style.overflow = 'auto';
															});
		} else {
			element.style.overflow = 'hidden';
			GabeUtil.slideDownClose(element, minHeight, function() {
																 	closed = true;
																 });
		}
	}
	
}

GabeUtil.slideDown = function(element, maxHeight, callback) {

	if(typeof maxHeight == 'undefined') {
		maxHeight = element.scrollHeight;
	}
	var intId;
	
	intId = setInterval(	function() {
								if(parseInt(element.style.height, 10) >= maxHeight) {
									element.style.height = maxHeight + "px";
									clearInterval(intId);
									if(typeof callback != 'undefined') {
										callback();
									}
									return;
								}
								element.style.height = (parseInt(element.style.height, 10) + 20) + "px";
							}, 
							10);
}

GabeUtil.slideRight = function(element, maxWidth, callback) {

	if(typeof maxWidth == 'undefined') {
		maxWidth = element.scrollWidth;
		maxWidth = 300;
	}
	var intId;
	
	intId = setInterval(	function() {
								if(parseInt(element.style.width, 10) >= maxWidth) {
									element.style.width = maxWidth + "px";
									clearInterval(intId);
									if(typeof callback != 'undefined') {
										callback();
									}
									return;
								}
								element.style.width = (parseInt(element.style.width, 10) + 20) + "px";
							}, 
							10);
}

GabeUtil.slideDownClose = function(element, minHeight, callback) {
	
	if(typeof minHeight == 'undefined') {
		minHeight = 10;
	}
	
	var intId;
	
	intId = setInterval(	function() {
								if(parseInt(element.style.height, 10) <= minHeight) {
									
									element.style.height = minHeight + "px";
									clearInterval(intId);
									if(typeof callback != 'undefined') {
										callback();
									}
									return;
								}
								element.style.height = (parseInt(element.style.height, 10) - 20) + "px";
							}, 
							10);
}

GabeUtil.expandImage = function(img, url) {
	var newImg = document.createElement("img");
	newImg.src = url;
	newImg.style.position = 'absolute';
	var pos = GabeUtil.getAbsolutePos(img);
	var offsetx = Math.ceil((newImg.width - img.width) / 2);
	var offsety = Math.ceil((newImg.height - img.height) / 2);
	newImg.style.left = (pos.x - offsetx) + 'px';
	newImg.style.top = (pos.y - offsety) + 'px';
	document.body.appendChild(newImg);
	
	newImg.onmouseout = function(e) {
		newImg.parentNode.removeChild(newImg);
	}
}

GabeUtil.confirmRedirect = function(location, message) {
	
	if(typeof message == 'undefined') {
		message = 'Continue?';	
	}
	
	if(confirm(message)) {
		window.location = location;
	}
	
	return false;
}


GabeUtil.registerFlyoutBottom = function(parent, element) {
	
	parent.onmouseover = function(e) {
		//var pos = GabeUtil.getAbsolutePos(parent);
		//element.style.position = 'absolute';
		element.style.top = 'auto';
		element.style.left = 'auto';
		element.style.zIndex = 5;
	}
	
	parent.onmouseout = function(e) {
		element.style.top = '-100em';
	}
	
}

GabeUtil.numericOnly = function(field) {
	
	var allowed = "0123456789.";
	var len;
	var value;
	var char;
	var newvalue;
	
	var filter = function(e) {
		newvalue = '';
		e = GabeUtil.getEvent(e);
		len = field.value.length;
		value = field.value;
		for(var i = 0; i < len; i++) {
			char = value.substr(i, 1);
			if(allowed.indexOf(char) != -1) {
				newvalue += char;
			}
		}
		field.value = newvalue;
	}
	
	GabeUtil.addEventListener(field, "keyup", filter, false);
	
}

GabeUtil.createTable = function(doc, cols, rows, className) {
	var table = doc.createElement("table");
	var tbody = doc.createElement("tbody");
	if(className) {
		table.className = className;	
	}
	table.border = "1px";
	for(var i = 0; i < rows; i++) {
		var newRow = doc.createElement("tr");
		for(var j = 0; j < cols; j++) {
			var newCell = doc.createElement("td");	
			newCell.innerHTML = "&nbsp;";
			newRow.appendChild(newCell);
		}
		tbody.appendChild(newRow);
	}
	table.appendChild(tbody);
	return table;
}

/*
	Gets elements by class name
*/
GabeUtil.getElements = function(aparent, tagName, className) {
	
	if((typeof tagName == "undefined") || (tagName == null)) {
		// No tagName specified
		tagName = "*";
	}
	
	var temp = aparent.getElementsByTagName(tagName);
	var tempLen = temp.length;
	var elements = [];
	
	for(var i = 0; i < tempLen; i++) {
		if(typeof temp[i] == "object") {
			elements.push(temp[i]);
		}
	}
	
	if(typeof className != "undefined") {
		// Class name was specified
		for(var i = 0; i < elements.length; i++) {
			if(	(elements[i].className.indexOf(className) == -1) || 
				(typeof elements[i].className == "undefined")
				) {
				//alert(elements[i].className);
				elements.splice(i, 1);
				--i;
			}
		}
	}
	
	return elements;
	
}

/*
	Determines if internet browser is IE.
*/
GabeUtil.isIE = function() {
	if(typeof window.addEventListener == "undefined") {
		return true;
	}	
	return false;
}

/*
	Adds an event listener to an element
*/
GabeUtil.addEventListener = function(aelement, action, afunction, bool) {
	if(typeof aelement.addEventListener == "function") {
		aelement.addEventListener(action, afunction, bool);	
	} else {
		aelement.attachEvent("on" + action, afunction);
	}
}

/*
	Removes an event listener from an element.
*/
GabeUtil.removeEventListener = function(aelement, action, afunction, bool) {
	if(typeof aelement.addEventListener == "function") {
		aelement.removeEventListener(action, afunction, bool);	
	} else {
		aelement.detachEvent("on" + action, afunction);
	}
}

/*
	Generalizes the event object.
*/
GabeUtil.getEvent = function(e) {
	if(window.event) {
		//alert("windows!");
		e = window.event;
		e.target = e.srcElement;
		e.preventDefault = function() {
			e.returnValue = false;
		}
		if(e.type == 'mouseover' || e.type == 'mouseout') {
			e.relatedTarget = e.toElement;
		}
	}
	return e;
}

GabeUtil.getScrollPos = function() {
	var pos = {};
	if(!GabeUtil.isIE()) {
		// Mozilla
		pos.x = window.pageXOffset;
		pos.y = window.pageYOffset;
	} else {
		if(typeof document.documentElement.scrollLeft != "undefined") {
			pos.x = document.documentElement.scrollLeft;
			pos.y = document.documentElement.scrollTop;
		} else {
			pos.x = document.body.scrollLeft;
			pos.y = document.body.scrollTop;
		}
	}
	return pos;
}

GabeUtil.getMousePos = function(e) {
	var pos = {};
	var wscroll = GabeUtil.getScrollPos();
	pos.x = wscroll.x + e.clientX;
	pos.y = wscroll.y + e.clientY;
	return pos;
}

GabeUtil.getAbsolutePos = function(element) {
	var offset = {};
	offset.x = 0;
	offset.y = 0;
	while(element != null) {
		offset.x += parseInt(element.offsetLeft, 10);
		offset.y += parseInt(element.offsetTop, 10);
		element = element.offsetParent;
	}
	return offset;
}

GabeUtil.moveElementVertical = function(aelement, newPos, cPos) {
	
	aelement.style.position = "absolute";
	
	if(typeof cPos != "undefined") {
		aelement.style.top = cPos + "px";	
	}
	
	var currPos = parseInt(aelement.style.top, 10);
	
	var tempPos = 0;
	var callback = null;
	var intId = null;
	if(newPos > currPos) {
		callback = function() {
			tempPos = (parseInt(aelement.style.top, 10) + 10);
			aelement.style.top =  tempPos + "px";
			if(tempPos >= newPos) {
				clearInterval(intId);	
			}
		}
	} else {
		callback = function() {
			tempPos = (parseInt(aelement.style.top, 10) - 10);
			aelement.style.top =  tempPos + "px";
			if(tempPos <= newPos) {
				clearInterval(intId);	
			}
		}
	}
	
	intId = setInterval(function() { callback(); }, 20);
	
}

GabeUtil.populateDropdownWithObj = function(dropdown, obj) {
	for(var key in obj) {
		dropdown.options[dropdown.length] = new Option(obj[key], key, false, false);
	}
	return true;
}

GabeUtil.getTextMatchesObj = function(text, obj) {
	var matches = {};
	for(var key in obj) {
		//alert(obj[key].indexOf(text));
		if(obj[key].toLowerCase().indexOf(text.toLowerCase()) != -1) {
			matches[key] = obj[key];	
		}
	}
	return matches;
}

GabeUtil.populateDropdownWithMatch = function(text, dropdown, obj) {
	var matches = GabeUtil.getTextMatchesObj(text, obj);
	GabeUtil.populateDropdownWithObj(dropdown, matches);
}

GabeUtil.registerActiveDropdownSearch = function(	textInput, 
												 	dropdown, 
													callback /* that should return an object with key value pairs to populate dropdown */) {
	
	var obj = null;
	var timeoutId = null;
	
	textInput.onkeyup = function(e) {
		
		clearTimeout(timeoutId);
		
		timeoutId = setTimeout(	function() {

											obj = callback();
											dropdown.options.length = 0;
											
											if(textInput.value.length >= 1) {
												GabeUtil.populateDropdownWithMatch(textInput.value, dropdown, obj);
											} else {
												//GabeUtil.populateDropdownWithObj(dropdown, obj);
											}
											
											if(dropdown.selectedIndex >= 0) {
												textInput.value = dropdown.options[dropdown.selectedIndex].value;
												dropdown.style.display = 'inline';
											} else {
												dropdown.style.display = 'none';
											}
										 
										}, 500
						   	); 
		
		
		
	}
	
	dropdown.onchange = function(e) {
		if(dropdown.selectedIndex >= 0) {
			textInput.value = dropdown.options[dropdown.selectedIndex].value;
		}
	}
	
	return true;
	
}

GabeUtil.setOpacity = function(element, opacityVal) {
	if('opacity' in element.style) {
		element.style.opacity = opacityVal;
	} else {
		element.style.filter = "alpha(opacity=" + (opacityVal * 100) + ")";	
	}
}

GabeUtil.getOpacity = function(element) {
	if('opacity' in element.style) {
		return element.style.opacity;
	} else {
		var opacity = element.style.filter.replace("alpha(opacity=", '');
		opacity = parseInt(opacity.replace(")", '')) / 100;
		if(isNaN(opacity)) {
			opacity = '';	
		}
		return opacity;
	}
}

GabeUtil.fadeOut = function(element, fadeEnd, callback, fadeStart, speed, increment) {
	// default fadeStart == 1
	var elementOpacity = GabeUtil.getOpacity(element);
	if(typeof fadeStart == 'undefined' || fadeStart === null) {
		if(elementOpacity !== '') {
			fadeStart = elementOpacity;
		} else {
			fadeStart = 1;
		}
	}
	return GabeUtil.fadeEffect(element, fadeEnd, callback, fadeStart, speed, increment);
}

GabeUtil.fadeIn = function(element, fadeEnd, callback, fadeStart, speed, increment) {

	// default fadeStart == 0
	var elementOpacity = GabeUtil.getOpacity(element);
	if(typeof fadeStart == 'undefined' || fadeStart === null) {
		if(elementOpacity !== '') {
			fadeStart = elementOpacity;
		} else {
			fadeStart = 0;
		}
	}
	return GabeUtil.fadeEffect(element, fadeEnd, callback, fadeStart, speed, increment);
}

GabeUtil.fadeEffect = function(element, fadeEnd, callback, fadeStart, speed, increment) {
	
	if(typeof increment == 'undefined' || increment === null) {
		increment = .10;
	}
	
	if(typeof speed == 'undefined' || speed === null) {
		speed = 50;
	}

	var addTo = function(n1, n2) {
		return parseFloat(n1) + parseFloat(n2);
	}
	
	var minusFrom = function(n1, n2) {
		return  parseFloat(n1) -  parseFloat(n2);
	}
	
	var toExec;
	
	if(fadeEnd > fadeStart) {
		toExec = addTo;
	} else {
		toExec = minusFrom;
	}
	
	GabeUtil.setOpacity(element, fadeStart);
	
	var fadeIntId = setInterval(	function() {
										if(GabeUtil.getOpacity(element) == fadeEnd) {
											clearInterval(fadeIntId);
											return;
										}
										//element.innerHTML = element.style.opacity;
										GabeUtil.setOpacity(element, toExec(GabeUtil.getOpacity(element), increment));
									},
									speed
									);
	return fadeIntId;
	
}

GabeUtil.registerFadeInOut = function(element, fadeEnd, callback, fadeStart, speed, increment) {

	var fadeIntId;
	
	element.onmouseover = function(e) {
		clearInterval(fadeIntId);
		fadeIntId = GabeUtil.fadeIn(element, fadeEnd, callback, fadeStart, speed, increment);	
	}
	
	element.onmouseout = function(e) {
		clearInterval(fadeIntId);
		fadeIntId = GabeUtil.fadeOut(element, fadeStart, callback, fadeEnd, speed, increment);
	}
}

GabeUtil.getWindowInfo = function() {
	var info = {};
	if(typeof window.innerWidth != 'undefined') {
		info.innerWidth = window.innerWidth;
		info.innerHeight = window.innerHeight; 
	} else {
		if(!document.documentElement && !document.documentElement.clientWidth) {
			info.innerWidth = document.body.clientWidth;
			info.innerHeight = document.body.clientHeight;
		} else {
			info.innerWidth = document.documentElement.clientWidth;
			info.innerHeight = document.documentElement.clientHeight;
		}
	}
	return info;
}

GabeUtil.getElementSize = function(element) {
	
	var specs = {};
	
	if(element.style.width === '') {	
		specs.width = parseInt(element.scrollWidth);
	} else {
		specs.width = parseInt(element.style.width);
	}
	
	if(element.style.height === '') {		
		specs.height = parseInt(element.scrollHeight);
	} else {
		specs.height = parseInt(element.style.height);
	}
	
	return specs;
	
}

GabeUtil.centerElementToWindow = function(element) {
	var elementSize = GabeUtil.getElementSize(element);
	var windowInfo = GabeUtil.getWindowInfo();
	var scrollPos = GabeUtil.getScrollPos();
	var offsetLeft = Math.round((windowInfo.innerWidth - parseInt(elementSize.width)) / 2);
	element.style.left = offsetLeft + "px";
	if(parseInt(elementSize.height) >= windowInfo.innerHeight) {
		element.style.top = (scrollPos.y + 15) + "px";	
	} else {
		var offsetTop = Math.round((windowInfo.innerHeight - parseInt(elementSize.height)) / 2);
		element.style.top = ((offsetTop - 50) + scrollPos.y) + "px";	
	}
}
