// MedcompIR.com -- Main JavaScript Document

var adminExp = /dealer|admin/;
if(!adminExp.test(location.href) && top.location == self.location) {
	location = 'http://www.medcompnet.com';
}

// Standard Variables //
var myEntity			= 'Medcomp® Interventional';	// company or website trademark / proper name
var myDisplaySeparator	= '    >   ';	// goes betweem myEntity & message in the status bar
var emailAdminName		= 'Eric Harris';
var emailAdminAlias		= 'webmaster';
var emailIntlName		= 'Doreen Kibblehouse';
var emailIntlAlias		= 'doreen';
var emailDomName		= 'Adam Brody';
var emailDomAlias		= 'abrody';
//var emailClinicalName		= 'Susan Smith';
//var emailClinicalAlias	= 'ssmith';
var emailDefaultName	= emailDomName;
var emailDefaultAlias	= emailDomAlias;
var mail_url			= 'cgi-bin/contact/email.cgi';	//used in function mail()
var username_url		= 'cgi-bin/members/index.cgi';	//used in function afterLoad()
var download_url_dir	= 'cgi-bin/products/literature/';	//used in function download()
//var download_frame_url	= 'products/literature/download_frame.html';
var myDomain;						// NOTE: 'domain' is a reserved word, thus 'myDomain'
var root;							// http document root for nav within JavaScripts
var endURL;							// location.href without the root part
var httpExp			= /^http/i;		// to tell whether we're online or not
var secureExp		= /^https:/;	// to tell whether we're using SSL
var emailExp		= /^[\w.-]{2,}\@[\w.-]{2,}\.([a-z]{2,3}|aero|arpa|coop|info|museum|name)$/
var emptyExp		= /^\s*$/;		// for client-side validation of form fields
var Netscape		= false;		// is Netscape 7.1+ the user-agent?
var IE				= false;		// is IE the user-agent?
var IE7				= false;		// is IE version 7.0 or higher? (windowless SELECT elements)
var functions		= 1;			// indicates a frame has loaded this code. (not a PDF window)
var loaded			= false;		// indicates page is completely loaded, (onLoad handler called)
var childWindow		= new Object;	// window name of the messaging pop-up
var mainFrame		= new Object;	// object referencing top.frames[0]
var topFrame		= new Object;	// object referencing top
var NetscapeEvent	= new Object;	// see function setNetscapeEvent() in menus.js
var VAR				= new Object();	// contains key=value pairs from query string
var qStringArgs		= new Array();	// used in creating VAR object
var onload_list		= new Array();
var onscroll_list	= new Array();
var onresize_list	= new Array();

var nav_order = new Array(			// set to different values in dealers.js
	'about',
	'products',
	'lit_downloads',
	'contact',
	'login'
);



////////////////////////////////////////////////
// Determine Where we are for dynamic linking //
////////////////////////////////////////////////
{
	var rootExp; var domExp;
	if(httpExp.test(location.href)) {
		rootExp	= /^(https?:\/\/[^\/]+\/)\??(.*[^\/]+(\.html)?.*$3?.*$3?.*)$/i;
		domExp	= /^https?:\/\/([\w.-]+\.)?([\w-]+\.[a-z]+)(\:\d+)?\/?$/i;
	} else {	//LOCAL SITE ONLY: Customize the below 2 vars
		rootExp	= /^(.+\/medcompir.com\/)\??(.*[^\/]+(\.html)?.*$3?.*$3?.*)$/i;
		domExp	= /^(.+)\/(medcompir.com)\/?$/i;
	}
	
	root		= (location.href).replace(rootExp,"$1");
	endURL		= (location.href).replace(rootExp,"$2");
	myDomain	= root.replace(domExp,"$2");
}


