// Clas functions for DuraLockC.com
// Compatible with IE5+, Netscape 7+ and Firefox										//
// Designed as a standard library of variables and functions used by most of the pages	//
// in the Frameset website. The variable siteIndex MUST be set to 1 in the /index.html	//
// (frameset) file, as it's integral in the process of re-framing pages that are loaded	//
// independantly of the main frameset.
// * Customizable Variables *
// var myEntity (in main)
// var mailNameAdmin and all other mail[Name|Alias]_* variables (in main)
// var rootExp & domExp (in main - FOR LOCAL SITE ONLY)
// function reframe (url replacement expressions)

// Standard Variables //
var myEntity			= 'Medcomp®';	// company or website trademark / proper name
var myDisplaySeparator	= '    »   ';	// goes betweem myEntity & message in the status bar
var mailNameAdmin		= 'Eric Harris';
var mailAliasAdmin		= 'webmaster';
var mailNameIntl		= 'Doreen Kibblehouse';
var mailAliasIntl		= 'doreen';
//var mailNameDom			= 'Frank DeBartola';
//var mailAliasDom		= 'fdebartola';
//var mailNameClinical	= 'Sue Hess';
//var mailAliasClinical	= 'shess';
var mailNameDefault		= mailNameIntl;
var mailAliasDefault	= mailAliasIntl;
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/download/';	//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();


////////////////////////////////////////////////
// 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	= /^(.+\/duralockc.com\/)\??(.*[^\/]+(\.html)?.*$3?.*$3?.*)$/i;
		domExp	= /^(.+)\/(duralockc.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">');
}


///////////////////////////////////////////////////////////////////
// Re-frame pages that were loaded outside of the main frameset. //
///////////////////////////////////////////////////////////////////
if(top.location != self.location) { reframe(self.location) }
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$/,"/");
		// *CUSTOMIZE: replace any other page urls, such as sub-framed pages, etc.
		//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.	//
//////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////////////////
// 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 = self;
onload_list.push('loaded = 1;');	//use this method to add functions to document event handlers

//Netscape puts no space around form elements, so add a style to match their look to those in IE.
//document.styleSheets.* is not yet available in Netscape, so use this method:
if(Netscape) {
//	document.write('<LINK REL="stylesheet" type="text/css" href="'+ root +'netscape.css">');
}

