/***
* Utility functions created and maintained by d.a.l.e.AT.e.a.s.y.c.o.m
**/
var IE = ( document.all );
var DOM = ( document.getElementById || parseInt(navigator.appVersion) >= 5 );
if( IE ) try{ document.execCommand('BackgroundImageCache',false,true); } catch(e){};

// retrieve an object from the name specified
function getObject( title ) {
	var obj = _dge ? _dge(title) : document.all ? document.all[title] : null;
	return obj;
}

///////////////////////////////////////////////////////////
// strip out html that could cause security issues.
function StripFormHTML( form ) {
	for( i = 0; i < form.length; i++ ) {
		if( form[i].type.toLowerCase() == 'text' || form[i].type.toLowerCase() == 'textarea' ) 
			form[i].value = StripHTML(form[i].value);
	}
}

///////////////////////////////////////////////////////////
// strip out html that could cause security issues.
function StripHTML( text ) {
	text = text.replace( /\<[^>]*\>/ig, '' );
	return text;
}

///////////////////////////////////////////////////////////
function StripWhiteSpace( text ) {
	text = text.replace(/[\t\n\r]/ig,' ').replace(/\s{2,}/ig,' ');
	text = text.replace(/^\s+/ig,'').replace(/\s+$/ig,'');
	return text;
}

///////////////////////////////////////////////////////////
function CleanText( text ) {
	text = StripHTML( text );
	text = StripWhiteSpace( text );
	return text;
}

///////////////////////////////////////////////////////////
function CleanVal(obj) {
	if( obj.value ) obj.value = CleanText(obj.value);
}

///////////////////////////////////////////////////////////
function ValidateNumber( obj ) {
	var num = Number(obj.value.replace(/[^0-9]/,''));
	num = isNaN(num) ? 0 : num;
	obj.value = num;
}

///////////////////////////////////////////////////////////
function ValidateDate( obj ) {
	if( !obj.value ) return;
	var now = new Date();
	obj.value = obj.value.replace(/[^0-9\/\-]/g,'').replace(/-/g,'/');
	if( obj.value.match(/^\d{1,2}$/) ) obj.value = (now.getMonth()+1)+'/'+obj.value+'/'+now.getFullYear()
	else if( obj.value.match(/\d{1,2}\/\d{1,2}$/) ) obj.value += '/'+now.getFullYear()
	var dt = new Date(obj.value);
	obj.value = isNaN(dt) ? '' : ( (dt.getMonth()+1)+'/'+dt.getDate()+'/'+dt.getFullYear() );
}

///////////////////////////////////////////////////////////
function ValidateCurrency( obj, strip_cents ) {
	var amt = obj.value.replace(/[^0-9km\.\-]/ig,'').replace(/k/ig,'000').replace(/m/ig,'000000');
	var dollars = amt.replace(/(\d+)\.(.*)/,'$1');
	var comma_reg = /(\d+)(\d{3})/;
	while( comma_reg.test(dollars) ) dollars = dollars.replace(comma_reg,'$1,$2');
	var cents = amt.match(/\./) ? Number(amt.replace(/(.*)\.(\d+)/,'$2')) : 0;
	cents = cents < 10 ? '0'+cents : ''+cents;
	amt = dollars ? dollars+'.'+cents : '';
	obj.value = amt;
}

//////////////////////////////////////////////////////
function ValidEmail( email ) {
	if( typeof email == 'object' ) email = email.value;
	email = email.replace(/^\s{1,}/,'').replace(/\s{1,}$/,'');
	if( !email || !email.match(/^([^@ \!\?\*\[\]\(\)\{\}])+@([^@ \!\?\*\[\]\(\)\{\}])+\.[a-z]{3}$/i) ) return false;
	return true;
}

//////////////////////////////////////////////////////
function GetHTTPObj() {
	var http;
	try { http = new XMLHttpRequest(); } 
	catch(e) { http = null; }
	if( ! http ) {
		/*@cc_on
		@if( @_jscript_version >= 5 )
		try {
			http = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch(e) {
			try { http = new ActiveXObject("Microsoft.XMLHTTP"); } 
			catch (E) { http = null; }
		}
		@else
			http = false;
		@end @*/
	}
	return http;
}

