//For popUp window and help buttons
function open_win(URL,WindowName,Features)
{
	if (typeof(winRef) != "object"){
	   winRef = window.open(URL,WindowName,Features);
	} else {
	if (!winRef.closed){
	   winRef.location.href = URL;
	} else {
	   winRef = window.open(URL,WindowName,Features);
	}
}
winRef.focus();

}
function emailValidatePopupWrapper()
{
	var emField = document.getElementById('emailadd');
	if (checkEmail(emField))
	{
		OpenMoreDetailsPopupAndSubmit();
	}
}
function OpenMoreDetailsPopupAndSubmit()
{
	var txtEmail = document.getElementById('emailadd');

	var win = open_win("validate.htm?txtSFEmail=" + txtEmail.value,"openWin","toolbar=no,location=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=400,height=400")

	document.EMsignup.submit();
	return false; // cancel the link

}

function checkEmail(emField){
	var fieldValue = emField.value  // store field's value in variable, "fieldValue"

	if(fieldValue != ""){  //if field is not empty
		var atSymbol = 0		   
	   for(var a = 0; a < fieldValue.length; a++){ //loop through field value string
		   if(fieldValue.charAt(a) == "@"){ //look for @ symbol and for each @ found, increment atSymbol variable by 1
				atSymbol++
		   }
	   }
	   
	   if(atSymbol > 1){ // if more than 1 @ symbol exists
			alert("Please enter a valid email address. "+fieldValue) // then cancel
			return false
	   }
	   
	   if(atSymbol == 1 && fieldValue.charAt(0) != "@"){  // if @ symbol was found, and it is not the 1st character in string
		   var period = fieldValue.indexOf(".",fieldValue.indexOf("@")+2) //look for period at 2nd character after @ symbol
		   var twoPeriods = (fieldValue.charAt((period+1)) == ".") ? true : false // "."  immediately following 1st "." ?
					 
			//if period was not found OR 2 periods together OR field contains less than 5 characters OR period is in last position
		   if(period == -1 || twoPeriods || fieldValue.length < period + 2 || fieldValue.charAt(fieldValue.length-1)=="."){
			   alert("Please enter a valid email address. "+fieldValue) // then cancel
			   return false
		   }
				   
	   }
	   else{  // no @ symbol exists or it is in position 0 (the first character of the field)
		   alert("Please enter a valid email address. "+fieldValue)
		   return false // then cancel
	   }
   }
   else{  // if field is empty
	   alert("Please Enter A Valid Email Address "+fieldValue)
	   return false  // then cancel
   }
   
return true
}

function getValue(varname)
{
  // First, we load the URL into a variable
  var url = window.location.href;

  // Next, split the url by the ?
  var qparts = url.split("?");

  // Check that there is a querystring, return "" if not
  if (qparts.length == 0)
  {
    return "";
  }

  // Then find the querystring, everything after the ?
  var query = qparts[1];

  // Split the query string into variables (separates by &s)
  var vars = query.split("&");

  // Initialize the value with "" as default
  var value = "";

  // Iterate through vars, checking each one for varname
  for (i=0;i<vars.length;i++)
  {
    // Split the variable by =, which splits name and value
    var parts = vars[i].split("=");
    
    // Check if the correct variable
    if (parts[0] == varname)
    {
      // Load value into variable
      value = parts[1];

      // End the loop
      break;
    }
  }
  
  // Convert escape code
  value = unescape(value);

  // Convert "+"s to " "s
  value.replace(/\+/g," ");

  // Return the value
  return value;
}

/* 
 * Cross-browser event handling, by Scott Andrew
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}

/* 
 * Cross-browser style extraction, from the JavaScript & DHTML Cookbook
 * <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
 */
function getElementStyle(elementID, CssStyleProperty) {
    var element = document.getElementById(elementID);
    if (element.currentStyle) {
        return element.currentStyle[toCamelCase(CssStyleProperty)];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(element, '');
        return compStyle.getPropertyValue(CssStyleProperty);
    } else {
        return '';
    }
}

/* 
 * CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
 * From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>
 */
function toCamelCase(CssProperty) {
    var stringArray = CssProperty.toLowerCase().split('-');
    if (stringArray.length == 1) {
        return stringArray[0];
    }
    var ret = (CssProperty.indexOf("-") == 0)
              ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
              : stringArray[0];
    for (var i = 1; i < stringArray.length; i++) {
        var s = stringArray[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1);
    }
    return ret;
}

/*
 * Disables all 'test' links, that point to the href '#', by Ross Shannon
 */
function disableTestLinks() {
  var pageLinks = document.getElementsByTagName('a');
  for (var i=0; i<pageLinks.length; i++) {
    if (pageLinks[i].href.match(/[^#]#$/)) {
      addEvent(pageLinks[i], 'click', knackerEvent, false);
    }
  }
}

/* 
 * Cookie functions
 */
function createCookie(name, value, days) {
    var expires = '';
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
    var cookieCrumbs = document.cookie.split(';');
    var nameToFind = name + '=';
    for (var i = 0; i < cookieCrumbs.length; i++) {
        var crumb = cookieCrumbs[i];
        while (crumb.charAt(0) == ' ') {
            crumb = crumb.substring(1, crumb.length); /* delete spaces */
        }
        if (crumb.indexOf(nameToFind) == 0) {
            return crumb.substring(nameToFind.length, crumb.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, '', -1);
}

/*
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 *
 * by Ross Shannon, http://www.yourhtmlsource.com/
 */

addEvent(window, 'load', init, false);

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && theInput.className.match(/\bemailcapture\b/)) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}

function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}
