// ** *************************************************************************** ** //
// **                                                                             ** //
// ** Main.js - file for different javascripts                                    ** //
// **                                                                             ** //
// ** Created by Tibor(tibor@planetsg.com)                                        ** //
// **                                                                             ** //
// ** Last Modified by Tibor(tibor@planetsg.com)                                  ** //
// ** Last Change Date: Macrh, 17 2008. 									    			              ** //
// **                                                                             ** //
// ** *************************************************************************** ** //

/* INIT EVENT HANDLER*/
Event.observe( window, 'load', function() {
InitCalendar();
CreateEmailHiddenCnt();
} 
);

/* INVITATION EMAIL */
/*
function ManageHiddenContent(id,cond,dac) {

   if(cond == 1) $(id).style.display = 'block';
   if(cond == 0) $(id).style.display = 'none';
   if(dac.length > 0) $(dac).style.display = 'none';
}
*/
function ShowHiddenContent() {
   $('invitationmore').style.display = 'block';
   $('invitationaddmore').style.display = 'none';
   $('addmorecnt').value = 'on';
}

function CreateEmailHiddenCnt() {

 if($('addmorecnt') != null && $('addmorecnt').value == 'on') {
   $('invitationmore').style.display = 'block';
   $('invitationaddmore').style.display = 'none';
 }
}
/*
function ReloadSelf() {
var theForm = document.forms['report'];
var redirect = document.getElementById('redireconself').value;
theForm.target = '_top';
theForm.action = redirect;
theForm.method = 'post';
theForm.submit();
}
*/
/* CLEAR SESSION */
function ClearSession() {

    var url = "System/Ajax/ClearSession.php";
		var myAjax = new Ajax.Request(url);

}


