﻿//EUCLID TECHNOLOGY//
//euclidScripts.js//
//These functions are general for the entire website//
//3/30/09//


/*////////////////////// UITLITIES /////////////////////////////////////////*/

//displays debug message
//uses variable DEBUG (if DEBUG=true, display debug)
function debug(message){
	if(DEBUG){alert('DEBUG: \n\n'+message)};
}


//returns arbitrary parameter from the URL 
//example: URL = '../memberdll.dll/list?ismemberflg=Y&DOSEARCH=N&sort=LASTNAME
//getURLValue('DOSEARCH') -> N
function getURLValue(name){
	var finalValue = '';
	var URL = window.location + '';
	
	if(URL.match(name)){
		var tempSplitter = name+'=';
		var tempArr = URL.split(tempSplitter);
		var secondHalf = '';
		secondHalf = tempArr[1];

		
		//if parameters continue
		if(secondHalf.match('&')){
			var tempArr2 = secondHalf.split('&');
			finalValue = tempArr2[0];
		}else{
			finalValue = secondHalf;
		}
	}
	return finalValue;
}
//replaced with CVWEBRequired.js version
function Set_Cookie( name, value, expires, path, domain, secure ) {
	//alert('setting cookie!');
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


// get cookie value by cookie name
//replaced with CVWebRequired.js version
/*function GetCookieValue(name)
{
	//use AJAX request instead of actually reading cookie
	var cookieURL = '../logindll.dll/getCookieVal?cookiename='+name;
	alert(cookieURL);
	new Ajax.Request(cookieURL, {method:'get', asynchronous:false,
		onSuccess:function(content){
			var response = content.responseText || '';
			//alert(response);
			var cookieReturn = removeNL(response);
			return cookieReturn;
		},
		onFailure:function(){alert("An error occurred while reading your cookie. Please reload the page to try again.");}
	});
}*/
//LUCAS DUAL VERSION
function GetCookieValue(name)
{
                //use AJAX request instead of actually reading cookie
                var cookieURL = '../logindll.dll/getCookieVal?cookiename='+name;
                var cookieReturn = '';
                new Ajax.Request(cookieURL, {method:'get', asynchronous:false,
                                onSuccess:function(content){
                                                var response = content.responseText || '';
                                                //alert("cookie: " + response);
                                                cookieReturn = removeNL(response);
                                },
                                onFailure:function(){alert("An error occurred while reading your cookie. Please reload the page to try again.");}
                });
                
				if (cookieReturn == '')
				{
					//might be blank because it is a cookie that is not login related
					var allcookies = document.cookie;
					var pos = allcookies.indexOf(name+"=");
					if (pos != -1) 
					{
						var start = pos + name.length+1;
						var end = allcookies.indexOf(";", start);
						if (end == -1) 
						{
							end = allcookies.length+1;
						}	
						cookieReturn = allcookies.substring(start, end);
						cookieReturn = unescape(cookieReturn);	
					}
				}
				return cookieReturn;
}





//prints current page
function printpage() {
	window.print();  
}

//mails current page link
function mailpage()
{
	mail_str = "mailto:?subject=aca Send to a friend -- " + document.title;
	mail_str += "&body= This is a link to an item on the aca Website:" + "&nbsp;&nbsp;"+ location.href;
	location.href = mail_str;
}


// Prompt user before emptying shopping cart.
// NEILTAG 5/31/07
function emptyCartConfirmation() {
	var answer = confirm("Empty your cart?")
	if (answer){
		window.location = "ResetCart";
	}
}


//writes year dropdown from current year  -> (current year + addYears)
function selectYear(addYears){

	//alert('in selectYEars()');
	var d = new Date();
	var endYear = d.getFullYear();
	var currYear = d.getFullYear();
	var endYear = parseInt(endYear + addYears);
	
	document.write('<select name="expireyear">');
	document.write('<option value="">Choose...</option>');
	for(var i=currYear;i<=endYear;i++){
		document.write('<option value="'+i+'">'+i+'</option>');
	}
} 


//writes year options from startyear to endyear (must run from within select box)
//enter "NOW" for current year
// if startYear > endYear then go in descending order
//Jacob 4/16/09
function writeYear(startYear, endYear){
	var today = new Date();
	var writeString = '<option value=""></option>';
	//set start and end year
	if(startYear == 'NOW'){
		startYear = today.getFullYear();
	}
	
	if(endYear == 'NOW'){
		endYear = today.getFullYear();
	}
	
	if(startYear > endYear){
		for(var i=startYear; i>=endYear; i--){
			var yearThing = i+'';
			yearThing = yearThing.substring(2);
			writeString += '<option value="'+yearThing+'">'+i+'</option>';
		}
	}else{
		for(var i=startYear; i<= endYear; i++){
			var yearThing = i+'';
			yearThing = yearThing.substring(2);
			writeString += '<option value="'+yearThing+'">'+i+'</option>';
		}
	}
	document.write(writeString);
}
	
	
//default view for dates (MM/DD/YYYY)
Date.prototype.defaultView=function(){
	var dd=this.getDate();
	if(dd<10)dd='0'+dd;
		var mm=this.getMonth()+1;
	if(mm<10)mm='0'+mm;
		var yyyy=this.getFullYear();
		
	return String(mm+"\/"+dd+"\/"+yyyy);
}


/*///////////////////////// LOG IN FUNCTIONALITY /////////////////////////*/

//checks &REDIRECTURL= parameter in header and submits login 
function submitLogin(formName){
	//check for redirectURL
	var loc = window.location+'';
	//debug(loc);
	var temp = loc.split("REDIRECTURL=");
	var redirectURL = temp[1];
	//debug('redirecURL is: '+redirectURL);
	
	if((redirectURL != '') && (redirectURL != undefined)){
		formName.REDIRECTURL.value = redirectURL;
	}
	
	//alert('submitting!');
	formName.submit();
}

function displayLinks(){
	if(CUSTOMERCD == ''){
		$('menu_loggedOut').show();
		$('menu_loggedIn').hide();
	}else{
		$('menu_loggedOut').hide();
		$('menu_loggedIn').show();
	}
}


//sets "Remember Me" flag
function setRemember(){
		//alert('in setRemember');
		if(document.loggedIn.rememberMe.checked){
				Set_Cookie('rememberMe','Y',999,'/','','');
		}else{
				Set_Cookie('rememberMe','N',999,'/','','');
		}
}

//gets value of rememberMe to set checkbox
function getRemember(){
		//alert('in getRemember');
		if(GetCookieValue('rememberMe')=='Y'){
				document.loggedIn.rememberMe.checked=true;
		}else{
			document.loggedIn.rememberMe.checked=false;
		}
}
				

//to check cookie and redirect to Path if user has already logged in
function ResetLogin(Path) 
{
	document.login.CUSTOMERCD.value = CUSTOMERCD;
	var remembered = GetCookieValue('rememberMe');
	if ((document.login.CUSTOMERCD.value != "") && (remembered == 'Y'))
	{
		location.href = Path;
	}
	document.login.WEBUSERID.focus();
}

//handles login / logoff
function showLogin(){
	var loginCD = CUSTOMERCD;

	if(loginCD == ''){
		
		//alert('logged out');
		document.getElementById("loginDiv").style.display='block';
		document.getElementById("myAccountDiv").style.display='none';
	}else {
		//alert('logged in');
		document.getElementById("loginDiv").style.display='none';
		document.getElementById("myAccountDiv").style.display='block';
	}
}


// set REDIRECTURL hidden field value
function SetRedirectURL() 
{
	var RedirectStr=""
  
	if (location.search) 
	{
		RedirectStr=location.search.substring(1,255);
	}		
	document.login.REDIRECTURL.value=RedirectStr;	
}

// on the pageload check page access and redirect to the login page if necessery 
function CheckPageAccess()
{
	
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf("/") + 1);
	var doredirect = false;
	switch (sPage)
	{
		case "mbr_locator.shtml" : 
			doredirect = true;
			sPage = "../../"+sPage;
			break;
		case "awt_mainlogin_loggedon.shtml" :
			sPage = "../../"+sPage;
			doredirect = true;
			break;
		case "company_locator1.shtml" :
			sPage = "../../"+sPage;
			doredirect = true;
			break;	
	}
	if (doredirect)
	{
		var memberid = CUSTOMERCD;
		var ismember = ISMEMBERFLG;
		if ((memberid == "") || (ismember!="Y")) 
		{	
			//location.href = "awt_mainlogin1.shtml?"+sPage;
			alert("You must logon to our Member's Only site");	
			location.href="https://www.awt.org/awt_mainlogin.shtml";
		}
	}
}

