var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isNN = (navigator.appName.indexOf("Netscape")!=-1) ? true : false;

var requiredMinorVersion = 0;
var requiredRevision = 0;

$(document).ready(function(){
	var currentButton = '';
	if(typeof parentDir != 'undefined'){currentButton = '#'+parentDir+'Button';}
	$("#menuButtons").find(currentButton).css('background-color','#fbb16a');
	
	$("#menuButtons > a").mouseover(function(){
		$("#menuButtons > a").not(this).not(currentButton).css("background-color","");
		$(this).css("background-color","#f7a85d");
	});
	$("#aboutButton").mouseover(function(event){
		$("#subMenus > div").not("#subMenuAbout").slideUp("fast");
		var posXY = $(this).offset();
		var tPos = posXY.top + $(this).outerHeight();
		var lPos = posXY.left;
		$("#subMenuAbout").css("left",lPos);
		$("#subMenuAbout").slideDown("400");
		event.stopPropagation();
	});
	$("#givingButton").mouseover(function(event){
		$("#subMenus > div").not("#subMenuGiving").slideUp("fast");
		var posXY = $(this).offset();
		$("#subMenuGiving").css("left",posXY.left);
		$("#subMenuGiving").slideDown("400");
		event.stopPropagation();
	});
	$("#subMenus > div").mouseover(function(event){
		event.stopImmediatePropagation();
	});
	$("body").mouseover(function(){
		$("#menuButtons > a").not(currentButton).css("background-color","");
		$("#subMenus > div").slideUp("fast");
	});
});

if(isIE)
{
	document.write('<scri');
	document.write('pt language="vbscript" type="text/vbscript" src="/sg-goodies/atomic.vbs"');
	document.write('><');
	document.write('/scri');
	document.write('pt>');
}

function getCookie(cookieName)
{
	if (document.cookie.length>0)
	  {
	  chrPos=document.cookie.indexOf(cookieName + '=');
	  if (chrPos!=-1)
	  { 
			chrPos=chrPos + cookieName.length+1; 
	    chrEnd=document.cookie.indexOf(';',chrPos);
	    if (chrEnd==-1) chrEnd=document.cookie.length;
	    return unescape(document.cookie.substring(chrPos,chrEnd));
    } 
  }
	return '';
} 

function getWidth()
{
	var frameWidth = '';
  if (self.innerWidth)
  {
		frameWidth = self.innerWidth;
  }
  else if (document.documentElement && document.documentElement.clientWidth)
  {
		frameWidth = document.documentElement.clientWidth;
  }
  else if (document.body)
  {
		frameWidth = document.body.clientWidth;
  }
  return frameWidth;
}

function getHeight()
{
	var frameHeight = '';
  if (self.innerHeight)
  {
		frameHeight = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
  {
		frameHeight = document.documentElement.clientHeight;
  }
  else if (document.body)
  {
		frameHeight = document.body.clientHeight;
  }
  return frameHeight;
}

function reDir(){
	location.href=self.location;
}

function timeAlert(){
	alert('Your session is about to time out.  Please submit this page before your lose the information that you have entered');	
	setTimeout('reDir()',260000);
}

function getStyleObject(objectId) 
{
  if(document.getElementById && document.getElementById(objectId)) 
	{
		// W3C DOM
		return document.getElementById(objectId).style;
  } else if (document.all && document.all(objectId)) {
		// MSIE 4 DOM
		return document.all(objectId).style;
  } else if (document.layers && document.layers[objectId]) {
		// NN 4 DOM
		return document.layers[objectId];
  } else {
		return false;
  }
} 

function changeObjectVisibility(objectId, newVisibility, newZindex)
{
  var styleObject = getStyleObject(objectId);
  if(styleObject) 
	{
		
		styleObject.visibility = newVisibility;
		styleObject.zIndex = newZindex;
		return true;
	} 
	else 
	{
		//couldn't find the object, can't change its visibility
		return false;
  }
}	
		
function findPos(styleObject) {
	var curleft = 0;
	var curtop = 0;
	if (styleObject.offsetParent) {
		curleft = styleObject.offsetLeft
		curtop = styleObject.offsetTop
		while (styleObject = styleObject.offsetParent) {
			curleft += styleObject.offsetLeft
			curtop += styleObject.offsetTop
		}
	}
	return [curleft,curtop];
}

function liftUp(whatItem)
{
	var styleObj = getStyleObject(whatItem);
	styleObj.zIndex = 10;
}

function dropDown(whatItem)
{
	var styleObj = getStyleObject(whatItem);
	styleObj.zIndex = 1;
}

function getFlashMovieObject(movieName)
{
	if (window.document[movieName])
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName];
	}
	else
	{
		return document.getElementById(movieName);
	}
}