//////////////////////////////////////////////////////
function BGPost( action, params, destObj, callbackFunction ) {
	var returnval;
	var http = GetHTTPObj();
	var bgurl = window.global_bg_url ? global_bg_url : 'bg.php';

	if( http ) {
		http.open( 'POST', bgurl );
		http.onreadystatechange = function() {
			if( http.readyState == 4 ) {
				try {
					if( http.responseText.match(/id="_username"/) ) location.reload();
					if( destObj && _dge(destObj) ) _dge(destObj).innerHTML = http.responseText;
					returnval = http.responseText.replace(/[\t\n\r]/ig,' ').replace(/\s{2,}/ig,' ').replace(/"/g,'\\\"').replace(/\\(\w)/g,'\\\\$1');
					if( callbackFunction && eval('window.'+callbackFunction) ) eval( callbackFunction+'("'+returnval+'","'+action+'")' );
				}
				catch(e) {
					var dest = _dge('results');
					if( dest ) {
						dest.innerHTML = '<h3 style="color:red;">'+e.description+'</h3>';
						dest.innerHTML += '<br><b>callback function</b>: '+callbackFunction+'<br><b>action</b>: '+action;
						dest.innerHTML += '<br><b>returned text</b>: <xmp>'+returnval.replace(/(\<[a-z])/ig,'\n$1')+'</xmp>';
					}
					//else alert( e.message );
				}
			}
		}
		http.setRequestHeader( 'POST', bgurl+' HTTP/1.1' );
		http.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
		http.send( 'a='+action+'&'+params.join('&') );
	}
	else
		alert( 'Could not get a background process' );
}

//////////////////////////////////////////////////////
function BGGet( action, params, destObj, callbackFunction ) {
	var returnval;
	var http = GetHTTPObj();
	var bgurl = ( window.global_bg_url ? global_bg_url : 'bg.php' )+'?a='+action+'&'+params.join('&');

	if( http ) {
		http.open( 'GET', bgurl );
		http.onreadystatechange = function() {
			if( http.readyState == 4 ) {
				if( destObj && _dge(destObj) ) _dge(destObj).innerHTML = http.responseText;
				returnval = http.responseText.replace(/[\t\n\r]/ig,' ').replace(/\s{2,}/ig,' ').replace(/"/g,'\\\"');
				if( callbackFunction ) eval( callbackFunction+'("'+val+'","'+action+'")' );
			}
		}
		http.send(null);
	}
	else
		alert( 'Could not get a background process' );
}

//////////////////////////////////////////////////////
// This function will set a "session" value dynamically without reloading the page
function SessValue( name, value ) {
	BGPost( 'set_value', Array('var='+name,'val='+value) );
}

//////////////////////////////////////////////////////
function CheckResponse( response, action ) {
	alert( response );
}

//////////////////////////////////////////////////////
function _dge( obj ) {
	return document.getElementById(obj);
}

//////////////////////////////////////////////////////
// pop open a window. this window can be posted to
var pop_win;
function popupWin( url, width, height, useExisting ) {
	if( !width ) width = 600;
	if( !height ) height = 400;
	var win_opts = 'width='+width+',height='+height+',toolbar=no,location=no,directories=no,menubar=no,status=no,resizable=yes,scrollbars=yes';
	pop_win = window.open( '', '_info', win_opts );
	if( pop_win ) {
		pop_win.document.write('<font face="tahoma,arial,helvetica" size="4" color="maroon">Loading...</font>');
		window.status = 'Loading...';
	
		var frm;
		if( !_dge('_generated_form') && !useExisting ) {
			frm = document.body.appendChild( document.createElement('form') );
			frm.name = '_generated_form';
			frm.id = '_generated_form';
		}
		frm = useExisting ? document.forms[0] : _dge('_generated_form');
		frm.target = '_info';
		if( url ) {
			if( url.match(/.*\?(.*)$/) ) {
				var inpt, nam, val;
				var qstring = url.replace(/.*\?(.*)$/ig,'$1');
				var params = qstring.split('&');
				while( frm.elements.length > 0 ) frm.removeChild(frm.elements[0]); // cleanup
				for( var i = 0; i < params.length; i++ ) {
					inpt = document.createElement('input');
					inpt.name = params[i].replace(/(.*)=(.*)/i,'$1');
					inpt.value = params[i].replace(/(.*)=(.*)/i,'$2');
					inpt.type = 'hidden';
					frm.appendChild(inpt);
				}
				url = url.replace(/^(.*)\?.*$/ig,'$1');
			}
			frm.action = url;
		}
		frm.method = 'post';
		frm.submit();

		// this is a little hack to get Firefox to stop spinning
		if( !_dge('_generated_frame') ) {
			frm = document.body.appendChild( document.createElement('iframe') );
			frm.name = '_generated_frame';
			frm.id = '_generated_frame';
			frm.style.cssText = 'display:none;width:1px;height:1px;';
		}
		if( _dge('_generated_frame') ) _dge('_generated_frame').src='';

		if( !pop_win.closed ) pop_win.focus();
	}
}

//////////////////////////////////////////////////////
function openWin( width, height, title, opts ) {
	if( !width ) width = 600;
	if( !height ) height = 400;
	if( !title ) title = '_win';
	if( !opts ) opts = ',resizable=1,scrollbars=1,menubar=0,status=0,toolbar=0,location=0';
	pop_win = window.open( '', title, 'width='+width+',height='+height+opts );
	if( pop_win ) pop_win.focus();
	return true;
}

//////////////////////////////////////////////////////
function ShowModalWin( obj, leftOffset ) {
	if( obj && typeof(obj) == 'string' ) obj = _dge(obj);
	if( !obj || !obj.id ) return;
	if( window.currModalDlg ) HideModalWin( _dge(window.currModalDlg) )
	var height = document.body.clientHeight ? document.body.clientHeight : window.innerHeight;
	var width = document.body.clientWidth ? document.body.clientWidth : window.innerWidth;
	if( height && width ) {
		leftOffset = obj.style.width ? ( obj.style.width.replace(/[^0-9]/g,'')/2 ) : leftOffset
		if( !leftOffset ) leftOffset = 300;
		obj.style.left = ((width/2)-leftOffset)+'px';
		obj.style.zIndex = 150;
		obj.style.display = '';
		try { setTimeout('gradientshadow.create("'+obj.id+'")',100); } catch(e) {}
	}
	window.currModalDlg = obj.id;
}

//////////////////////////////////////////////////////
function HideModalWin( obj ) {
	if( !obj && window.currModalDlg ) obj = _dge(window.currModalDlg);
	if( obj && typeof(obj) == 'string' ) obj = _dge(obj);
	if( !obj || !obj.id ) return;
	obj.style.display = 'none';
	if( obj.getAttribute('dynanamic') ) document.body.removeChild(obj);
	if( window.currModalDlg ) window.currModalDlg = null;
	try { gradientshadow.destroy(obj.id); } catch(e) {}
}

//////////////////////////////////////////////////////
function ModalWindow(id,width) {
	var m_obj;
	this.id = id ? id : '_modal';
	this.title = 'modal window';
	this.width = width ? width : 500;
	this.className = 'modal_window';
	this.contents = '';
	this.Create = CreateObj;
	this.Show = ShowObj;
	this.Display = ShowObj;
	this.Print = PrintObj;
	this.Write = WriteObj;
	this.Get = GetObj;

	function CreateObj() {
		m_obj = document.createElement('div');
		m_obj.id = this.id;
		m_obj.className = this.className;
		m_obj.style.border = '1px solid #333';
		m_obj.style.width = this.width+'px';
		m_obj.style.display = '';
		m_obj.innerHTML = '<div class="modal_title">'+this.title+'</div>';
		m_obj.innerHTML += '<div class="modal_content">'+this.content+'</div>';
		m_obj.setAttribute('dynanamic','true');
	}

	function WriteObj(dest) {
		try  { 
			_dge(dest).appendChild(m_obj);
			_dge(dest).style.display = '';
		}
		catch(e) { alert('There was an error writing the modal window\n'+e.message); }
	}

	function ShowObj() {
		try  { 
			this.Create();
			document.body.appendChild(m_obj); 
			if( gradientshadow ) gradientshadow.create(m_obj.id);
			window.currModalDlg = m_obj.id;
		}
		catch(e) { alert('There was an error displaying the modal window\n'+e.message); }
	}

	function GetObj() {
		return m_obj;
	}

	function PrintObj() {
		try { alert(m_obj.outerHTML); }
		catch(e) {}
	}
}

//////////////////////////////////////////////////////
// shadow stuff
var gradientshadow = {}
gradientshadow.depth = 6
gradientshadow.containers = []

//////////////////////////////////////////////////////
gradientshadow.create = function(id) {
	var obj = _dge(id);
	if( !gradientshadow || !obj ) return;
	try {
		gradientshadow.destroy( id );
		for( var x = 0; x < gradientshadow.depth; x++ ) {
			var newShadow = document.createElement('div')
			newShadow.className = 'floating_shadow';
			newShadow.id = 'shadow_'+id+'_'+x //Each shadow DIV has an id of 'shadow_ID_X' (ID=id of target element, X=index of shadow (depth) 
			newShadow.style.background = obj.getAttribute('rel') ? obj.getAttribute('rel') : 'black'; // black by default
			document.body.appendChild(newShadow);
			gradientshadow.containers[gradientshadow.containers.length] = newShadow.id;
		}
		gradientshadow.position();
		window.onresize = function(){gradientshadow.position()}
	}
	catch(e) { alert( 'gradientshadow.create: '+e.message ); }
}

//////////////////////////////////////////////////////
gradientshadow.destroy = function(id) {
	if( !gradientshadow || !gradientshadow.containers || !gradientshadow.containers.length ) return;
	var tmpcontainer = [];
	try {
		for( var i = 0; i < gradientshadow.containers.length; i++ ) {
			if( !id || gradientshadow.containers[i].indexOf('shadow_'+id) != -1 ) {
				var shadowdiv = _dge(gradientshadow.containers[i]);
				if( shadowdiv ) shadowdiv.parentNode.removeChild(shadowdiv);
			}
			else tmpcontainer[tmpcontainer.length] = gradientshadow.containers[i];
		}
		gradientshadow.containers = tmpcontainer;
	}
	catch(e) { alert( 'gradientshadow.destroy: '+e.message ); }
}

//////////////////////////////////////////////////////
gradientshadow.position = function() {
	if( !gradientshadow || !gradientshadow.containers || !gradientshadow.containers.length ) return;
	try {
		for( var i = 0; i < gradientshadow.containers.length; i++ ) {
			var id = gradientshadow.containers[i].replace(/shadow_(.*)_\d/,'$1');
			var depth = Number(gradientshadow.containers[i].replace(/shadow_.*_(\d)/,'$1'));
			//alert(gradientshadow.containers[i] + '\n' + id + '\n' + depth);
			var shadowdiv = _dge(gradientshadow.containers[i]);
			shadowdiv.style.width = _dge(id).offsetWidth+'px';
			shadowdiv.style.height = _dge(id).offsetHeight+'px';
			shadowdiv.style.left = _dge(id).offsetLeft+depth+'px';
			shadowdiv.style.top = _dge(id).offsetTop+depth+'px';
			if( _dge(id).style.zIndex ) shadowdiv.style.zIndex = ( _dge(id).style.zIndex-depth-1 );
		}
	}
	catch(e) { alert( 'gradientshadow.position: '+e.message ); }
}

//////////////////////////////////////////////////////
// validates a cc number using the Luhn algorithm
function LuhnCheck( num ) {
	var oddoeven = num.length & 1;
	var sum = 0; 

	for( i = 0; i < num.length; i++ ) {
		var ch = parseInt( num.charAt(i) );
		if( ch < '0' || ch > '9' ) return false;
		if( !( (i & 1) ^ oddoeven) ) {
			ch *= 2;
			if( ch > 9 ) ch -= 9;
		}
		sum += ch;
	}
	
	return ( (sum % 10) == 0 );
}

//////////////////////////////////////////////////////
function GetCCType( cardnum ) {
	var cardType;
	if( cardnum.match(/^4(\d{15}|\d{12})/) ) cardType = "Visa";
	else if( cardnum.match(/^3(4|7)\d{13}/) ) cardType = "Amex";
	else if( cardnum.match(/^5(1|2|3|4|5)\d{14}/) ) cardType = "Mastercard";
	else if( cardnum.match(/^6011\d{12}/) ) cardType = "Discover";
	return cardType;
}

//////////////////////////////////////////////////////
function ValidCCNumber( cardnum ) {
	cardnum = cardnum.replace(/[^0-9]/g,'');
	var isValid = ( LuhnCheck(cardnum) && GetCCType(cardnum) );
	return isValid;
}

//////////////////////////////////////////////////////
function DisablePage(msg) {
	try {
		if( msg ) window.status = msg;
		if( currModalDlg ) HideModalWin( _dge(currModalDlg) )
		if( _dge('inactivate_div') ) _dge('inactivate_div').style.display = '';
	}
	catch(e){}
}

//////////////////////////////////////////////////////
function EnablePage() {
	try {
		window.status = 'Done';
		if( _dge('inactivate_div') ) _dge('inactivate_div').style.display = 'none';
		if( currModalDlg ) HideModalWin( _dge(currModalDlg) )
	}
	catch(e){}
}

//////////////////////////////////////////////////////
function LogOut(resp,actn) {
	if( !actn ) BGPost('log_off',Array(),'','LogOut');
	else if( actn ) location.href = location.href;
}

//////////////////////////////////////////////////////
function DoScroll(obj,count) {
	var size = 10;
	var buf = document.all ? 0 : 300;
	var oldtop = obj.parentNode.scrollTop;
	if( (oldtop+size+buf) < obj.offsetTop && count < 500 ) {
		obj.parentNode.scrollTop += size;
		var newtop = obj.parentNode.scrollTop;
		if( newtop != oldtop ) DoScroll(obj,(count+1));
		//else alert(obj.offsetTop + '\n' + obj.scrollTop + '\n' + newtop + '\n' + count );
	}
}