//to check cookie and redirect to Path if user has already logged in
function ResetLogin(Path) 
{
	document.login.CUSTOMERCD.value = CUSTOMERCD;
	if (document.login.CUSTOMERCD.value != "") 
	{
		location.href = Path;
	}
	document.login.WEBUSERID.focus();
}



/*///////// NOT SURE WHAT THESE DO //////////////////////////////*/




function RunLogin() 
{
	var RedirectStr=""
  
	if (location.search) 
	{
		RedirectStr=location.search.substring(1,255);
	}		
	document.login.REDIRECTURL.value=RedirectStr;
	document.login.submit()
}


function getCursorPosition(el)
{
	if (document.selection)//IE
	{
		var range = document.selection.createRange();
		range.text = '';//delete selected text
		range.select();
		return (-1)*range.move("character", -100); //move selection to the first character. the result is the qty of moved characters that, actually, is a current cursor position
	}
	else //MOZILLA
	{
		var selStart = el.selectionStart; //get selection start point
		//delete selected text
		el.value = el.value.substring(0, selStart) + el.value.substring(el.selectionEnd, el.value.length); 
		return selStart;
	}	
}

function autoformat(el, e, mask)
{
	var CurrentElValue = el.value;
	var evt = (e) ? e : window.event; //IE:Mozilla
	var code = (document.all) ? evt.keyCode:evt.which; //IE:Mozilla
	var isAllowed = (code==0)||(code==8); //allow Backspace and all service key combination (Left, Right, Del, etc)
	code = String.fromCharCode(code);
		
    var CheckPattern = /^\d{1}$/; //checking pattern. one digital simbol
	var pos = getCursorPosition(el); //get current cursor position
		
	if (code.match(CheckPattern) || (code == mask.charAt(pos))) //if input simbol is digit or same as the mask
	{
		var InputVal = code+el.value.substring(pos); //start adding characters from current cursor position
		var OutputVal = el.value.substring(0,pos);	//part of the value for checking and formatting. 	
		for( k=0; k < InputVal.length; k++)
		{
			code = InputVal.charAt(k);	
			if (code.match(CheckPattern) )
			{
				for( i=OutputVal.length; i <= mask.length; i++)
				{
					var tChar = mask.charAt(i); //compare input simbol with mask
					if (tChar=='#') 
					{
						OutputVal = OutputVal+code; //replace # by input simbol and leave the loop.
						break;
					}
					else {OutputVal = OutputVal+tChar} //add character from mask and continue looping.
				}
			}
			else 
			{
				//allow to input mask character. for first, input character only
				if ( (code == mask.charAt(pos)) && (k==0) ) {OutputVal = OutputVal+code} 
			}
		}
		el.value=OutputVal; //return the result
	}
	else
	{
		if (!isAllowed) 
		{
			el.value = CurrentElValue; //restore element value
			alert('invalid character');
		}
	}
		
	
	if ('\v'=='v'){e.returnValue = false;} //IE
	else
	{
		if (!isAllowed) {e.preventDefault();} //Mozilla
	}	
}