function playFlash(whatMovie)
{
	var flashMovie = getFlashMovieObject(whatMovie);
	//var flashMovie = window.document[whatMovie];
	if(flashMovie == null)
	{
//    window.setTimeout('playFlash("'+whatMovie+'")',500);
	}
	else
	{
		flashMovie.Play();
	}
}

function ResetFlashMovie(whatMovie,whatFrame)
{
	var flashMovie = getFlashMovieObject(whatMovie);
	flashMovie.GotoFrame(whatFrame);
}

function SendDataToFlashMovie(whatMovie,whatTarget,whatData)
{
	var flashMovie=getFlashMovieObject(whatMovie);
	flashMovie.SetVariable(whatTarget,whatData);
}

function JSGetSwfVer(i)
{
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			descArray = flashDescription.split(" ");
			tempArrayMajor = descArray[2].split(".");
			versionMajor = tempArrayMajor[0];
			versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
      	} else {
			flashVer = -1;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	// Can't detect in all other cases
	else {
		
		flashVer = -1;
	}
	return flashVer;
} 

function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) 
{
 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
   	// loop backwards through the versions until we find the newest version	
	for (i=25;i>0;i--) {	
		if (isIE && isWin && !isOpera) {
			versionStr = VBGetSwfVer(i);
		} else {
			versionStr = JSGetSwfVer(i);		
		}
		if (versionStr == -1 ) 
		{ 
			//alert('no version');
			return false;
		} else if (versionStr != 0) {
			if(isIE && isWin && !isOpera) {
				tempArray         = versionStr.split(" ");
				tempString        = tempArray[1];
				versionArray      = tempString .split(",");				
			} else {
				versionArray      = versionStr.split(".");
			}
			versionMajor      = versionArray[0];
			versionMinor      = versionArray[1];
			versionRevision   = versionArray[2];
			
			versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
			versionNum        = parseFloat(versionString);
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
			if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
				return true;
			} else {
				return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );	
			}
		}
	}	
	return (reqVer ? false : 0.0);
}

function showFlash(whatMovie,paramString,movieName,W,H,BG,Win,Alignment,whatScale,whatVersion,alternateContent,whatAccess)
{
	var requiredMajorVersion = whatVersion;
	if(whatScale == null || whatScale == '')
	{
		whatScale = 'showAll';
	}
	if(whatAccess == null || whatAccess == '')
	{
		whatAccess = 'sameDomain';
	}
	var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	if(hasRightVersion)
	{  // if we've detected an acceptable version
    var oeTags = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
    + ' width="'+W+'" height="'+H+'" id="'+movieName+'"'
    + ' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'
    + '<param name="movie" value="'+whatMovie+paramString+'" />'
    + '<param name="menu" value="false" />'
    + '<param name="quality" value="high" />'
    + '<param name="wmode" value="'+Win+'" />'
    + '<param name="bgcolor" value="#'+BG+'" />'
    + '<param name="scale" value="'+whatScale+'" />'
    + '<embed src="'+whatMovie+paramString+'" menu="false" quality="high"'
    + ' wmode="'+Win+'" bgcolor="#'+BG+'"'
    + ' scale="'+whatScale+'"'
    + ' width="'+W+'" height="'+H+'" name="'+movieName+'" align="'+Alignment+'"'
    + ' play="true"'
    + ' loop="false"'
    + ' quality="high"'
    + ' allowScriptAccess="'+whatAccess+'"'
    + ' swliveconnect="true"'
    + ' type="application/x-shockwave-flash"'
    + ' pluginspage="https://www.macromedia.com/go/getflashplayer">'
    + '<\/embed>'
    + '<\/object>';
		//alert(oeTags);
    document.write(oeTags);   // embed the flash movie
  } 
	else 
	{
		document.write(alternateContent);
  }
}

