// Function to accomodate IE and FF event model
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
	 	obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}
function stopEvent(event) {
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	} else {
		event.returnValue = false;
		event.cancelBubble = true;
	}
}

/* Check Existence Of Drag Registry */
if (typeof window.dragRegistry != 'object') {
	window.dragRegistry = {};
}

/* DEALERPEAK DHTML POPUP WINDOW */
function dpPopup(_url,_name,_title,_width,_height,_top,_left,_skin) {
	var winName = 'dpPopup'+_name;
	if(!document.getElementById(winName)) {
		/* Use a passed in Skin? */
		if (typeof _skin != 'undefined') {
			var skin = _skin;
		} else {
			var skin = {
				topLeft: 'WinUpLeft',
				topCenter: 'WinUpCenter',
				topRight: 'WinUpRight',
				midLeft: 'WinMidLeft',
				midCenter: 'WinMidCenter',
				midRight: 'WinMidRight',
				botLeft: 'WinLowLeft',
				botCenter: 'WinLowCenter',
				botRight: 'WinLowRight',
				closeSrc: '/Skin/AgentTemplates/Generic/Images/b_x.gif',
				closeStyle: 'margin:10px 0px 0px -2px',
				closeValign: 'center'
			};
		}
		/* Build The "Window" Style Container */
		var mContainer = Builder.node("div", {id:winName,style:"z-index: 500; position:absolute; top:"+(getScrollTop()+_top)+"px; left:"+_left+"px; width:"+_width+"px; height:"+_height+"px;"}, [
			/* required to hide select boxes in older browser IE6 */
			Builder.node("iframe", {src:"javascript:false;", frameborder:"0", scrolling:"no", id:winName+"shimFrame", style:"width:"+(_width-46)+"px; height:"+(_height-2)+"px;margin:16px 0px 0px 15px; z-index:-1; position:absolute; display:visible;"},""),
			Builder.node("table", {cellpadding:0,cellspacing:0,border:0,width:'100%',height:'100%'}, [
				Builder.node("tbody", {}, [
					Builder.node("tr", {}, [
						Builder.node("td", {className:skin['topLeft']}, ' '),
						Builder.node("td", {className:skin['topCenter'],id:winName+"Title"}, _title),
						Builder.node("td", {id:winName + "x",className:skin['topRight'], vAlign:skin['closeValign']}, [
							Builder.node("img", {src:skin['closeSrc'],style:skin['closeStyle']},"")
						])
					]),
					Builder.node("tr", {}, [
						Builder.node("td", {className:skin['midLeft']}, ' '),
						Builder.node("td", {className:skin['midCenter'],id:winName+"ContentTD", vAlign:"top", height:(_height-38)}, [
							Builder.node("div", {id:winName+"Content",style:"position:relative;width:100%;height:"+(_height-38)+"px;height:expression(this.scrollHeight>"+(_height-38)+"?'"+(_height-38)+"px':'100%');overflow:auto;background-color:FFFFFF;"}, "")
						]),
						Builder.node("td", {className:skin['midRight']}, ' ')
					]),
					Builder.node("tr", {}, [
						Builder.node("td", {className:skin['botLeft']}, ' '),
						Builder.node("td", {className:skin['botCenter']}, ' '),
						Builder.node("td", {className:skin['botRight']}, ' ')
					])
				])
			])
		]);
		
		/* Add The "Window" Style Container To The DOM */
		document.body.appendChild(mContainer);
		
		/* I guess we had to do this for IE 6 :-( */
		$(winName + 'x').onclick = function(){	
			dpPopupClose(_name);
		}
	}
	
	/* Scroll view pane to the top */
	$(winName+"Content").scrollTop = 0;
	
	/* Empty array to put functions in for calling after load */
	$(winName).afterLoadArray = [];
	
	/* Function to call any listeners after content is loaded */
	$(winName).afterLoad = function() {
		var listeners = $(winName).afterLoadArray;
		for (var i=0; i<listeners.length; i++) { 
			var listener = listeners[i];
			listener.call(listener, null); 
			//alert('Calling: ' + listener.toString())
		}
		/* Clear afterLoadArray */
		$(winName).afterLoadArray = [];
		/* Set "loading" flag to false */
		$(winName).loading = false;
		//alert('$(winName).afterLoad');
	}
	
	/* Get Contents And Fill */
	if (typeof _url == 'string' && _url.length > 0) {
		var ts = new Date();
		var pars = '&TS=' + ts.toString();
		$(winName).loading = true;
		var ajaxCall = new Ajax.Updater(
			winName+"Content",
			_url,
			{
				evalScripts: true,
				method: 'get',
				parameters: pars,
				asynchronous: true,
				onComplete: function(){
								window.setTimeout("$('"+winName+"').afterLoad()",10);
							}
			}
		);
	} else {
		$(winName).loading = false;
	}
	
	/* Make Container Draggable */
	window.dragRegistry[winName] = new Draggable(winName,{handle:winName+'Title',starteffect:null,endeffect:null});
	
	/* Store Original Window Args */
	$(winName).dpParams = {
		url:_url
		,name:_name
		,title:_title
		,width:_width
		,height:_height
		,top:_top
		,left:_left
		,skin:_skin
	};
	
	/* WINDOW FUNCTIONS */
	
	$(winName).addCloseEvent = function(_function) {
		if (typeof(_function)=='function') {
			if (typeof(this.CloseEvents)=='undefined') {
				this.CloseEvents = [];
			}
			this.CloseEvents.push(_function);
		}
		return this;
	}
	
	/* [instance].center(['vertical'|'horizontal']) */
	$(winName).center = function(_direction){
		$(winName)._center(_direction);
		if (/MSIE/.test(navigator.userAgent) && !window.opera && $(winName).loading) {
			$(winName).afterLoadArray.push(
							function(){ $(winName)._center(_direction); /* alert('_center() after load.'); */ }
						);
		}
		return this;
	}
	$(winName)._center = function(_direction) { 
		if (typeof(_direction)=='undefined' || _direction=='vertical') {
			this.style.top = (getWindowHeight()/2)-(this.dpParams.height/2)+getScrollTop() + 'px';
		}
		if (typeof(_direction)=='undefined' || _direction=='horizontal') {
			this.style.left = (getWindowWidth()/2)-(this.dpParams.width/2) + 'px';
		}
		return this;
	}
	
	/* Max Height proxy function */
	$(winName).maxHeight = function(padding){
		if (/MSIE/.test(navigator.userAgent) && !window.opera && $(winName).loading) {
			$(winName).afterLoadArray.push(
							function(){ $(winName)._maxHeight(padding); /* alert('_maxHeight() after load.'); */ }
						);
		} else {
			$(winName)._maxHeight(padding);
		}
		return this;
	}
	/* Real Max Height function */
	$(winName)._maxHeight = function(padding) {
		if (typeof padding == 'number') {
			padding = padding*2;
		} else {
			padding = 0;
		}
		if ((getWindowHeight()-$(winName).dpParams.height) > 100) {
			var height = getWindowHeight()-60-padding;
			$(winName).dpParams.height = height;
			var p = $(winName).dpParams;
			$(winName).style.height = height + 'px';
			$(winName+'shimFrame').style.height = height-2 + 'px';
			$(winName+'ContentTD').style.height = height-38 + 'px';
			/* Figure out when IE and do wacky stuff */
			if(/MSIE/.test(navigator.userAgent) && !window.opera) {
				var cbox = $(winName+'Content');
				//alert('cbox.scrollHeight:' + cbox.scrollHeight + '\n(height-38):' + (height-38));
				var ieHeight = (cbox.scrollHeight>(height-38)?(height-38)+'px':'100%');
				$(winName+'Content').style.height = ieHeight;
			} else {
				$(winName+'Content').style.height = height-38 + 'px';
			}
		}
		return this;
	}
	$(winName).close = function() {
		dpPopupClose(this.dpParams.name);
	}
	$(winName).setTop = function(_top) {
		if (typeof(_top)=='number') {
			this.style.top = (getScrollTop()+_top) + 'px';
		}
		return this;
	}
	$(winName).setLeft = function(_left) {
		if (typeof(_top)=='number') {
			this.style.left = _left + 'px';
		}
		return this;
	}
	$(winName).setContent = function(_content) {
		$(winName+'Content').innerHTML = _content;
	}
	
	/* END - WINDOW FUNCTIONS */
	
	/* Return window DOM element */
	return $(winName);
}