//////////////////////////////////////////////////////////////////////////////
// Before possibly re-framing, get rid of Netscapes older than appVersion 5 //
//////////////////////////////////////////////////////////////////////////////
if(navigator.appName == 'Netscape') {
	Netscape = true;
	//var version = navigator.appVersion.replace(/^(\d)\.(\d+).*/,"$1$2");
	//if(version < 50) { top.location.replace(root +'old_netscape.html') }
//	var version = Number(navigator.userAgent.replace(/^.+Netscape\/([\d\.]+).*$/,"$1"));
//	if(version < 7) { top.location.replace(root +'old_netscape.html') }
} else {
	IE = true;	// we'll just assume
	var version = Number(navigator.userAgent.replace(/^.+MSIE\s+([\d\.]+).*$/,"$1"));
	if(version >= 7) {
		IE7 = true;
	}
	document.write('<META HTTP-EQUIV="imagetoolbar" CONTENT="no">');
	document.write('<meta name="MSSmartTagsPreventParsing" content="TRUE">');
}



//////////////////////////////////////////////////////////////////////////
// !!TEMP!! Show people the "upgrade" page once every [interval] days.	//
//////////////////////////////////////////////////////////////////////////
/*if(document.cookie.indexOf('fairly_warned') < 0 &&
		location.href.indexOf('upgrade.html') < 0) {
	top.location.replace(root + 'upgrade.html');
} else if(document.cookie.indexOf('fairly_warned') > -1) {
	//document.write('<style type="text/css">BODY{overflow:auto;}</style>');
}*/


///////////////////////////////////////////////////////////////////
// Re-frame pages that were loaded outside of the main frameset. //
///////////////////////////////////////////////////////////////////
if(top.siteIndex != 1) { reframe(root + endURL) }
function reframe(x) {
	var url = x;
	if(!httpExp.test(url)) {	//so this will work offline
		url = url.replace(/\/\?/,"/index.html?");
	} else {//only when online, as we don't want to see a windows folder instead of a page
		url = url.replace(/\/index.html$/,"/");
		//url = url.replace(/\/\?home.html$/,"");
		// *CUSTOMIZE: replace any other page urls, such as sub-framed pages, etc.
		url = url.replace(/\/index_dd_menus.html$/,"/");
		//url = url.replace(/COVER.html$/,"");
		//url = url.replace(/\/([^\/]+)?MENU.html$/,"/$1index.html");
	}
	top.location.replace(url);
	// Disable errors that will inevitably pop up (in IE) as the new page	//
	// is loading, but the currently loaded page is still receiving events.	//
	onerror = function(){return true}
}



//////////////////////////////////////////////////////////////////////////
// Now we should be dealing with framed pages. Write in dynamic page	//
// elements, set frame-related/qString variables & standard functions.	//
//////////////////////////////////////////////////////////////////////////
var new_styles = '';
if(Netscape) {
	new_styles = 'height:355px; width:95%; top:-200px;';
}
var layoutStyle = '<style type="text/css"> #MAIN_BG_FADE { height:200px; }\n'+
				'#MAIN_SCROLLER { position:relative; top:-203px; margin:0px 0px -205px; '+
				new_styles +'}\n'+
				'</style>';
document.write(layoutStyle);


//////////////////////////////////////////////////////////////////////////////////////
// Format VAR object: query string args of "...html?key1=value&key2=value2&etc..."	//
// will be accessible in JavaScript as VAR.key# -ex:- alert(VAR.key1); => 'value'	//
//////////////////////////////////////////////////////////////////////////////////////
qStringArgs = location.search.substring(1).split('&');
if(qStringArgs.length > 0 && location.search.substring(1).indexOf('=') > -1) {
	for(i=0; i<qStringArgs.length; i++) {
		if(qStringArgs[i] != undefined && qStringArgs[i] != '') {
			var key = qStringArgs[i].split('=')[0].replace(/\W/g,'');
			/*var val = unescape(qStringArgs[i].split('=')[1]).replace(/'/g,"\\'");
			val = val.replace(/\n/g, "\\n");
			eval("VAR."+ key +" = '"+ val +"'");*/
			//alert(key+', '+ eval('VAR.'+key));
			var val = unescape(qStringArgs[i].split('=')[1]);
			VAR[key] = val;
		}
	}
	//Take special measures to preserve sub-query strings in 'redirect'//
	if(location.search.substring(1).indexOf('redirect=') > -1) {
		VAR.redirect = location.search.substring(1).replace(/redirect=(.+)$/, "$1");
	}
}