//Uncomment the below 3 lines unless the tags already appear in all document templates
//document.write('<link rel="P3Pv1" href="/w3c/p3p.xml">');
//document.write('<LINK REL="SHORTCUT ICON" HREF="/Martech.ico">');
//document.write('<META NAME="ROBOTS" CONTENT="NOARCHIVE">');

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() {
	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.	//
	//////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////
// Execute these commands at the end of all other onLoad functions (onload_list). //
////////////////////////////////////////////////////////////////////////////////////
function afterLoad() {
	//update login/logout links, if applicable//
	/*if(top.document.getElementById('registration_link')) {
		if(document.cookie.indexOf('login=') > 0) {
			var username = document.cookie.replace(/^.*login=([^;]*);?.*$/, "$1");
			//display username//
			with(top.document.getElementById('registration_link')) {
				title = 'Edit Your Membership Data';
				innerHTML = 'EDIT MEMBERSHIP';
			}
			with(top.document.getElementById('username_span')) {
				innerHTML = username.toUpperCase();
				title = 'Member Tools for '+ username;
				style.visibility = '';
			}
			with(top.document.getElementById('login_link')) {
				href = 'cgi-bin/members/logout.cgi';
				title = 'Log Out';
				innerHTML = 'LOG OUT';
			}
		} else {//display registration & log in links//
			with(top.document.getElementById('registration_link')) {
				title = 'Register For Membership';
				innerHTML = 'MEMBERSHIP FORM';
			}
			with(top.document.getElementById('username_span')) {
				innerHTML = username;
				style.visibility = 'hidden';
			}
			with(top.document.getElementById('login_link')) {
				href = '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//
	
}


/////////////////////////////////////////////////////////////////////////////////////////
// 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;
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////
// Launch the "Add Favorite" dialog in IE. Mozilla doesn't give script access for bookmarks. //
///////////////////////////////////////////////////////////////////////////////////////////////
function bookmark() {
	if(IE) {
		window.external.AddFavorite(mainFrame.location.href, mainFrame.document.title);
	} else {
		alert('Netscape/Mozilla/Firefox Users: \n Press Cntrl + D to Bookmark This Page');
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////
// 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/},
	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('cgi-bin/contact/email.cgi?compose=1&recipients=' + escape(recipients) +
		'&subject=' + subject + '&cc=' + cc + '&page=' + escape(page));
	//page must be escaped in case it contains a query string//
}


function download(resources,as,zip,targ,dialog) {
	//to start an os-dependant "save as" dialog box for this download, set dialog=1//
	var target = (typeof(targ) == 'object')? targ : mainFrame.document;
	//var extExp = /\.(pdf|zip)$/;
	//var script = (as == undefined || !extExp.test(as))? 'download.cgi' : as;
	var script = (as == undefined)? 'download.cgi' : as;
	dialog = (dialog == undefined)? 0 : 1;
	var zipExp = /\.zip/;
	if(zip || zipExp.test(as)) {
		script = script.replace(/\.[^\.]*$/, ".zip");
		zip = 1;
	} else {
		zip = 0;
	}
	
	//always use a dialog on this site
	dialog = 1;
	target.location = root + download_url_dir + script +'?resources='+
		resources +'&archive='+ zip +'&script='+ script +'&dialog='+ dialog +'&page='+ escape(location);
}


//////////////////////////////////////////////////////////////////////////////////////////////
// Since M$ IE decided to disable embedded activeX controlls - like Flash - until the user	//
// clicks on it once, this workaround is necessary to write-in the Flash object after the	//
// document loads. Push this function call into the onload_list array.						//
//////////////////////////////////////////////////////////////////////////////////////////////
function placeFlash(target, id, url, width, height, wmode) {
	url += '?root='+root;
	var protocol = (secureExp.test(root))? 'https' : 'http';
/*	if(document.cookie.indexOf('login=eharris') > 0) {
		alert(protocol);
	}*/
	document.getElementById(target).innerHTML = '<object classid="'+
		'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
		'codebase="'+protocol+'://fpdownload.macromedia.com/pub/shockwave/'+
		'cabs/flash/swflash.cab#version=7,0,0,0" '+
		'id="'+ id +'" width="'+ width +'" height="'+ height +'" style="position:absolute; top:0px; left:0px;">' +
		'<param name="movie" value="'+ url +'">'+
		'<param name="loop" value="false">'+
		'<param name="menu" value="false">'+
		'<param name="quality" value="high">'+
		'<param name="wmode" value="'+ wmode +'">'+
		'<param name="allowScriptAccess" value="sameDomain">'+
		'<embed src="'+ url +'" width="'+ width +'" height="'+ height +'" wmode="'+ wmode +
		'" loop="false" menu="false" quality="high" type="application/x-shockwave-flash" '+
		//'pluginspage="'+protocol+'://www.macromedia.com/go/getflashplayer" '+
		'pluginspage="'+protocol+'://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" '+
		'allowscriptaccess="sameDomain" name="'+ id +'">'+
		'</object>';
}


//////////////////////////////////////////////////////////////////////
// Functions for Drop-Down Menus. The code must run in all frames,	//
// even though the actual menus will only drop down in mainFrame.	//
//////////////////////////////////////////////////////////////////////
function setNetscapeEvent(x) { NetscapeEvent = x; }


//Google Analytics for main window pages:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12572967-6']);
_gaq.push(['_trackPageview']);

function initGoogleAnalytics() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}

onload_list.push("initGoogleAnalytics()");
//END Google


