function resultPopUp(url,winName)
{
  var width = 700;
  var height = 550;
  resultPopUp2(url,winName,width,height);
}

function resultPopUp2(url,winName,width,height)
{
  var scrolling = "yes";
  var features = "width="+width+",";
  features += "height="+height+",";
  features += "toolbar=no,";
  features += "location=no,";
  features += "status=no,";
  features += "menubar=yes,";
  features += "resizable=yes,";
  features += "scrollbars="+scrolling+",";
  features += "top="+(window.screen.height-height)/2+",";
  features += "left="+(window.screen.width-width)/2;
  var newWin = window.open(url,winName,features);
  newWin.focus();
}

function emailValid(emailStr, confirmEmail)
{
	if (emailStr.length === 0)
    {
    	return false;
    }
    if (emailStr != confirmEmail)
    {
        return false;
    }

    // TLD checking turned off by default
    var checkTLD=1;
    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null)
    {
    	return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    for (i=0; i<user.length; i++)
    {
        if (user.charCodeAt(i)>127)
        {
            return false;
        }
    }
    for (i=0; i<domain.length; i++)
    {
        if (domain.charCodeAt(i)>127)
        {
            return false;
        }
    }
    if (user.match(userPat)==null)
    {
        return false;
    }
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null)
    {
        for (var i=1;i<=4;i++)
        {
            if (IPArray[i]>255)
            {
                return false;
            }
        }
        return true;
    }
    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++)
    {
        if (domArr[i].search(atomPat)==-1)
        {
            return false;
        }
    }
    if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
    {
        return false;
    }
    if (len<2)
    {
        return false;
    }
    return true;
}

function checkContactUs(theForm)
{
  var pass = emailValid(theForm.email.value, theForm.confirmEmail.value) && theForm.name.value.length > 0;
  if (!pass)
  {
    alert("Please include your name, a valid email address, and a matching confirm email address.");
    return pass;
  }
  pass = theForm.message.value.length > 0;
  if (!pass)
  {
    alert("Please enter your question or comment before submitting.");
  }
  return pass;
}

function checkRequestKit(theForm)
{
  var checkRKMessages = ""; //success if remains empty

  for (var i = 1; i <= 6; i++)
  {
    if (i == 4) // 4 isn't on the form right now
        continue;
    if (!theForm["participate" + i + "-of-6"]["checked"])
    {
      checkRKMessages += "To participate, you must accept and comply with all the requirements, and check the corresponding checkboxes.\n";
      break;
    }
  }

  if (!emailValid(theForm.email.value, theForm.confirmEmail.value))
  {
    checkRKMessages += "Please enter a valid email address, and a matching confirm email address.\n";
  }

  if (trim(theForm["name"].value).length < 1)
  {
    checkRKMessages += "First name is required.\n";
  }
  if (trim(theForm["last"].value).length < 1)
  {
    checkRKMessages += "Last name is required.\n";
  }

  if (!(theForm["age"][0].checked || theForm["age"][1].checked || theForm["age"][2].checked))
  {
    checkRKMessages += "Age is required.\n";
  }

  if ( !(theForm["gender"][0].checked || theForm["gender"][1].checked))
  {
    checkRKMessages += "Gender is required.\n";
  }

  if (trim(theForm["address"].value).length < 1 || trim(theForm["city"].value).length < 1 || trim(theForm["state"].value).length < 1 || trim(theForm["zip"].value).length < 1)
  {
    checkRKMessages += "A complete mailing address (address, city, state, zip) is required.\n";
  }

  if (trim(theForm["phone"].value).length < 1)
  {
    checkRKMessages += "Phone number is required.  If unavailable, enter 'none'.\n";
  }
  
  if (theForm["How I heard about the project"].value == "none")
  {
    checkRKMessages += "Please tell us how you heard about SMGF.\n";
  }

  if (checkRKMessages.length > 0)
  {
    alert(checkRKMessages);
    return false; //failure
  }
  return true;
}

function checkSubscription(theForm)
{
  var pass = emailValid(theForm.email.value, theForm.email.value) && theForm.name.value.length > 0;
  if (!pass)
  {
    alert("Please include your name and valid email address.");
  }
  return pass;
}

function checkOptions(theForm)
{
  var pass = emailValid(theForm.email.value, theForm.email.value);
  if (!pass)
  {
    alert("Please include a valid email address.");
  }
  return pass;
}

function checkLogin(theForm)
{
  var pass = theForm.password.value.length > 0;
  if (!pass)
  {
    alert("Please enter your password.");
  }
  return pass;
}