mainFrame = (top.frames[0] == undefined)? top : top.frames[0];
topFrame = top;
// The top doc runs this code before the main frame is loaded, so:
if(top.mainFrame == undefined && mainFrame) { top.mainFrame = mainFrame }


onload_list.push('loaded = 1;');	//use this method to add functions to document event handlers

window.defaultStatus = myEntity;
function display(message) {
	/*if(Netscape) {	// do I still need this?
		if(top.child_window) { top.child_window.focus() }
	}*/
	message = (message == undefined)? '' : myDisplaySeparator + message;
	window.status = myEntity + message;
}


//////////////////////////////////
// Document event handlers::	//
//////////////////////////////////
onload = function() {
	beforeLoad();	//Special onLoad functions to execute before all the rest//
	for(var loadIndex=0; loadIndex<=onload_list.length; loadIndex++) {
		eval(onload_list[loadIndex]);
	}
	afterLoad();	//Special onLoad functions to execute after all the rest//
}

onscroll = function() {
	for(var scrollIndex=0; scrollIndex<=onscroll_list.length; scrollIndex++) {
		eval(onscroll_list[scrollIndex]);
	}
}

onresize = function() {
	for(var resizeIndex=0; resizeIndex<=onresize_list.length; resizeIndex++) {
		eval(onresize_list[resizeIndex]);
	}
}

if(IE) {
	onfocus = function(){
		//this allows IE to focus on a form fields in the popup window
		//unlike using "onblur=focus()" in the popup
		if(typeof(top.childWindow.document) == 'object') {
			top.childWindow.focus();
		}
	}
}
	//////////////////////////////////////////////////////////////////////////////////////////
	// DOCUMENT EVENT HANDLER NOTES::														//
	//////////////////////////////////////////////////////////////////////////////////////////
	// The on*_list arrays are global lists of functions to be called by their respective	//
	// window event handlers. Functions were previously added to handlers by scripts on		//
	//		each page like so:																//
	//		onload2 = onload;																//
	//		onload = function() { onload2(); cutomFunction1(); cutomFunction2(); }			//
	// This would eventaully cause a "stack overflow" because of the recursion involved		//
	// when this code appeared in multiple scripts imported into a single HTML page. Now	//
	// calls like onload_list.push('commands;'); are used by each page to control the flow.	//
	// Note: Any function with a for loop will keep the remaining calls in its on*_list		//
	// array from executing IF a globally-scoped i variable is used, as is the norm. In		//
	// such a case use: on*_list.unshift('func'); to add functions to the end of the list.	//
	//////////////////////////////////////////////////////////////////////////////////////////