// WINDOW FUNCTIONS
  function newwindow(url)
  {
  	newwindow=window.open(url);
  	if (window.focus) {newwindow.focus()}
  	return false;
  }
  
  function open_url(urltoopen,menubar,scrollbars,resizable,width,height)
  {
    window.open(urltoopen,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=" + menubar + ", scrollbars="+ scrollbars + ", resizable=" + resizable + ", copyhistory=no, innerWidth=0, innerHeight=0, width=" + width + ", height=" + height);
  }
 
// TOP MENU 
  function menuMouseOver(param) {
  
  if(document.getElementById(param) != null) {
    document.getElementById(param).style.display='block';
  }
  }
  
  function menuMouseOut(param) {
  
  if(document.getElementById(param) != null) {
    document.getElementById(param).style.display='none';
  }
  }

  function TMactive(element, pic){
  var x=document.getElementById(element);
  //alert(x.src)
  x.src ='System/Image/Top_Menu/'+pic+'_rollover'+'.jpg'
  
  }
  function TMinactive(element, pic){
  var x=document.getElementById(element);
  x.src ='System/Image/Top_Menu/'+pic+'.jpg'
  }


function cleanString(string) {

      var cleaned = string.replace(/[<>]/gi, '').replace(/&lt;/gi, '').replace(/&gt;/gi, '').replace(/alert\(/gi, '').replace(/[#!\+$]/gi, '');
      //cleaned = escape(cleaned);

      return cleaned;
}

function prepareSearch() {

      var string = document.getElementById('searchField').value;

      if(string != "Full Site Search" && string.length > 1) {

      document.getElementById('searchField').value = cleanString(string);
      //alert(cleaned);
      //window.location.href='System/Search.php?Search='+cleaned;
      document.SearchHeader.submit();
      return true;
      } else {
          
          if(string == "Full Site Search") {
          
          alert('Missing search string.');
          return false;
          
          } else if(string.length < 2) {
          
           alert('Minimum search string length is two characters.');
           return false;         
          }
      }
		  return false;
     
}

function cleanSend() {

      var string = document.getElementById('email').value;

      if(string.length > 1) {

      string = cleanString(string);

      if (check(string)==false){
      return false
      }

      document.getElementById('email').value = string;
      
      //document.EmailForm.submit();
      
      var theForm = document.forms['EmailForm'];
      //theForm.target = '_top';
      theForm.action = "System/Ajax/SaveEmail.php";
      theForm.method = 'post';
      theForm.submit();
           
      //return true;
      } else {
                
          alert('Missing email address.');
          return false;
          

      }
		  return false;
     
}


// FORM VALIDATORS
 
  function check(adr) {
  
    var esc = adr.toLowerCase();
    var kw = 0;
    for (var i=0; i < esc.length; i++) {
    var ch = esc.charAt(i);
    if (ch == '@')
    	kw += 1;
    }
    if (kw!=1){
    alert("Error type: missing or multiple instances of @ in email address!");
    return(false);
    }
    var filter=/^.+@.+\..{2,3}$/
    if (!filter.test(esc)){
    alert("Error type: missing or wrong character in email address!");
    return(false);
    }
    txt=esc.split("@");
    if (txt[1].indexOf("..")>1) {
    alert("Error type: multiple use of dot!");
    return(false);
    }
    if (esc.indexOf(" ")>0){
    alert("Error type: a space between letters!");
    return(false);
    }
    adr.value=esc;
    return(true);
  }
  
function FormValidator(){

	//var email=document.ContactForm.emailto;
	var yname=document.ContactForm.name;
	var ymail=document.ContactForm.mailfrom;
	var message=document.ContactForm.message.value;
 
	//(email.value==null)||(email.value=="") || 
	if ((yname.value=="") || (ymail.value=="") || (ymail.value==null)){
		alert("Please, fill the required fields.");
		ymail.focus();
		return false;
	}
	
	/*
	if(check(email.value)==false){
		email.value=""
		email.focus()
		return false
	} 
  */
  if(check(ymail.value)==false){
		ymail.value="";
		ymail.focus();
		return false;
	}

	if(message.length > 850) {
		alert("Sorry, to many characters in the message. Only ten full lines allowed.");
		ymail.focus();
		return false;
	
	}
  	
	if(message.length > 0)  document.ContactForm.message.value = cleanString(message); 
		                      document.ContactForm.name.value = cleanString(yname.value);
		

  return true;
 }

function CheckRequired(param){

      
    var comment = document.getElementById('Survey_Comment').value;
    var name = document.getElementById('Survey_Comment_Name').value;
   
   //alert(name+comment);
   
    if(param.length > 0) {
		if(comment=='' || name=='') {
			window.alert ("Please, fill the required fields.");
			return false

	   }
	   }
			
	Validator();

	 if(name.length > 0) document.getElementById('name').value = cleanString(name); 
	 if(comment.length > 0) document.getElementById('comment').value = cleanString(comment); 
	

      return true;
	
}

function Validator(){

  if(document.getElementById('xmail')) {

	var xmail=document.ContactForm.xmail;
	
	if ((xmail.value==null)||(xmail.value=="")){
		alert("Must contain an e-mail address!");
		xmail.focus()
		return false
	}
	if (check(xmail.value)==false){
		xmail.value=""
		xmail.focus()
		return false
	}
	
	return true
	
 } else {
 
	return true
 }
}
// FORM VALIDATOR END


// ** ACCOUNT AND REGISTRATION VALIDATION  **/

function CheckRegistrationWebForm(rtype) {

var theForm = document.forms['RegistrationWeb'];


    var hcheck = 0;
    var ocheck = 0;
    var gcheck = 0;
    
    if(theForm.Student_ID.options[theForm.Student_ID.selectedIndex].value == '' && (theForm.elements['FirstName'].value == '' || theForm.elements['LastName'].value == '')) {
    
        AlertWebThis("Select student from the drop down list. Type the student's information only  for a new student."); 
       return false;   
    }

   for(i=0; i<theForm.elements.length; i++) {
   //alert(theForm.elements[i].name + theForm.elements[i].type);
   
    if(theForm.elements[i].type == "text") {
         
      if(theForm.elements[i].name != 'School' 
      && theForm.elements[i].name != 'MiddleName'
      && theForm.elements[i].name != 'Birthday'
      && theForm.elements[i].name != 'ParentLastName'
      && theForm.elements[i].name != 'ParentFirstName'
      && theForm.elements[i].name != 'ParentAddress'
      && theForm.elements[i].name != 'ParentCity'
      && theForm.elements[i].name != 'ParentPostalCode'
      && theForm.elements[i].name != 'ParentMobilePhone'
      && theForm.elements[i].name != 'ParentOfficePhone'
      && theForm.elements[i].name != 'ParentEmail'
      && theForm.elements[i].name != 'ParentRelation'
      && theForm.elements[i].name != 'Sex'
      ) {
      
      if(theForm.elements[i].value == '') {
      var eLabel = theForm.elements[i].name+'LB';
      var eAlert = '';
      if($(eLabel)) {
      var eAlert = ($(eLabel).innerHTML);
       eAlert = eAlert.slice(2, 50);
       //alert(eAlert);
       eAlert = '"' + eAlert + '" is required!';
       }
       AlertWebThis(eAlert); 
       return false;
      }
    }

        if(rtype == 'Camp' && theForm.elements[i].name == 'School' && theForm.elements[i].value == '') {
        AlertWebThis('"School" is required!'); 
        return false;        
        
        }
    
  }
  
      
    if(theForm.elements[i].type == "checkbox" && (theForm.elements[i].name == 'Liability' || theForm.elements[i].name == 'Rules'  || theForm.elements[i].name == 'Drug'  || theForm.elements[i].name == 'Payment'  || theForm.elements[i].name == 'Faq') && theForm.elements[i].checked != true) {   
          AlertWebThis('Some of the checkboxes for waivers are required!');
          return false;
    }

    if(theForm.elements[i].type == "radio" && theForm.elements[i].name == 'Allergies' && theForm.elements[i].checked == true) {
    ocheck++;
    var allergy = theForm.elements[i].value;

    }
    
    if(theForm.elements[i].type == "radio" && theForm.elements[i].name == 'Sex' && theForm.elements[i].checked == true) {
    gcheck++;
    var gender = theForm.elements[i].value;
    }
    
    if(theForm.elements[i].type == "checkbox" && theForm.elements[i].name.indexOf("Allergy") != -1 && theForm.elements[i].checked == true) {   
    hcheck++
    }
    
 
    if(theForm.elements[i].type == "select-one" && theForm.elements[i].name != 'Grade' && theForm.elements[i].name != 'Student_ID' && theForm.elements[i].name != 'ParentState' && theForm.elements[i].name.indexOf("Tetanus") == -1) {
     if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == '') {

          var eLabel = theForm.elements[i].name+'LB';
          var eAlert = '';
          if($(eLabel)) {
          var eAlert = ($(eLabel).innerHTML);
           eAlert = eAlert.slice(2, 50);
           //alert(eAlert);
           eAlert = '"' + eAlert + '" is required!';
           }    
          AlertWebThis(eAlert);
          return false;
          }
    }

    if(rtype == 'Camp' && theForm.elements[i].type == "select-one" && theForm.elements[i].name.indexOf("Tetanus") != -1) {
     if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == '') {  
          AlertWebThis('"Tetanus" is required!');
          return false;
          } 
          
    }
 }


      
    if(rtype != 'Party') {
    
     if(ocheck == 0) {
     AlertWebThis('Does the student suffer from any allergies?'); 
     return false;     
     }
     

     if(hcheck == 0 && allergy == 'Yes') { 
     AlertWebThis('If the student suffer from any allergies, please check the boxes associated to allergies.'); 
     return false;
     }

    if(rtype != 'Camp') {
    if(document.getElementById('genderreadonlyid') == null) {
    
    if(gcheck == 0) {
     AlertWebThis('"Gender" is required!'); 
     return false;     
    }
    
    } else {
    
     var gender = document.getElementById('genderreadonlyid').value;    
    }

     var classgender = document.getElementById('classgender').value;


     //alert(gender+' : '+classgender);
     if(gender != classgender && classgender != 'Both') {
      AlertWebThis("Child's gender & " + rtype + " selection do not match.");
      return false;
     }
     }
     
 
    if(document.getElementById('formatBirthday') != null) {
    var studentbirthday = document.getElementById('formatBirthday').value;
   // alert('1: '+studentbirthday);
    } else {
    var studentbirthday_month = document.getElementById('Birthday_Month').options[document.getElementById('Birthday_Month').selectedIndex].value;
    var studentbirthday_day = document.getElementById('Birthday_Day').options[document.getElementById('Birthday_Day').selectedIndex].value;
    var studentbirthday_year = document.getElementById('Birthday_Year').options[document.getElementById('Birthday_Year').selectedIndex].value;
    var studentbirthday = studentbirthday_month+'/'+studentbirthday_day+'/'+studentbirthday_year;
    //alert('2: '+studentbirthday);
    }
        
     
     var sessionstart = document.getElementById('sessionstart').value;
    // alert(sessionstart);
    // if(rtype != 'Camp') {
 
     var agelow = document.getElementById('agelow').value;
     //agelow = agelow - 1;
     agelow = 12*(parseFloat(agelow));
     agelow = agelow - 1;
     var agehigh = document.getElementById('agehigh').value;
     agehigh = Math.ceil(agehigh);
     agehigh++;
     agehigh = 12*(agehigh);
     agehigh--;
     agehigh = parseFloat(agehigh);
     
    
    var user_date = Date.parse(studentbirthday);
    //var today_date = new Date();
    //var diff_date =  today_date - user_date;
    var session_date = Date.parse(sessionstart);
    //alert(session_date+' '+user_date);
    var diff_date =  session_date - user_date;
    
    var num_years = diff_date/31536000000;
    var num_months = (diff_date % 31536000000)/2628000000; 
    
    //alert(num_years+' : '+num_months);
    //var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;
    var student = 12*(Math.floor(num_years))+(Math.floor(num_months));
    
    //alert(agelow+' < '+student+' > '+agehigh);
  
    if(num_years < 0 || num_months < 0) {
    AlertWebThis("Child's age & " + rtype + " selection do not match.");
    return false;
    }
    
    //if(rtype != 'Camp') {
    if(student > agehigh || student < agelow) {
      AlertWebThis("Child's age & " + rtype + " selection do not match.");
      return false;
      }
   } else {
     //var sAge = theForm.elements['Age'].value;
     var sAge = parseInt(theForm.elements['Age'].options[theForm.elements['Age'].selectedIndex].value);
     var age = parseInt(document.getElementById('agelow').value);
     var agelimit = document.getElementById('agehigh').value;


     if(agelimit == 'over') {
     
      if(sAge < age) {
      AlertWebThis("Child's age & " + rtype + " selection do not match.");
      return false;    
      }
     
     }

     if(agelimit == 'under') {
     
      if(sAge > age) {
      AlertWebThis("Child's age & " + rtype + " selection do not match.");
      return false;    
      }
     
     }
     
   }
    $('validSubmit').value = 'valid';
    //document.forms['RegistrationWeb'].submit();
    return true;
 
}

function SecureCheckout() {
    document.forms['Resume'].submit();
}

function AlertWebThis(txt) {

if(txt.length == 0) txt = 'Please, fill out all required fields.';
alert(txt);
}

function CheckAccountWebForm() {
var hcheck = 0;
var theForm = document.forms['CreateAccountWeb'];

   for(i=0; i<theForm.elements.length; i++) {
    
      if((theForm.elements[i].type == "text" || theForm.elements[i].type == "password") && theForm.elements[i].value == '' && theForm.elements[i].name != 'ParentEmail') {

      AlertWebThis(''); 
      return false;
      }
      
    
      if(theForm.elements[i].name == 'AccountEmail') {      
        if(CheckEmailWebForm(theForm.elements[i]) == false) return false;     
      }


      if(theForm.elements[i].name == 'ParentEmail' && theForm.elements[i].value != '' ) {
        if(CheckEmailWebForm(theForm.elements[i]) == false) return false;  
      }
     
      if(theForm.elements[i].type == "select-one") {
       if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == '') {
            AlertWebThis('');
            return false;
            }
            
      }
    
    
    if(theForm.elements[i].type == "checkbox" && theForm.elements[i].name.indexOf("HowDidYouFind") != -1 && theForm.elements[i].checked == true) {   
    hcheck++
    }
         
    }
    
     if(hcheck == 0) {
     AlertWebThis(''); 
     return false;     
     }



      if(theForm.AccountPassword.value != theForm.AccountPasswordRepeat.value) {
      theForm.AccountPassword.value = '';
      theForm.AccountPasswordRepeat.value = '';
      AlertWebThis('The passwords do not match.');
      return false;
      }
   

    return true;
}

function CheckManageMemberWebForm() {

var theForm = document.forms['ManageMemberWeb'];
   //alert(theForm.name);
   for(i=0; i<theForm.elements.length; i++) {
     //alert(theForm.elements[i].name);
    
      if(theForm.elements[i].type == "text" && theForm.elements[i].value == '' && theForm.elements[i].name != 'ParentEmail') {
      AlertWebThis(''); 
      return false;
      }


      if(theForm.elements[i].name == 'ParentEmail' && theForm.elements[i].value != '' ) {
        if(CheckEmailWebForm(theForm.elements[i]) == false) return false;  
      }
      
      if(theForm.elements[i].type == "select-one") {
       if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == '') {
            AlertWebThis('');
            return false;
            }
            
      }          
    }


    return true;
}