function checkUpdate(theForm)
{
  var pass = theForm.new_email.value.length == 0 || emailValid(theForm.new_email.value, theForm.confirm_email.value);
  if (!pass)
  {
    alert("Please include a valid email address.");
    return pass;
  }

  pass = theForm.new_password.value.length == 0 || theForm.new_password.value == theForm.confirm_password.value;
  if (!pass)
  {
    alert("The passwords must match.");
  }
  return pass;
}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

function namedArrayLength(array)
{
    var count = 0;
    for (var i in array)
    {
        if (array[i].length > 0)
        {
            count++;
        }
    }
    return count;
}

function switchImage(imgId, source)
{
	var img = document.getElementById(imgId);
	img.src = source;
}

// helper function to set a value in a combo box
function setComboValue(elementId, selection, defaultSelection)
{
    // get the combo
    var comboBox = document.getElementById(elementId);
    if (comboBox == null)
	    return;

    // restore the selection
    var found = false;
    for (var i = 0; i < comboBox.options.length; i++)
    {
        if (comboBox.options[i].value == selection)
        {
            comboBox.selectedIndex = i;
            found = true;
            break;
        }
    }
    if (!found)
    {
        // Illegal value -- not in combobox so use default
        comboBox.selectedIndex = defaultSelection;
    }
}

// sets the text node of an element, adds it if not there
function setTextNode(name, value)
{
    var node = document.getElementById(name);
	for (var i = 0; i < node.childNodes.length; i++)
    {
        if (node.childNodes[i].nodeName == '#text')
        {
            node.childNodes[i].nodeValue = value;
            return;
        }
    }
    //if we get here there wasn't a text node so create one
    node.appendChild(document.createTextNode(value));
}

// get the text node value of an element
function getTextNode(name)
{
    var node = document.getElementById(name);
	for (var i = 0; i < node.childNodes.length; i++)
    {
        if (node.childNodes[i].nodeName == '#text')
        {
			return node.childNodes[i].nodeValue;
        }
    }
    return null;
}

// create a dom element
function createElement(type)
{
    if (document.createElementNS)
        return document.createElementNS('http://www.w3.org/1999/xhtml', type);
    return document.createElement(type);
}

// this function will find hrefs that have rel="external" and set the target attribute to _blank
// this is necessary because the target attribute is not valid in xhtml strict doctype
function externalLinks()
{
    if (!document.getElementsByTagName)
 	    return;

    var regex = new RegExp("^https?://" + window.location.host);
    $('a').each(function()
    {
        if (this.href && this.rel == 'external')
        {
            this.target = '_blank';
            // only change the class for non local links, we use .href here because it is guaranteed to return the absolute url
            if (!this.className && !this.href.match(regex))
                this.className = "external";
        }
    });
}
$(function()
{
    externalLinks();
});

// Trim string
function strTrim(str)
{
	if (str == null || str.length == 0)
	{
    	return str;
   	}
  	var idx0 = 0;
  	while (idx0 < str.length)
  	{
    	var c = str.charAt(idx0);
    	if (c == ' ' || c == '\n' || c == '\r' || c == '\t')
    	{
    		++idx0;
    	}
    	else
    	{
    		break;
    	}
	}
	var idx1 = str.length - 1;
	while (idx1 > idx0)
	{
    	var c = str.charAt(idx1);
    	if (c == ' ' || c == '\n' || c == '\r' || c == '\t')
    	{
    		--idx1;
    	}
    	else
    	{
    		break;
    	}
	}
	return str.substring(idx0, idx1 + 1);
}

// Read cookies
function getCookies()
{
	var cookies = new Array();
  	var cookieStr = document.cookie;
  	if (cookieStr != null && cookieStr.length > 0)
  	{
    	var cookieParts = cookieStr.split(';');
    	for (var i = 0; i < cookieParts.length; i++)
    	{
	        var part = strTrim(cookieParts[i]);
	        var eqIdx = part.indexOf('=');
	        if (eqIdx >= 0)
	        {
	        	var name = strTrim(part.substring(0, eqIdx));
	        	var value = strTrim(part.substring(eqIdx + 1, part.length));
	        	if (name.length > 0 && value.length > 0)
	        	{
	        		cookies[name] = value;
	        	}
			}
		}
	}
	return cookies;
}

function createCookie(name,value,days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ')
            c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name)
{
    createCookie(name,"",-1);
}

function setupLink(id, str1, str2)
{
    var element = document.getElementById(id);
    element.href = unescape(str1);
    setTextNode(id, unescape(str2));
}
