﻿//EUCLID TECHNOLOGY CVWEB SCRIPTS//
//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 != undefined){
			if(secondHalf.match('&')){
				var tempArr2 = secondHalf.split('&');
				finalValue = tempArr2[0];
			}else{
				finalValue = secondHalf;
			}
		}
	}
	return finalValue;
}



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
function GetCookieValue(name)
{
	var allcookies = document.cookie;
	var value = "";
	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;
		}	
		value = allcookies.substring(start, end);
		value = unescape(value);			
	}
	return value;		
}


//opens a list of committee checkboxes for submitted customercd
function committeeWindow(customercd){
	window.open("../memberdll.dll/customlist?SQLNAME=committee&c.typecd=|IN|!elg!|!elg_sub!&customercd="+customercd+"&sort=name&whp=joinComm_header.htm&wbp=joinComm_list.htm&wmt=none&sort=name")
}




//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;
}


// Search for organization name.
// NEILTAG 6/4/07
function RunOrgSearch() {	
	var tmpsearch = document.abc.ORGNAME.value;
	if (tmpsearch.length < 2) {
		alert('Please enter the first two characters (or more) of the organization name');
		document.abc.ORGNAME.focus();
		return false;
	} else {
		tmpsearch = tmpsearch + '~';   
		window.open("../organizationdll.dll/List?ORGNAME="+tmpsearch+"&SORT=ORGNAME&WMT=none&WHP=OrganizationHeader.htm&WBP=OrganizationAddForm.htm&RANGE=1/25","","fullscreen=no,location=yes,toolbar=no,menubar=yes,scrollbars=yes,resizable=yes,width=640,height=480")
		return true;
	}
}   


// Prompt user before emptying shopping cart.
// NEILTAG 5/31/07
function emptyCartConfirmation() {
	var answer = confirm("Empty your cart?")
	if (answer){
		window.location = "ResetCart?wrp=emptycartmessage.htm";
	}
}

/*///////////////////////// LOG IN FUNCTIONALITY /////////////////////////*/

function submitLogin(formName){
	//alert('in submitLogin');
	//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!');
	document.login.submit();
}

function displayLinks(){
	//if(GetCookieValue('memberid') == ''){
	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 = GetCookieValue("memberid");
	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 = GetCookieValue('customercd');
	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 = GetCookieValue("memberid");
		//var ismember = GetCookieValue("ismember");
		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 = GetCookieValue("memberid");
	document.login.CUSTOMERCD.value = CUSTOMERCD;
	
	if (document.login.CUSTOMERCD.value != "") 
	{
		location.href = Path;
	}
	document.login.WEBUSERID.focus();
}



/*////////////// CREDIT CARD CHECK ///////////////////////////////*/
// Make sure a Card Type is selected.
function isCardtype()
	{
	var count = 0;
	for (var i = 0; i <= 2; i++)
		{
		if (document.order.PAYMENTTYPECD[i].checked==true)
			{
			count = count + 1;
			}
		}
		
	 if (count==0)
		{
			alert("\nYou must choose a Card Type.")
			document.order.PAYMENTTYPECD[0].focus();
			return false;
		}
		else
		{
		  return true;
		}	
	}	
       
//This script was written by yosarian@cyberramp.net
//I made some minor changes 
function verify_ccard(inNumber, type)
{// returns 0 if valid, positive number if invalid.
        total = 1*0;
        tmp = 1*0;

        number = "";

        // make sure there are only numbers in the string...
        for(i = 0; i < inNumber.length; i++)
        {
		if(inNumber.charAt(i) >= "0" && inNumber.charAt(i) <= "9")
                {
                        number = number + inNumber.charAt(i);
                }
        }

        if(number.length < 13) return 10; // too short for anything

        first = "" + number.charAt(0);
        second = "" + number.charAt(1);
        third = "" + number.charAt(2);
        firstTwo = first + second;
        firstFour = firstTwo + third + number.charAt(3);

        if(type == "MC")
        {
                if(first != "5" || second < "1" || second > "5")
                        return 11;// invalid Mastercard prefix
                if(number.length != 16)
                        return 21;
        }
        else if(type == "VISA")
        {
                if(first != "4")
                        return 12;// invalid Visa prefix
                if(number.length != 13 && number.length != 16)
                        return 22;
        }
        else if(type == "AMEX")
        {
                if(first != "3" || (second != "4" && second != "7"))
                        return 13;// invalid American Express Prefix
                if(number.length != 15) 
                        return 23;
        }

        // now check the credit card suffix and length vs. the type

    
         // do the check sum
        for(loc = number.length - 2; loc >= 0; loc -= 2)
        {
                total += 1 * number.charAt(loc +1);
                tmp = number.charAt(loc) * 2;
		if(tmp > 9) total += 1;
		total += tmp%10;
        }
	if(number.length % 2 > 0)
	total += 1 * number.charAt(0);


        return (total % 10);
}


function cardConfirm()
{
	for (var i = 0; i <= 2; i++)
		{
		if (document.order.PAYMENTTYPECD[i].checked==true)
		var cardtype = document.order.PAYMENTTYPECD[i].value;
			{
			}
		}
        if((reason = verify_ccard(document.order.PAYMENTREFNUM.value, cardtype)) == 0)
        {
			 return true;
        }
        else
        {
                alert("Card Number Invalid.");
                document.order.PAYMENTREFNUM.focus();
                return false;
        }
}

function isExpmonth()
{
	var mymonth=document.order.expiremonth.selectedIndex;
	if (mymonth==0) 
		{
			alert("\nYou must select Expiration month from the dropdown box.");
			document.order.expiremonth.focus();
		   	return false; 
		}
	else  
		{
		      return true;
 		}	     
}

function isExpyear() {
   var str = document.order.expireyear.value;
     // Return false if Exp. Date year is blank.
   
   if (document.order.expireyear.value == "") {
         alert("\nThe Exp. Date year is required.");
         document.order.expireyear.focus();
         return false;
   }
   // Return false if characters are not any of the following. 
		var ch = document.order.expireyear.value;
		if ( (ch != "05") && (ch != "06") && (ch != "07") && (ch != "08") && (ch != "09") && (ch != "10") && (ch != "11") && (ch != "12") ) {
         alert("\nPlease enter the correct expiration year.");
         document.order.expireyear.select();
         document.order.expireyear.focus();
         return false;
      }
    		return true;
}

function isExpdate() {
	var month = document.order.expiremonth.value;
	var year = document.order.expireyear.value;
	var expiredate;
	expiredate = month + "/" + year;
	document.order.PAYMENTREFEXPDATE.value = expiredate;
	return true;
}

//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();
}


/*///////// 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()
}