var MaskPool = new Array('(###) ###-####','##/##/####');


function switchDateMask(val)
{
	switch(val)
	{
		case "1":
			MaskPool[1]='##/##/####';
  			break;
		case "2":
			MaskPool[1]='##.##.##';
		    break;
		default:
			MaskPool[1]='##/##/####';
	}
}


function switchMask(val)
{
	switch(val)
	{
		case "1":
			MaskPool[0]='(###) ###-####';
  			break;
		case "2":
			MaskPool[0]='+1(###) ###-####';
		    break;
		case "3":
			MaskPool[0]='';
		    break;
		case "4":
			MaskPool[0]='########################';
		    break;
		default:
			MaskPool[0]='(###) ###-####';
	}
}

function switchPhoneMask(val)
{
	if (val=='USA')
	{
			MaskPool[0]='(###) ###-####';
	}
	else 
	{
			MaskPool[0]='+########################';
	}
}


function autoformatWithPool(el, e, maskStr, PoolIndex)
{
	var CurrentElValue = el.value;
	var evt = (e) ? e : window.event; //IE:Mozilla
	var code = (document.all) ? evt.keyCode:evt.which; //IE:Mozilla
	var mask = maskStr;
	if (PoolIndex>-1) {mask = MaskPool[PoolIndex]};
	if (mask!='')
	{
		var isAllowed = (code==0)||(code==8); //allow Backspace and all service key combination (Left, Right, Del, etc)
		code = String.fromCharCode(code);
		
	    var CheckPattern = /^\d{1}$/; //checking pattern. one digital simbol
		if(MaskPool[0]=='+########################'){
			CheckPattern = /^\d{1}|-|\(|\)|\s$/;	
		}
		
		var pos = getCursorPosition(el); //get current cursor position
		
		if (code.match(CheckPattern) || (code == mask.charAt(pos))) //if input simbol is digit or same as the mask
		{
			var InputVal = code+el.value.substring(pos); //start adding characters from current cursor position
			var OutputVal = el.value.substring(0,pos);	//part of the value for checking and formatting. 	
			for( k=0; k < InputVal.length; k++)
			{
				code = InputVal.charAt(k);	
				if (code.match(CheckPattern) )
				{
					for( i=OutputVal.length; i <= mask.length; i++)
					{
						var tChar = mask.charAt(i); //compare input simbol with mask
						if (tChar=='#') 
						{
							OutputVal = OutputVal+code; //replace # by input simbol and leave the loop.
							break;
						}
						else {OutputVal = OutputVal+tChar} //add character from mask and continue looping.
					}
				}
				else 
				{
					//allow to input mask character. for first, input character only
					if ( (code == mask.charAt(pos)) && (k==0) ) {OutputVal = OutputVal+code} 
				}
			}
			el.value=OutputVal; //return the result
		}
		else
		{
			if (!isAllowed) 
			{
				el.value = CurrentElValue; //restore element value
				alert('invalid character');
			}
		}
		
	
		if ('\v'=='v'){e.returnValue = false;} //IE
		else
		{
			if (!isAllowed) {e.preventDefault();} //Mozilla
		}	
	}	
}