function setBottom(objectId)
{
  var styleObject = getStyleObject(objectId);
  if(styleObject) 
  {
		var objectH = styleObject.height;
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0)
		{
	    if (window.pageYOffset)
			{
				ScrollTop = window.pageYOffset;
			}
    	else
			{
        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
		}
		var docH = getHeight();
		var objTop = ScrollTop + (docH - objectH)
		if(isIE == true)
		{
			styleObject.top = objTop;
		}
		else
		{
			styleObject.top = objTop + 'px';
		}
    window.setTimeout('setBottom("'+objectId+'")',500);
  }
}

function imageWindow(whatFile,whatTitle,w,h,x,y,extraText)
{
	var imgSrc = '<img src="../goodies/'+whatFile+'" />';
	var winW = w + 75;
	var winH = h + 50;
  var frontPane = open(whatFile,'frontPane','toolbar=no,width='+winW+',height='+winH+',left='+x+',top='+y+',menubar=no,location=no,status=no,scrollbars=no,resizable=yes');
  frontPane.focus();
  frontPane.document.write('<html>');
  frontPane.document.write('<head>');
  frontPane.document.write('<title>');
  frontPane.document.write(whatTitle);
  frontPane.document.write('</title>');
  frontPane.document.write('<scr'+'ipt>\n');
  frontPane.document.write('<!--\n');
  frontPane.document.write('function killWin()');
  frontPane.document.write('{\n');
  frontPane.document.write('window.close();\n');
  frontPane.document.write('}\n');
  frontPane.document.write('function right(e)\n');
  frontPane.document.write('{\n');
  frontPane.document.write('if (navigator.appName == \'Netscape\' && e.which == 3)\n');
  frontPane.document.write('{\n');
  frontPane.document.write('killWin();\n');
  frontPane.document.write('return false;\n');
  frontPane.document.write('}\n');
  frontPane.document.write('else\n');
  frontPane.document.write('if (navigator.appName == \'Microsoft Internet Explorer\' && event.button==2)\n');
  frontPane.document.write('{\n');
  frontPane.document.write('killWin();\n');
  frontPane.document.write('return false;\n');
  frontPane.document.write('}\n');
  frontPane.document.write('return true;\n');
  frontPane.document.write('}\n');
  frontPane.document.write('document.onmousedown = right;\n');
  frontPane.document.write('//-->\n');
  frontPane.document.write('</scr'+'ipt>\n');
  frontPane.document.write('<meta http-equiv="imagetoolbar" content="no">');
	frontPane.document.write('<link href="../goodies/styles-home.css" rel="stylesheet" type="text/css">');
  frontPane.document.write('</head>');
  frontPane.document.write('<body marginwidth="0" marginheight="0">');
  frontPane.document.write('<table width="100%" height="100%" cellpadding="0" cellspacing="0" border="0"><tr>');
  frontPane.document.write('<td align="center" valign="middle">');
	frontPane.document.write('<h2>'+whatTitle+'</h2>');
  frontPane.document.write(imgSrc);
	frontPane.document.write('<p align="center" class="bodyText">'+extraText+'</p>');
  frontPane.document.write('</td></tr></table>');
  frontPane.document.write('</body>');
  frontPane.document.write('</html>');
  frontPane.document.close();
}