function beforeLoad() {
	var beginL	= 226;	var beginT	= 97;
	var diffL	= -8;	var diffT	= 18;
	var myLeft;	var myTop; var count = 0;
	for(var i=0; i<nav_order.length; i++) {
		var div = document.getElementById('nav_'+ nav_order[i] +'_div');
		//alert(div.style);
		if(div != null) {
			myLeft = (count == 0)? beginL : myLeft + diffL;
			myTop = (count == 0)? beginT : myTop + diffT;
			with(div.style) { left = myLeft+'px'; top = myTop+'px'; }
			count++;
		//	alert(myLeft+', '+myTop);
		}
	}
}
////////////////////////////////////////////////////////////////////////////////////
// Execute these commands at the end of all other onLoad functions (onload_list). //
////////////////////////////////////////////////////////////////////////////////////
function afterLoad() {
	//hide the "loading" progress bar, if applicable//
	//loading('hide');
	
	//update login/logout links, if applicable//
	if(top.document.getElementById('username_span')) {
		if(document.cookie.indexOf('login=') > 0) {
			var username = document.cookie.replace(/^.*login=([^;]*);?.*$/, "$1");
			with(top.document.getElementById('username_span')) {
				//innerHTML = 'WELCOME, '+ username.toUpperCase();
				innerHTML = username;
				title = 'Home Page for '+ username;
				href = 'javascript:nav(username_url);';
			}
			with(top.document.getElementById('login_link')) {
				href = "javascript:nav('cgi-bin/members/logout.cgi');";
				title = 'Log Out';
				innerHTML = 'Log Out';
			}
		} else {//display registration & log in links//
			with(top.document.getElementById('username_span')) {
				innerHTML = 'Membership Form';
				title = 'Register For Membership';
				href = "javascript:nav('cgi-bin/members/registration.cgi');";
			}
			with(top.document.getElementById('login_link')) {
				href = "javascript:nav('cgi-bin/members/login.cgi');";
				title = 'Log In';
				innerHTML = 'Log In';
			}
		}
	}
	
	//Make all document links display their title attributes in the status bar//
	for(var i=0; i<document.links.length; i++) {
		if(document.links[i].title) {
			var otherOvers = document.links[i].onmouseover;
			if(otherOvers == undefined) { otherOvers = 'void(1);' }
			if(otherOvers.toString().indexOf('function') < 0) { otherOvers = function(){otherOvers} }
			document.links[i].mouseover2 = otherOvers;
			document.links[i].onmouseover = function(){
				setNetscapeEvent(1);
				this.mouseover2();
				display(this.title);
				return true;
			};
			
			if(Netscape) {//needs a mousout event to clear the status bar
				var otherOuts = document.links[i].onmouseout;
				if(otherOuts == undefined) { otherOuts = 'void(1);' }
				if(otherOuts.toString().indexOf('function') < 0) {
					eval('otherOuts = function(){'+otherOuts+'}');
				}
				//otherOuts = otherOuts.toString().replace(/^[^{]+\{([^}])\}.*$/,"$1");
				document.links[i].mouseout2 = otherOuts;
				document.links[i].onmouseout = function() {
					setNetscapeEvent(1);
					this.mouseout2();
					window.status = window.defaultStatus;
					//'alert('+otherOuts+');
					return true;
				};
			}
		}
		
		var otherFocus = document.links[i].onfocus;
		if(otherFocus == undefined) { otherFocus = 'void(1);' }
		if(otherFocus.toString().indexOf('function') < 0) { otherFocus = function(){otherFocus} }
		document.links[i].focus2 = otherFocus;
		document.links[i].onfocus = function(){
			this.focus2();
			this.blur();
		};
		
	}
	//END fixing links//
	
	//Take the focus off of form buttons & checkboxes
	for(var i=0; i<document.forms.length; i++) {
		var myForm = document.forms[i];
		for(var j=0; j<myForm.elements.length; j++) {
			var myObj = myForm.elements[j];
			if(myObj.type == 'submit' || myObj.type == 'reset' || myObj.type == 'button' ||
			   myObj.type == 'radio' || myObj.type == 'checkbox') {
				var otherFocus = myObj.onfocus;
				if(otherFocus == undefined) { otherFocus = 'void();' }
				if(otherFocus.toString().indexOf('function') < 0) {
					otherFocus = function(){otherFocus}
				}
				myObj.focus2 = otherFocus;
				myObj.onfocus = function(){
					this.focus2();
					this.blur();
				};
			}
		}
	}
	//END de-focusing buttons//
}

function setNetscapeEvent(x) { NetscapeEvent = x; }






/////////////////////////////////////////////////////////////////////////////////////////
// Navigate from any subframe without having to change target paths to the main frame. //
/////////////////////////////////////////////////////////////////////////////////////////
function nav(x) {
	if(mainFrame == self && mainFrame.relative_nav == true) {
		//var relative_nav MUST be set in the calling document if used at all
		mainFrame.location = x;
	} else {
		mainFrame.location = root + x;
	}
}