function checkNobox(itemname, elmname,formname)
{
	
	if (eval("document."+elmname+".checked"))
	{
		eval("document.abc."+itemname+".value='Y'");
	}
	else
	{
		eval("document.abc."+itemname+".value='N'");
	}
	return true;
	
}	

function checkNobox2(element){
	if(element.checked){
		element.value ="Y";
	}
	else
	{
		element.value="N";
	}	
}


var xmlHttp;
var isMozilla = false;
var AJAXresultID = "";
                
function createXMLHttpRequest()
{
	if (window.ActiveXObject)
    {
    	xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
    else if (window.XMLHttpRequest)
    {
    	xmlHttp = new XMLHttpRequest();
        isMozilla = true;
	}
}

function doAjaxFill2(HREF, URL, fieldToFill) 
{
	
    var URLaddress = HREF+'://'+URL;
	AJAXresultID = fieldToFill;
	//alert(URLaddress);
    createXMLHttpRequest();
    if(!isMozilla){xmlHttp.onreadystatechange = handleStateChange;}
    xmlHttp.open("get",URLaddress, false);
    xmlHttp.send(null);
    if(isMozilla){xmlHttp.onreadystatechange = handleStateChange();}
}    
	

            
function handleStateChange()
{
	if (xmlHttp.readyState==4)
    {
    	if (xmlHttp.status==200)
        {        	
			document.getElementById(AJAXresultID).innerHTML = xmlHttp.responseText;
		}
	}
}

//LUCAS taken from CVWebRequired.js
//takes parameters in a hash (params) and submits as a post instead of get
function createPOST(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var newForm = document.createElement("form");
    newForm.setAttribute("method", method);
    newForm.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        newForm.appendChild(hiddenField);
    }

	document.body.appendChild(newForm);    
    newForm.submit();
}

//LUCAS taken from CVWebRequired.js
function checkSSL(){
	var loc = window.location + '';
	if(!loc.match('https://')){
		newLoc = loc.replace('http://','https://');
		window.location = newLoc;
	}
}