function dpPopupClose(winName) {
	var winName = 'dpPopup'+winName;
	var winObj = $(winName);
	var listener = {};
	if (window.dragRegistry[winName]) {
		/* Call "Popup Close" listeners */
		if (typeof(winObj.CloseEvents)!='undefined') {
			for (var i=0; i<winObj.CloseEvents.length; i++) {
				listener = winObj.CloseEvents[i];
				listener.call(); 
			}
		}
		window.dragRegistry[winName].destroy();
		delete window.dragRegistry[winName];
		document.body.removeChild($(winName));
	}
}
/* END - DEALERPEAK DHTML POPUP WINDOW */


function getMouseX(event) {
	var posx = 0;
	if (event.pageX) {
		// FF
		posx = event.pageX;
	}
	else if (event.clientX) {
		// IE
		posx = event.clientX + document.body.scrollLeft;
	}
	return posx;
}
function getMouseY(event) {
	var posy = 0;
	if (event.pageY) {
		// FF
		posy = event.pageY;
	}
	else if (event.clientY) {
		// IE
		posy = event.clientY + document.body.scrollTop;
	}
	return posy;
}
function getScrollTop() {
	    return  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
}
function getWindowWidth(event) {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  myWidth = document.body.clientWidth;
	}
	return myWidth;
}
function getWindowHeight(event) {
	var myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function hasProps(obj) {
	for (var i in obj) { return true; } 
	return false;
}

//determine browser height 2
	f_filterResults = function(n_win, n_docel, n_body) {
		var n_result = n_win ? n_win : 0;
		if (n_docel && (!n_result || (n_result > n_docel)))
			n_result = n_docel;
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	}
	
	f_clientHeight = function() {
		return f_filterResults (
			window.innerHeight ? window.innerHeight : 0,
			document.documentElement ? document.documentElement.clientHeight : 0,
			document.body ? document.body.clientHeight : 0
		);
	}
	
	function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function formatPhone(PhoneNumber) {
	var p = PhoneNumber.replace(/[^0-9]|^1/g,'');
	var formatted = "(" + p.substr(0,3) + ") " + p.substr(3,3) + "-" + p.substr(6,4);
	if(p.length > 10){
		formatted += " ext. " + p.substr(10,5);
	}
	return formatted;	
}
function hideSelects(tf) {
	var sels = document.getElementsByTagName("select");
	sels_visible = !tf;
	for (var i = 0; i < sels.length; ++i) {
		if (tf == true) { // 
			sels[i].o_visibility = sels[i].style.visibility;
			sels[i].o_display = sels[i].style.display;
		}
		sels[i].style.visibility = sels_visible ? sels[i].o_visibility : "hidden";
		sels[i].style.display = sels_visible ? sels[i].o_display : "none";
	}
}

/* 
	toolTip
	Author:		Chris Phillips
	Created:	09/13/2006
	
	Note: Requires prototype.js.
	
	Aguments:
	title		Short description of the tip
	body		The HTML body of the tip
	width		The Width of the tip popup
	element		The element you are mousing over to popup the tip
	event		The mouse event to get the position stuff from
	
	Example:
	onmouseover="toolTip('Hint','The seperator for fields.<br/>Use \'T\' for TAB.',150,this,event);"
*/
function toolTip(title,body,width,element,event) {
	if (typeof(toolTipNum)=='undefined') {
		toolTipNum = 0;	
	}
	toolTipNum++;
	document.body.appendChild(
		Builder.node("div", {id:"tooltip"+toolTipNum,style:"position:absolute;"}, [
			Builder.node("div",{className:"TipTitle"},title),
			Builder.node("div",{className:"TipContent",id:"TipContent"+toolTipNum})
		])
	);
	$('TipContent'+toolTipNum).innerHTML = body;
	var _top = (getMouseY(event)-10-$('tooltip'+toolTipNum).getHeight());
	var _left = (getMouseX(event)+15);
	$('tooltip'+toolTipNum).style.width = width+'px';
	$('tooltip'+toolTipNum).style.top = (_top > 0)?_top:5;
	$('tooltip'+toolTipNum).style.left = _left;
	addEvent(element,'mouseout',function(){if($('tooltip'+toolTipNum)){document.body.removeChild($('tooltip'+toolTipNum))}});
}

function isGuid(guid){//guid format : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx or xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
	if(!guid) return false;
	GuidRegExp = /^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$/
	return GuidRegExp.test(guid);
}