//////////////////////////////////////////////////////////////////////////////////////////////
// Create a standard pop-up window that can be called dynamically from anywhere in the site //
//////////////////////////////////////////////////////////////////////////////////////////////
function small_window(path,x,y) {
	var iQ = path.indexOf('?');	//find out if path already has a query string//
	path = path + ( (iQ > 0 && path.indexOf('=') > iQ)? '&':'?' ) + 'smallwindow=1';
	x = (x == undefined)? 400 : x;
	y = (y == undefined)? 200 : y;
	var centerV = (screen.height / 2) - (y / 2);
	var centerH = (screen.width / 2) - (x / 2);
	path = (path.indexOf(':')>0 || path == '')? path : root + path;	//allow for "about:blank"
	top.childWindow = window.open(path, "small_window", 'height='+y+',width='+x+
		',left='+centerH+',top='+centerV+',status=0');
}



//////////////////////////////////////////////////////////////////////////////////
// The regexps in the object checkFieldTest are to exclude certain characters.	//
// The function is called in the onKeyUp or a similar handler from form fields.	//
//////////////////////////////////////////////////////////////////////////////////
var checkFieldTest = {
	numDigits2	: {replacer: /\D|^(\d{2}).+/g, checker: /\D|^\d{2}.+/},
	numbers		: {replacer: /\D()/g, checker: /\D/},
	ranges		: {replacer: /[^\d\-,]()/g, checker: /[^\d\-,]/},
	decimal		: {replacer: /[^\d\.]()/g, checker: /[^\d\.]/},
	noquotes	: {replacer: /["']()/g, checker: /['"]/},
	username	: {replacer: /\W|^[^A-z]+()/g, checker: /\W|^[^A-z]+/},
	email		: {replacer: /[^\w@\-.]()/g, checker: /[^\w@\-.]/} /*|([@\-.])[@\-.]+|^[_@\-.]+/g,
	cc			: /[^\w@\-.,;\s]|([@\-.,;\s])[@\-.,;]+|^[_@\-.,;\s]+/g*/
}
function checkField(field, checkset) {
	checkset = (checkset == undefined)? field.name : checkset;
	var checkExp = eval("checkFieldTest."+checkset+".replacer");
	var newValue = field.value.replace(checkExp, "$1");
	//field.value = field.value.replace(checkExp, "");
	/*if(checkset == 'cc') {	// let the cursor jump to the end of multiple spaces //
		newValue = newValue.replace(/(\s)\s+/, "$1");
	}*/
	
	checkExp = eval("checkFieldTest."+checkset+".checker");
	//Do all this nonesense to make sure the cursor ends up in the same position it started
	if(field.setSelectionRange) { //Netscape
		var caretPosition = field.selectionStart;
		if(checkExp.test(field.value)) { caretPosition-- }
		field.value = newValue;
		field.setSelectionRange(caretPosition, caretPosition);
	} else if(field.createTextRange) { //IE
		//Get cursor position via empty selection range
		var sel = document.selection.createRange();
		//Move selection start to 0 position
		sel.moveStart ('character', -field.value.length);
		//The caret position is selection length
		var caretPosition = sel.text.length
		if(checkExp.test(field.value)) { caretPosition-- }
		field.value = newValue;
		sel.collapse();
		sel.move('character', caretPosition);
		sel.select();
	}
	
}


//////////////////////////////////////////////////////////////////////////////////////////
// Toggle a form field between blank space and some default guide text, like "(email)".	//
// Fields that call this should do so with both onFocus AND onBlur handlers, and have	//
// starting/default values that match the value of guideText, the second argument.		//
//////////////////////////////////////////////////////////////////////////////////////////
function emptyField(field, guideText) {
	if(field.value == guideText) {
		field.value = '';
	} else if(emptyExp.test(field.value)) {
		field.value = guideText;
	}
}


//////////////////////////////////////////////////////////////////////////
// Compose & submit data to the emailer form. Recipients is a space-	//
// delimited list of full email addresses and/or local email aliases.	//
//////////////////////////////////////////////////////////////////////////
function mail(recipients, subject, cc) {
	var page = mainFrame.location.href;
	recipients = (recipients == undefined || recipients == '')? mailAliasDefault : recipients;
	subject = (subject == undefined)? '' : subject;
	if(cc != undefined && cc != '' && !emailExp.test(cc)) {
		cc += '@' + myDomain;
	} else {
		cc = '';
	}
	nav(mail_url+'?compose=1&recipients=' + escape(recipients) +
		'&subject=' + subject + '&cc=' + cc + '&page=' + escape(page));
	//page must be escaped in case it contains a query string//
}


