/*
 * site.js
 *
 * Copyright (c) 2009 Nicholas Shelly (www.breastfeedingcenter.org)
 *
 */

  // Google Analytics tracker
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  try {
    var pageTracker = _gat._getTracker("UA-8521736-1");
    pageTracker._trackPageview();
  } catch(err) {}

  var okDates = [];
  
  function classKeyPopup() {
      window.open( "http://www.breastfeedingcenter.org/classKey.php/", "myWindow", 
  			 "status = 1, height = 350, width = 350, resizable = 0" )
  }

  function rosterPopup() {
      window.open( "http://www.breastfeedingcenter.org/classRoster.php/", "myWindow", 
  			 "status = 1, height = 350, width = 400, resizable = 0" )
  }
  
  function checkPaidClass(classNum) {
	 // always display collect customer details
	   return false;
		 if (classNum == "3" || // Infant Massage 
		  	 classNum == "5" || // Meeting Baby's Needs
		 	 classNum == "6" || // Mom Massage
	 		 classNum == "9" || // Baby's First Solids
			 classNum == "11" ) // Breastfeeding & Baby Wearing
		{		
		 	 return true;
	    }
		else {
		 	 return false; 
		}	
   }
	 
	function checkEmail (strng) {
		var error = "";
		var good = true;  
		var emailFilter=/^.+@.+\..{2,3}$/;
		var illegalChars= /[\(\)\<\>\,\;\:\\\[\]\~\!\|\$\%\^\&\*\+\"]/;
	  	var at="@";
		var dot=".";
		var lat=strng.indexOf(at);
		var lstr=strng.length;
		var ldot=strng.indexOf(dot);
		if (strng == "") {
		 	error = "Please enter a valid home and work email address.\n";
		}
		else if (!(emailFilter.test(strng))) {
		   good = false;
		}
		else if (strng.match(illegalChars)) {
           good = false;
        }
		else if (strng.indexOf(at)==-1) {
		   good = false;
		}
		else if (strng.indexOf(at)==-1 || strng.indexOf(at)==0 || strng.indexOf(at)==lstr){
		   good = false;
		}
		else if (strng.indexOf(dot)==-1 || strng.indexOf(dot)==0 || strng.indexOf(dot)==lstr){
		   good = false;
		}
        else if (strng.indexOf(at,(lat+1))!=-1){
			 good = false;
		}
		else if (strng.substring(lat-1,lat)==dot || strng.substring(lat+1,lat+2)==dot){
			good = false;
		}
		else if (strng.indexOf(dot,(lat+2))==-1){
		 	good = false;
		}
		else if (strng.indexOf(" ")!=-1){
			good = false;
		}
		if (!good) {
              error = "The email address contains illegal characters.\n";
        }
      return error;    
   }
      
   // phone number - strip out delimiters and check for 10 digits
      
   function checkPhone (strng) {
      var error = "";
      if (strng == "") {
         error = "Please enter a phone number.\n";
      }
      var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
      if (isNaN(parseInt(stripped))) {
             error = "The phone number contains illegal characters.";
        
      }
      if (!(stripped.length == 10)) {
    	  	 error = "The phone number is the wrong length. Please include an area code.\n";
      } 
      return error;
    }
	  
	// confirm - check confirm has been entered
	function checkConfirm (strng) {
        var error = "";
        if (strng != "confirm") {
           error = "Please type \"confirm\" in the confirm box.\n";
        }
		return error;
	}
      
    function checkName(strng, strng2) {
		var error = "";
		if (strng.length == 0 || strng2.length == 0) {
		   error = "Please enter your first and last name.\n";
		}
		return error;	  
	}

   	function checkBirthDate (strng) {
			 var error = "";
			 if (strng == "mm/dd/yyyy") {
			 	error = "Please enter a birth or due date.\n";
			 }
			 return error;
	}
	
   	function checkClassDate (strng) {
			 var error = ""; 
			 if (strng == "mm/dd/yyyy") {
			 	error = "Please enter a class date.\n";
			 }
			 var dateSelected = new Date(parseInt(strng.substring(6,10),10), parseInt(strng.substring(0,2)-1,10), 
			 			 			  parseInt(strng.substring(3,5),10));
//			 alert ("dateSelected = " + dateSelected);			 		
			 var checkDates = okDates.slice(); 
			 var valid = 0;
			 var temp = ""; 
             while (checkDates.length != 0) {
			 	   temp = checkDates.pop();				   
				   if (temp.valueOf() == dateSelected.valueOf()) {
//				      alert (temp + " equal to " + dateSelected);
		  		   	  valid = 1;
					  break;
				   }  
          	 }
			 if (valid == 0) {
			 	error = "Sorry, the class is not offered on that date.\n"				
             }				  
			 return error;
			 
	}
	
	function checkClassName(strng) {
		var error = "";
		if (strng == "0") {
		   error = "Please select a class.\n";
		}
//		if (strng == "3" || strng == "5" || strng == "6" || strng == "9" || strng == "11") {
//		  error = "Please call (202) 293-5182 to register for a paid class.\n";
//		} 
		return error;	  
	}

	function getClassName(num) {
			classList = [ 	   "Breastfeeding Baby 0-4 months",
					   	 		"Breastfeeding Basics",
								"Infant Massage", //paid
								"Breastfeeding the Toddler (1 year +)", 
								"Meeting Babies Needs in the first 6 months", //paid 
								"Mom Massage", //paid
								"Breastpump Basics",
								"Return to Work",
								"Baby's First Solids (5-9 months)", //paid
								"Breastfeeding the Infant",
								"Breastfeeding & Baby Wearing",
								"Writing Workshop" ]; //paid
			return classList[num-1];	
	}	  	 
	
    function checkWholeForm(theForm) {
			 var why = "";
			 why += checkClassName(theForm.classname.value);
			 why += checkClassDate(theForm.classdate.value);			 			 			 
        	 var selObj = document.getElementById("classname");	
        	 var selIndex = selObj.selectedIndex;
        	 payVar = selObj.options[selIndex].value;			 
			 if (!checkPaidClass(payVar)) {
			     // only check customer details if free class (paid class details collected through PayPal)
    			 why += checkName(theForm.LastName.value, theForm.FirstName.value);			 			
    			 why += checkEmail(theForm.HomeEmail.value);
                 why += checkEmail(theForm.WorkEmail.value);				 
    			 why += checkPhone(theForm.HomePhone.value);
    			 why += checkBirthDate(theForm.BirthDate.value);			 
    			 if (theForm.AltPhone.value != "") {
    		 			 why += checkPhone(theForm.AltPhone.value)  // check alternate phone number if entered
 	    		 }
			 }			 
			 if (why != "") {
			 	alert(why);
				return false;
			 }

			if (!checkPaidClass(payVar)) {
			    // customer confirms if free class, other confirm through PayPal
    			if (confirm ('Please select OK to proceed with your registration.')) {
    			 	return true;
    			}
    			else {
    				return false;
    			}
			}
			return true;
    }
	
	/*function display(obj) {
	// display part of form for credit card details, if paid class selected		
        payVar = obj.options[obj.selectedIndex].value;
        if (!checkPaidClass(payVar)) {		
				// Not a paid class, collect customer details here
			showCustomer = 'block';
			showPay = 'none';
        }
        else {
			showCustomer = 'none';
			showPay= 'block';			
        }
        document.getElementById("customerDetails").style.display = showCustomer;
        document.getElementById("payDetails").style.display = showPay;		
        document.getElementById("classdate").value = "mm/dd/yyyy";					 						  
	}*/
	
window.onload = function(){
   function getClassDay (aDate) {
   		  myDays= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
  		  myDate=new Date(eval('"'+aDate+'"'));
  		  return myDays[myDate.getDay()];
  }			
  
  function NthXdayOfYM(N, X, Y, M) {
  		 // returns date of Nth week, X-day of week (e.g. 2 for Tuesday), year (Y), and month (M)
  		 var D;
  		 with (D = new Date(Y, M - 1, 1)) {
  		 	setDate(7 * N - 6 + (7 + X - getDay()) % 7);
  			 }
  		 return D;
  }
  
  function lastXOfYM(X, Y, M) {
         // returns last X-day of month for given year (Y), month (M), and day of week (X)
  		 var D = new Date(Y, M - 1, 1);
  		 var N = 5;
  		 for (var N = 5; N > 0; N--) {
  		  	D.setDate(7 * N - 6 + (7 + X - D.getDay()) % 7);
  			if (D.getMonth() == (M - 1)) {
  			break;
  		} else {
   		 D = new Date(Y, M - 1, 1);	// need to reset to original date for next run
  		}
         }
         return D;
  }
  
  function getOkDates(weekNumArr, dayOfWeek) {
         var goodDates = [];
         var Y = (new Date).getFullYear();
         var M = (new Date).getMonth() + 1;
		 var yesterday = new Date();
		 yesterday.setDate(yesterday.getDate()-1);
//		 alert ("yesterday = " + yesterday);
   		 for (var i = 0; i < 12; i++) {
    			for (var weekNum = 0; weekNum < weekNumArr.length; weekNum++) {
    				var d;
    				if (weekNumArr[weekNum] == "L" || weekNumArr[weekNum] == "l") {
					    // class on last day of month
    					d = lastXOfYM(dayOfWeek, Y, M);
    				} 
					else {
					    // class on specific week N
    					d = NthXdayOfYM(weekNumArr[weekNum], dayOfWeek, Y, M);	
   		                }
		 		if (d > yesterday) {
//				    alert("adding " + d);
         			goodDates.push(d);
				}
        	}
        	M++;
        	if (M > 12) {
        		M = 1;
        		Y++;
        	}
         }		
         return goodDates;
  }
  
  function isDateOk(date) {
       for (var d = 0; d < okDates.length; d++) {
       	if (date.getMonth() == okDates[d].getMonth() && date.getDate() == okDates[d].getDate() && date.getFullYear() == okDates[d].getFullYear()) {
       		return [true, ''];
       	}
       }
       return [false, ""];
  }
  
  function combineDates (okDates1, okDates2) {
   var temp = [];
   while (okDates2.length != 0) {
   	  temp = okDates2.pop(); 
   	  okDates1.push(temp);
  
   }
   return okDates1;
  }
   
  function cancelClass (okDates, canceledClass) {
     var temp = [];
     var goodDates = [];
     while (okDates.length != 0) {
  	  temp = okDates.pop();
  	  if (temp.valueOf() != canceledClass.valueOf()) {			  
  	      goodDates.push(temp);				  
  	  }
     }
     return goodDates;
  }
	   
  function handleClassSelection(event) {
   // format -- getOkDates([1st/2nd/3rd/4th/5th days of month], day of week (e.g. Tuesday = 2))
   
   if (this.value == 1) { // Breastfeeding Baby
   // every Tuesday of month
   	okDates = getOkDates([1, 2, 3, 4, 5], 2);
   } 
   else if (this.value == 2) { //Breastfeeding Basics
   		// Breastfeeding Basics, 1st Monday, and 1st and 3rd Wednesdays		
   		okDates = combineDates (getOkDates([1, 3], 3), getOkDates([1], 1));
		okDates = cancelClass(okDates, new Date(2009, 9-1, 16));
//       	okDates = cancelClass(okDates, new Date(2009, 6, 1));
   		// Breastfeeding Basics canceled on 1 Jul 2009
  		
   } else if (this.value == 3) { // Infant Massage
   	okDates = getOkDates([1, 2, 3], 4);
   } else if (this.value ==4) { //Breastfeeding the Toddler
   	okDates = getOkDates([1], 5);
   } else if (this.value ==5) { // Meeting Baby's Needs - every other month starting July
   		okDates = [];
   		tmp = new Date(2009, 4-1, 12); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2009, 5-1, 12); if ( tmp > new Date() ) { okDates.push(tmp) };
   		tmp = new Date(2009, 6-1, 12); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2009, 8-1, 14); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2009, 10-1, 9); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2009, 12-1, 11); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 2-1, 12); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 4-1, 9); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 6-1, 11); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 8-1, 13); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 10-1, 8); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2010, 12-1, 10); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 2-1, 11); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 4-1, 8); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 6-1, 10); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 8-1, 12); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 10-1, 14); if ( tmp > new Date() ) { okDates.push(tmp) };
		tmp = new Date(2011, 12-1, 9); if ( tmp > new Date() ) { okDates.push(tmp) };
