//-------------------------------------------------------------
//	getHTTPObject()
//
//  Description:			Determines which object is available
//							for performing background requests from
//							the server
//
//	Created by: 			Jesse Jarrell
//	Completion Status: 		Complete
//	Modifications:
//		November 4, 2005:	Added function to suite
//-------------------------------------------------------------
function getHTTPObject() {
	var xmlhttp;
	
	if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
		try {
			xmlhttp = new XMLHttpRequest();
			//alert("Using XMLHttpRequest()");
		} catch (e) {
			xmlhttp = false;
		}
	}else{
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			//alert("Using Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				//alert("Using Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	}
	return xmlhttp;
}

//-------------------------------------------------------------
//	getHTMLContent(thePage)
//
//		thePage		The name of the HTML snippet to return.
//					See PAGE_???? globals for values
//
//  Description:			Returns an html snippet from
//							the server
//
//	Created by: 			Jesse Jarrell
//	Completion Status: 		Complete
//	Modifications:
//		November 4, 2005:	Added function to suite
//-------------------------------------------------------------
function getHTMLContent(thePage) {
	var xmlhttp = getHTTPObject();
	xmlhttp.open("GET", thePage, false);
	xmlhttp.send(null);
	var text = xmlhttp.responseText;
	xmlhttp = null;
	return text;
}

function loadPage(thePage) {
	loadSubPage('theContent', thePage);
	MM_menuHideMenus();
}

function loadSubPage(element, thePage) {
	var theHTML = getHTMLContent(thePage);
	// Take only the body content
	var i = theHTML.indexOf(">", theHTML.indexOf("<body")) + 1;
	var j = theHTML.indexOf("</body") - 1;
	document.getElementById(element).innerHTML = theHTML.substring(i, j);
}

function postRegistration() {
	var theURL = "registrationPost.php"
	var xmlhttp = getHTTPObject();
	xmlhttp.open("POST", theURL, false);
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var data = "command=post";
	var el = document.getElementsByTagName("INPUT")
	for(var i=0; i < el.length; i++) {
		if (el[i].type == "radio" && el[i].checked == false) continue;
		data += "&" + el[i].id + "=" + el[i].value
	}
	xmlhttp.send(data);
	loadPage("registrationAccepted.htm");
}

function postChangeRequest() {
	var theURL = "changeRequestPost.php"
	var xmlhttp = getHTTPObject();
	xmlhttp.open("POST", theURL, false);
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var data = "command=post";
	var el = document.getElementsByTagName("INPUT")
	for(var i=0; i < el.length; i++) {
		if (el[i].type == "radio" && el[i].checked == false) continue;
		data += "&" + el[i].id + "=" + el[i].value
	}
	var el = document.getElementsByTagName("SELECT")
	for(var i=0; i < el.length; i++) {
		data += "&" + el[i].id + "=" + el[i].value
	}
	var el = document.getElementsByTagName("TEXTAREA")
	for(var i=0; i < el.length; i++) {
		data += "&" + el[i].id + "=" + el[i].value
	}
	xmlhttp.send(data);
	loadPage("changeRequestAccepted.htm");
}

function setContentHeight() {
	var hh = document.getElementsByTagName("HTML").item(0).clientHeight - 135;
	if (hh > 512) hh=512;
	document.getElementById("theContent").style.height = hh + "px";
}

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_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function login() {
	if (document.getElementById("passwd").value > 0 && document.getElementById("emailAddress").value > "") {
		loadPage("mailSchedule.php?email=" + document.getElementById("emailAddress").value + "&goodSamNumber=" + document.getElementById("passwd").value);
		Calendar.setup({
        inputField     :    "mailDate",           //*
        ifFormat       :    "%m/%d/%Y",
        showsTime      :    false,
		showOthers	   :	true,
		dateStatusFunc :	function (da) { if (da.getDay() == 0 || da.getDay() == 6) return true;
											var x = da.getFullYear()*10000 + da.getMonth()*100 + da.getDate();
											var y = new Date();
											var z = y.getFullYear()*10000 + y.getMonth()*100 + y.getDate();
											return (x <= z);
		}
    	});
	}else{
		alert("Please contact our office at 888-SAM-MAIL if you are having difficulty logging in.");
	}
}

function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(2005, 2007);        // min/max year allowed.
	cal.setDisabledHandler(isDisabled);
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar

  return false;
}

function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked) {
	  cal.callCloseHandler();
	  cal.sel.blur();
  }
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function isDisabled(date) {
  var MINUTE = 60 * 1000;
  var HOUR = 60 * MINUTE;
  var DAY = 24 * HOUR;
  var WEEK = 7 * DAY;
  var today = new Date();
  return ((date.getTime() - today.getTime()) / DAY) < 0;
}

function zipChange(el, c, s) {
	var xmlhttp = getHTTPObject();
	xmlhttp.open("GET", "zipCodes.php?" + el.value, false);
	xmlhttp.send(null);
	var text = xmlhttp.responseText;
	xmlhttp = null;
	document.getElementById(c).value = text.split(",")[0]
	document.getElementById(s).value = text.split(",")[1]
}

function addOption(element, text, value) {
	var opt = document.createElement("option");
	opt.text = text;
	opt.value = value;
	if (!document.all) {
		element.appendChild(opt);
	}else{
		element.add(opt);
	}
}

function removeElements() {
	var obj = document.getElementById(arguments[0]);
	for(var i=1; i < arguments.length; i++) {
		var id = arguments[i]
		if (document.getElementById(id)) {
			obj.removeChild(document.getElementById(id));
		}
	}
}

function notUsed() {
	var val = arguments[0];
	for(var i=1; i < arguments.length; i++) {
		var id = arguments[i];
		if (document.getElementById(id)) {
			if (document.getElementById(id).options(document.getElementById(id).selectedIndex).value == val) return false;	
		}
	}
	return true;
}

function createSchedDate(x) {
	if (x > 4) return;
	for(var i=x; i < 5; i++) {
		removeElements("mailScheduleDates", "schedDate" + i);
	}
	var s1 = document.createElement("SELECT");
	s1.id = "schedDate"+x
	addOption(s1, "No Selection", 0);
	for(var i=1; i < 32; i++) {
		if (notUsed(i, "schedDate1","schedDate2","schedDate3")) {
			addOption(s1, i, i);
		}
	}
	s1.onchange = function () {	createSchedDate(x+1) }
	removeElements("mailScheduleDates", s1.id);
	document.getElementById("mailScheduleDates").appendChild(s1);
}

var days = ["Monday","Tuesday","Wednesday","Thursday","Friday"];

function createSchedDay(x) {
	if (x > 3) return;
	for(var i=x; i < 4; i++) {
		removeElements("mailScheduleDays", "schedDay" + i);
	}
	var s1 = document.createElement("SELECT");
	s1.id = "schedDay"+x
	addOption(s1, "No Selection", 0);
	for(var p in days) {
		if (notUsed(days[p], "schedDay1","schedDay2")) {
			addOption(s1, days[p], days[p]);
		}
	}
	s1.onchange = function () {	createSchedDay(x+1) }
	document.getElementById("mailScheduleDays").appendChild(s1);
}

function scheduleChange(x) {
	// Remove all previous schedule days/dates
	removeElements("mailScheduleDays","schedDay1","schedDay2","schedDay3");
	removeElements("mailScheduleDates","schedDate1","schedDate2","schedDate3","schedDate4");
	switch (x) {
		case 2:
			createSchedDate(1);
			break;
		case 1:
			createSchedDay(1);
			break;
		default:
			// Do nothing
	}
}