function CheckManageStudentWebForm() {

var gcheck = 0;
var theForm = document.forms['ManageStudentWeb'];
   //alert(theForm.name);
   for(i=0; i<theForm.elements.length; i++) {
     //alert(theForm.elements[i].name);
    
      if(theForm.elements[i].type == "text" && theForm.elements[i].value == '' && theForm.elements[i].name != 'Middle_Name') {
      AlertWebThis(''); 
      return false;
      }
      
    if(theForm.elements[i].type == "radio" && theForm.elements[i].name == 'Student_Sex' && theForm.elements[i].checked == true) {
    gcheck++;
    }
    
      if(theForm.elements[i].type == "select-one") {
       if(theForm.elements[i].options[theForm.elements[i].selectedIndex].value == '') {
            AlertWebThis('');
            return false;
            }
            
      }
           
    }
    
    
     if(gcheck == 0) {
     AlertWebThis(''); 
     return false;     
     }

    return true;
}

function CheckManageAccountWebForm() {

var hcheck = 0;
var theForm = document.forms['ManageAccountWeb'];
   //alert(theForm.name);
   for(i=0; i<theForm.elements.length; i++) {
     //alert(theForm.elements[i].name);
    
      if(theForm.elements[i].type == "text" && theForm.elements[i].value == '' && theForm.elements[i].name != 'ParentEmail' && theForm.elements[i].name != 'AccountEmail') {
      AlertWebThis(''); 
      return false;
      }
      
      if(theForm.elements[i].name == 'ParentEmail' && theForm.elements[i].value != '' ) {
        if(CheckEmailWebForm(theForm.elements[i]) == false) return false;  
      }
          
    }



      if(theForm.AccountPassword.value != theForm.AccountPasswordRepeat.value) {
      theForm.AccountPassword.value = '';
      theForm.AccountPasswordRepeat.value = '';
      AlertWebThis('The passwords do not match.');
      return false;
      }
    

    return true;


}


function CheckEmailWebForm(mail){
	
	if ((mail.value==null)||(mail.value=="")){
		alert("Must contain an e-mail address!");
		mail.focus()
		return false
	}
	

	if (check(mail.value)==false){
		//mail.value=""
		mail.focus()
		return false
	}
	
	return true
	
}

function CheckInvitCode(str) {

  var invicodereverse = '';

  for (i = 0; i <= str.length; i++) {
    invicodereverse = str.charAt (i) + invicodereverse
  }
  return invicodereverse;
}


/* INFO NEWS */

function LoadNews() {

    var url = "System/Ajax/InfoNews.php";
		var pars = "";
		var myAjax = new Ajax.Updater(
				'infodiv', url, 
				{method: 'get', parameters: pars}
        );
	}

var RemoveTotal = function() {

    if($('regtotal')) $('regtotal').innerHTML = '';
}