//	    okDates = getOkDates([2], 5);
   } else if (this.value ==6) { // Mom Massage
   	okDates = getOkDates([3], 4);
   } else if (this.value ==7) { // Breastpump Basics
   	okDates = getOkDates([2, 4], 3);
   } else if (this.value ==8) { // Return to Work
   	okDates = getOkDates([2, 4], 3);
   } else if (this.value ==9) { // Baby's First Solids
   	okDates = getOkDates([3], 5);
		tmp = new Date(2009, 9-1, 21); if ( tmp > new Date() ) { okDates.push(tmp) };
		okDates = cancelClass(okDates, new Date(2009, 9-1, 18));
		okDates = cancelClass(okDates, new Date(2009, 10-1, 16));
		// tmp = new Date(2009, 9-1, 25); if ( tmp > new Date() ) { okDates.push(tmp) };
   } else if (this.value ==10) { // Breastfeeding the Infant
   	okDates = getOkDates(["L"], 4);
   } else if (this.value ==11) { // Breastfeeding & Baby Wearing
   	okDates = getOkDates([4], 5);
	okDates = cancelClass(okDates, new Date(2009, 11-1, 27));
	okDates = cancelClass(okDates, new Date(2009, 12-1, 25));
   	tmp = new Date(2010, 1-1, 11); if ( tmp > new Date() ) { okDates.push(tmp) };
   } else if (this.value ==12) { // Writer's Workshop 
   		okDates = [];
   		tmp = new Date(2010, 5-1, 22); if ( tmp > new Date() ) { okDates.push(tmp) };
   		tmp = new Date(2010, 7-1, 17); if ( tmp > new Date() ) { okDates.push(tmp) };
   } else if (this.value ==13) { // Infant Massage for Partners 
   		okDates = [];
   		tmp = new Date(2009, 8-1, 22); if ( tmp > new Date() ) { okDates.push(tmp) };
   		tmp = new Date(2010, 1-1, 16); if ( tmp > new Date() ) { okDates.push(tmp) };
   		tmp = new Date(2010, 4-1, 10); if ( tmp > new Date() ) { okDates.push(tmp) };
   		tmp = new Date(2010, 7-1, 17); if ( tmp > new Date() ) { okDates.push(tmp) };
   } else if (this.value ==14) { // Breastfeeding Multiples
   	okDates = getOkDates([2], 1);  // 2nd Monday
} else {
   	okDates = [];
   }
  }	
	
	$("#classnameView").bind("change", handleClassSelection);	
	$("#classdateView").datepicker({
		beforeShowDay: isDateOk,
		showOn: "both",
		yearRange: "-0:+1"});
	
	$("#classname").bind("change", handleClassSelection);
	$("#classdate").datepicker({
		beforeShowDay: isDateOk,
		showOn: "both",
		yearRange: "-0:+1"});
	$("#BirthDate").datepicker({
		showOn: "both",
		yearRange: "-2:+1"
	});
	
}  // end on window load (for IE browser)