function freshPane(whatFile,whatTitle,w,h,x,y)
{
  var frontPane = open(whatFile,'frontPane','toolbar=no,width='+w+',height='+h+',left='+x+',top='+y+',menubar=no,location=no,status=yes,scrollbars=yes,resizable=yes');
  frontPane.focus();
  frontPane.document.write('<html>');
  frontPane.document.write('<head>');
  frontPane.document.write('<title>');
  frontPane.document.write(whatTitle);
  frontPane.document.write('</title>');
  frontPane.document.write('</head>');
  frontPane.document.write('<frameset rows="100%,*" frameborder="0" border="0" framespacing="0">');
  frontPane.document.write('<frame src="http://');
  frontPane.document.write(whatFile);
  frontPane.document.write('" name="main" scrolling="yes" noresize marginwidth="0" marginheight="0">');
  frontPane.document.write('<frame src="../goodies/space.htm" name="space" scrolling="no" noresize marginwidth="0" marginheight="0">');
  frontPane.document.write('</frameset><noframes></noframes>');
  frontPane.document.write('</html>');
  frontPane.document.close();
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function verify(f)
{
  var empty_fields = "";
  var fCount = 0;
  var empty_options = "";
  var oCount = 0;
  var errors = "";
  var eCount = 0;
  var msg = "";

  for(var i = 0; i < f.length; i++)
  {
    var e = f.elements[i];
    if(((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional)
    {
      if (((e.value == null) || (e.value == "") || isblank(e.value)) && !e.conditional)
      {
        empty_fields += "\n" + replace(e.name,"_"," ") + " is required";
        fCount += 1
        continue;
      }
		}
    if(e.conditional)
    {
			var whatCondition = e.condition;
			if(document.dataForm[whatCondition].value != 1 || document.dataForm[whatCondition].value == 'Other')
			{
        if ((e.value == null) || (e.value == "") || isblank(e.value))
        {
          empty_fields += "\n" + replace(e.name,"_"," ") + " is required";
          fCount += 1
			  }
			}
    }
    if(e.money)
    {
			for(zz=0;zz<e.value.length;zz++)
			{
			  var v = parseFloat(e.value.substring(zz));
        if (isNaN(v) && v != '.')
        {	  
          errors += "\n" + replace(e.name,"_"," ") + " must be dollars and cents";
          eCount = eCount + 1;
			    break;
        }
			}
    }
    if(e.numeric)
    {
			for(zz=0;zz<e.value.length;zz++)
			{
			  var v = parseFloat(e.value.substring(zz));
        if (isNaN(v))
        {	  
          errors += "\n" + replace(e.name,"_"," ") + " must be numeric";
          eCount = eCount + 1;
			    break;
        }
			}
    }
    if(e.count != null)
    {
	    if (e.value.length < e.count)
      {	  
  	    errors += "\n" + replace(e.name,"_"," ") + " must be at least " + e.count + " characters in length";
        eCount = eCount + 1;
      }
    }
    if(e.min != null)
    {
		  var v = parseFloat(e.value);
      if (isNaN(v) || ((e.min != null) && (v < e.min)))
      {	  
        errors += "\n" + replace(e.name,"_"," ") + " must be greater than " + e.min;
        eCount = eCount + 1;
      }
    }
    if(e.max != null)
    {
		  var v = parseFloat(e.value);
      if (isNaN(v) || ((e.max != null) && ( v > e.max)))
      {	  
        errors += "\n" + replace(e.name,"_"," ") + " must be less than " + e.max;
        eCount = eCount + 1;
      }
    }
    if(e.email)
    {
			if(test(e.value) == false)
			{
			  errors += "\nA valid email address is required"
			  eCount += 1;
			}
    }

    if ((e.options) && !e.optional)
    {
      var which = e.options.selectedIndex
      var choice = e.options[which].value
      if ((choice == null) || (choice == "") && !e.conditional)
      {
        empty_options += "\n" + replace(e.name,"_"," ") + " selection is required";
        oCount = oCount + 1;
        continue;
      }
	    if(e.conditional)
      {
				var whatCondition = e.condition;
				if(f[whatCondition].value != 1 || f[whatCondition].value == 'Other')
				{
          if ((choice == null) || (choice == ""))
          {
            empty_fields += "\n" + replace(e.name,"_"," ") + " selection is required";
            fCount += 1
				  }
				}
      }
    }
  }

  if ((!empty_fields) && (!empty_options) && !errors)
  {
    return true;
  }
  else
  {
    msg = "Please be sure to complete all selections or fill in all required fields.\n";
    if (empty_fields)
    {
      fieldsVar = "field"
      if(fCount > 1){fieldsVar += "s"}
      msg += "\n" + fCount + " required " + fieldsVar + " left blank.";
      msg += empty_fields += "\n";
    }
    if (errors)
    {
      fieldsVar = "field"
      if(eCount > 1){fieldsVar += "s"}
      msg += "\n" + eCount + " " + fieldsVar + " with invalid entries.";
      msg += errors += "\n";
    }
    if (empty_options)
    {
      choicesVar = "choice"
      if (oCount > 1)
        {choicesVar += "s"}
      msg += "\n" + oCount + " required " + choicesVar + " not selected.";
      msg += empty_options += "\n";
    }
    alert(msg);
    return false;
  }
}

function isLetter(str)
{
  var fieldErrors = ""
  var rex = /[^a-zA-Z\s]/

  if ((str == "") || (str == null))
  {
  fieldErrors = "You must enter text.\n";
  }

  if(rex.test(str))
  {
  fieldErrors += "Invalid data was entered.";
  }

  if (fieldErrors)
  {
  alert(fieldErrors);
  return false;
  }
  else
  {
  return true;
  }
}

function isAlphaNum(str)
{
  var fieldErrors = ""
  var rex = /[^\w]/

  if ((str == "") || (str == null) || isblank(str))
  {
  fieldErrors = "You must enter something.\n";
  }

  if(rex.test(str))
  {
  fieldErrors += "Check that you have only entered letters and-or numbers.";
  }

  if (fieldErrors)
  {
  alert(fieldErrors);
  return false;
  }
  else
  {
  return true;
  }
}

function isblank(s)
{
  for(var i = 0; i < s.length; i++)
  {
    var c = s.charAt(i);
    if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
  }
  return true;
}

function replace(string,text,by) 
{
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

function test(src) 
{
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
}


function autoTab(input,len, e)
{
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

	if(input.value.length >= len && !containsElement(filter,keyCode)) 
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
}

function containsElement(arr, ele)
{
	var found = false
	var index = 0;
	while(!found && index < arr.length)
	{
		if(arr[index] == ele)
		{
			found = true;
		}
		else
		{
			index++;
		}
	}
	return found;
}

function getIndex(input) 
{
	var index = -1
	var i = 0
	var found = false;
	while (i < input.form.length && index == -1)
	{
		if (input.form[i] == input)
		{
			index = i;
		}
		else 
		{
			i++;
		}
	}
	return index;
}



function submitForm(formName,whereTo)
{
	var whatForm = document.getElementById(formName);
	if(formName == 'contactForm')
	{
		whatForm.Email.email=true;
		whatForm.Area_Code.numeric=true;
		whatForm.Phone_Prefix.numeric=true;
		whatForm.Phone_Number.numeric=true;
	}
	if(formName == 'footerForm')
	{
		whatForm.Sign_Up_Email_Address.email=true;
	}
	if(formName == 'signupForm')
	{
		whatForm.Email_Address.email=true;
		whatForm.Phone.optional=true;
		whatForm.Address.optional=true;
		whatForm.Address_2.optional=true;
		whatForm.City.optional=true;
		whatForm.State.optional=true;
		whatForm.Zip.optional=true;
	}
	var whatReturn = verify(whatForm); 
	if(whatReturn == true)
	{
		whatForm.action = whereTo;
		whatForm.submit();
	}
}

function checkField(whatField,whatValue)
{
	var fieldObj = document.getElementById(whatField);
	if(fieldObj.value == whatValue){fieldObj.value = '';}
}