//////////////////////////////////////////////////////////////////////////
// Write-in email links dynamically so email-harvesting spiders can't	//
// get them from the source code. Call with in-line script tag:			//
// document.write( write_email_link('name','alias' [,'emailDomain']) );	//
//////////////////////////////////////////////////////////////////////////
function write_email_link(name, alias, emailDomain, subject, cc) {
	name		= (name == undefined || name == '')?				mailNameAdmin	: name;
	alias		= (alias == undefined || alias == '')?				mailAliasAdmin	: alias;
	emailDomain = (emailDomain == undefined || emailDomain == '')?	myDomain		: emailDomain;
	subject		= (subject == undefined)?							''				: subject;
	cc			= (cc == undefined)?								''				: cc;
	var atOffsiteDomain = '';
	if(emailDomain != myDomain) {
		atOffsiteDomain = '@'+ emailDomain;
	}
	return	'<a href="javascript:mail(\''+ name +'\',\''+ alias + atOffsiteDomain +'\',\''+
			subject +'\',\''+ cc +'\');" title="'+ alias +'@'+ emailDomain +
			'" class="link">' +
			alias +'@'+ emailDomain +'</a>';
}


/////////////////////////////
//Downloading PDF Functions//
var subFrame = false;	//if using download_frame.html

function loading(x) {	//x = hide|show;//
	var layer = top.document.getElementById('downloading');
	if(layer == undefined) { return }
	if(x == 'show' && layer.style.visibility == 'hidden') {
		divLeft = (Netscape)? (top.window.outerWidth / 2) : (top.document.body.clientWidth / 2);
		divTop = (Netscape)? (top.window.innerHeight / 2) + top.window.scrollY :
			((top.document.body.clientHeight / 2) + top.document.body.scrollTop);
		with(layer.style) {
			left = divLeft - (layer.offsetWidth / 2);
			top = divTop - (layer.offsetHeight / 2);
			visibility = 'visible';
		}
		return;
	} else if(x == 'hide' && layer.style.visibility != 'hidden') {
		layer.style.visibility = 'hidden';
		//stop(); //causes error in IE
		//mainFrame.location.reload(false);
	}
}

function download(resources,as,zip,targ) {
	//to start an os-dependant "save as" dialog box for this download, make 4th arg='direct' && set dialog=1 in query string//
	var target = (typeof(targ) == 'object')? targ : mainFrame.document;
	var dialog = (targ == 'direct')? 1 : '';
	var script = (as == undefined || as == '')? 'download.cgi' : as;
	var zipExp = /\.zip/;
	if(zip || zipExp.test(as)) {
		script = script.replace(/\.[^\.]*$/, ".zip");
		zip = 1;
	} else {
		if(!dialog) {	//specify 'direct' in 4th arg when using application/octet-stream downloads//
			loading('show');
		}
		zip = 0;
	}
	
	if(subFrame && target == mainFrame.document) {
		var framed = '&frame=1';
		nav(download_frame_url +'?'+ root + download_url_dir +
			script +'?resources='+ resources +'&archive='+ zip +'&script='+ script + framed);
	} else {
		target.location = root + download_url_dir + script +'?resources='+
				resources +'&archive='+ zip +'&script='+ script +'&dialog='+ dialog +'&page='+ escape(location);
	}
	//as with function reframe(), we want to disable errors caused by code//
	//that is still loaded and responding to mouse events. //
	onerror = function(){return true}
}

function pnSearch(pn) {
	nav('products/literature/download_frame.html?'+ root +'cgi-bin/products/literature/resource_search.cgi?part_number='+ escape(pn));
}



/////////////////////////////////////////////////////////////////////
//Write in menus.js, which controlls the pop-up and drop-down menus//
/////////////////////////////////////////////////////////////////////
if(self.name != 'small_window' && self.name != 'dd_menus') {
	document.write('<script language="JavaScript" src="'+root+'js/menus.js"></script>');
//alert(self.name);
}

