// JavaScript Document

// example:
// populateForm(
//   landmarkForm,
//   {
//     'landmarkId' : 123,
//     'landmarkName' : 'home',
//     'landmarkStreet' : 'Sesame St."
//     [ , ... ]
//   }
// );

function populateForm(formElement, fieldValueMap) {
	for (var i in fieldValueMap) {
		var field = form.elements[i];
		if ( ! field) {
			throw 'field "' + i + '"does not exist in form "' + formElement.name + "'";
		}
		form.elements[i].value = fieldValueMap[i];
	}
}

var FormLoader = new Object();
// dummy impl for now. So be sure to call it after form has at least been
// written to document, so that it actually works.
FormLoader.queue = function(fn) { fn(); }

function formContaining(htmlElement) {
    if (htmlElement.nodeName.toLowerCase() == "form") { return htmlElement; }
    if (htmlElement.parentNode == null) { return null; }
    return formContaining(htmlElement.parentNode);
}

//Returns the value of the selected radio button
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

toplevel="100";
botlevel="-10";


//validates a 'group' of radio buttons or checkboxes.
function validateNamedGroupGeneric(group, attPopup){
	var checked = false;
	//if there is only one checkbox or radiobutton, element has no length properties.
	//just check for group.checked
	if(group.length==null){
		checked = group.checked
	}else{
		for(i = 0; i < group.length; i++){
			if( group[i].checked){
				checked = true;
				break;
			}
		}
	}
	
	if(!checked){
		riseupToLevel(attPopup, "200");
		return false;
	} else {
		return true;
	}
}

//Validate email addresses
function validateEmailAddressGeneric(formElement, attPopup){
	//validate email
    regex = /^[\w-_\.]*[\w-_\.]\@[\w]+\.+[\w]+[\w]$/;
    var valid = validateTextInputGeneric(formElement, attPopup, regex);
    if(!valid){
    	return false;
    }else{
    	return true;
    }
}

//Validates phone numbers.
function validatePhoneNumberGeneric(formElements, attPopup){
	var regex1 = /\d{3}/;
	var regex2 = /\d{4}/;
	
	if( formElements.length == 3){
	//fields are split into 3 e.g. areacode, pre, post
		if( !validateTextInputGeneric(formElements[0], attPopup, regex1) || 	//area code must be three digits
			!validateTextInputGeneric(formElements[1], attPopup, regex1) ||		//pre must be three digits
			!validateTextInputGeneric(formElements[2], attPopup, regex2)	   	//post must be four digits
			){ 
			return false;
		} else {
			return true;
		}
	}
}

//Validates that the text input is NOT null. if a third arg
//is supplied it'll be treated as a REGEX and will verify if the
//value of that element matches a certain regular expression.
function validateTextInputGeneric(formElement, attPopup){
	var valid = true;
	if( formElement.value.length == 0 ){
		valid = false;
	} else if( arguments.length == 3 ){
		//got regex
		var regex = arguments[2];
		var match = new String(formElement.value.match(regex));
		if( match.toLowerCase() == 'null' || match.length < formElement.value.length ){
			valid = false;
		}
	}
	
	if(!valid){
		riseupToLevel(attPopup, "200");
	}
	return valid;
}

//Validates that a value has been added to a the message textarea in sendSMS
function validateTextarea(form, attPopup) {
		if (form.message.value.length == 0 )  {
			riseupToLevel(attPopup, "202");
			return false;
		}
		else {
			form.submit();
			return true;
			}
}


//validates the Add Contact form
function validateAddContact(form){
	
	//validate name
	var nameValid = validateTextInputGeneric(form.name, 'hid_attName');
	
	//validate phone
	var phonefields = new Array(form.phonea, form.phoneb, form.phonec);
	var phoneValid = validatePhoneNumberGeneric(phonefields, 'hid_attPhone');
	

	if( nameValid && phoneValid ){
		form.submit();
		return true;
	}else{
		return false;
	}
}

//Validates the Add Landmark form
function validateAddLandmark(form) {
		var error_string = "";
		if (form.name.value.length == 0 )  {
			error_string += "<li>a name</li>";
		}
		if (form.address.value.length == 0 )  {
			error_string += "<li>the street address</li>";
		}
		if (form.city.value.length == 0 )  {
			error_string += "<li>the city</li>";
		}
		if (form.province.value.length == 0 )  {
			error_string += "<li>the state</li>";
		}
		if (error_string == "") {
			form.submit();
			return true;
		}
		else {
			error_string = "The following information is missing:<br /><ul>" + error_string + "</ul>"; 
			UI.notify_error(error_string);
			return false;
			}
}

//on Add Location Check
function validateAlertTypeRadioButtons(form, attPopup){
	var valid = validateNamedGroupGeneric(form.alertType, attPopup);
	
	if(valid){
		selectNextDialog(form, 'hid_addSchPeople');
	}
	
	return valid;
}


//on Add Alert, validates location check details
function validateLocationCheckDetails(form, box1, box2){
	//var validcb = validateNamedGroupGeneric(form.day, 'hid_attDaysOfWeek');
	var validcb = validateCheckboxes(form);
	var validselects = validateSelect(form);
	var valid = validcb && validselects;
	
	if(valid){
		switchbox(box1, box2);
	}else{
		hideSelects('hid_landmark');
	}
	
	return valid;
}

// On ADD ALERT FORM - works with PREVIOUS button on the 3rd dialog
// opens the correct second dialog based on which radio button was selected on first dialog
function selectPreviousDialog(box1) {                                               
        var alertPref = getCheckedValue(document.addAlertPeopleForm.alertType); 
        if (alertPref == 1) {                                    
            var box2 = "hid_addSchPeople-2Prox";                           
        }                                                   
        if (alertPref == 2) {
            var box2 = "hid_addSchPeople-2Timed";                          
        }                                                                      
        if (alertPref == 4) {                                                   
       		var box2 = "hid_addSchPeople-2Poll";                                    
        }                                                                       
        // pushes dialog to bottom
        document.getElementById(box1).style.zIndex = botlevel;                  
        // pulls dialog to top                                               
        document.getElementById(box2).style.zIndex = toplevel;                  

        showSelects(box2);                                                      
        hideSelects(box1);                                                      
        return true;                                                            
}                       

// On ADD ALERT FORM - works with NEXT button
// opens correct second dialog based on radio button selected on first dialog 
function selectNextDialog(form, box1) {
	var dialogs = new Array();
	dialogs['1'] = "hid_addSchPeople-2Prox";
	dialogs['2'] = "hid_addSchPeople-2Timed"
	dialogs['4'] = "hid_addSchPeople-2Poll"
	
	var alertPref = getCheckedValue(form.alertType);
 	
 	box2 = dialogs[alertPref];
	
 	document.getElementById(box1).style.zIndex = botlevel;
	document.getElementById(box2).style.zIndex = toplevel;

	//enable form elements for dialog to show
	disableFormElements(box2, false);

 	//disable form elements for the other dialogs
    for(x in dialogs){
        if(x != alertPref){
            disableFormElements(dialogs[x], true);
        }
    }

	showSelects(box2);
	hideSelects(box1);
	return true;
}

//Makes sure that one days of the week checkbox is selected on the addAlert page	
function validateCheckboxes(form) {
	var checkbox_selected = "no" ;
	var daysOfWeek = [ form.elements.sun, form.elements.mon, form.elements.tue, form.elements.wed, form.elements.thu, form.elements.fri, form.elements.sat ];
	for (i = 0; i < daysOfWeek.length; i++) {
		var day = daysOfWeek[i];
		if(!day.length){
    		if(daysOfWeek[i].checked){
	    		checkbox_selected = "yes";
				return true;
			}
		}else{
			for(j = 0; j < day.length; j++){
				if(day[j].checked){
					checkbox_selected = "yes";
					return true;
				}
			}
		}
		
	}
	if (checkbox_selected == "no") {
		riseupToLevel('hid_attDaysOfWeek', "200");
		return false;
	}
}

//Validates the the landmark id select box	
function validateSelect(form) {
	if (form.landmarkId.value != "None")  {
			return true;
	} else {
			riseupToLevel('hid_attLandmark', "200");
			return false;
	}
}

// Validates the addAlert (ie Add Safety Check) form 
// NOTE: Sprint no longer uses this function for validating safety checks, instead validateSafetyCheckForm is used
function validateSafetyCheck(form, box1, box2) {
	 var check_checkboxes = validateCheckboxes(form); 
     var check_selectboxes = validateSelect(form); 

  if (check_checkboxes && check_selectboxes) {
	  		/* pushes dialog to bottom */
		 	document.getElementById(box1).style.zIndex = botlevel;
			/* pulls dialog to top */
			document.getElementById(box2).style.zIndex = toplevel;

			showSelects(box2);
			hideSelects(box1);
    		return true;
  }
  else
    return false;
}

// Validates the addAlert (ie Add Safety Check) form in SPRINT
function validateSafetyCheckForm(form, box1, box2) {
	var errorMess = "";
	/* validate checkboxes */
	var checkbox_selected = "no" ;
	var daysOfWeek = [ form.elements.sun, form.elements.mon, form.elements.tue, form.elements.wed, form.elements.thu, form.elements.fri, form.elements.sat ];
	for (i = 0; i < daysOfWeek.length; i++) {
		var day = daysOfWeek[i];
		if(!day.length){
    		if(daysOfWeek[i].checked){
	    		checkbox_selected = "yes";
			}
		}else{
			for(j = 0; j < day.length; j++){
				if(day[j].checked){
					checkbox_selected = "yes";
				}
			}
		}
		
	}
	if (checkbox_selected == "no") {
		errorMess += "You must select a day of the week." + "<br />" + "<br />";
	}

	if (form.landmarkId.value != "None")  {
	} else {
		errorMess += "You must select a landmark. If you do not have a landmark in the list, you must first add one.";
	}

  if (errorMess == "") {
	  		/* pushes dialog to bottom */
		 	document.getElementById(box1).style.zIndex = botlevel;
			/* pulls dialog to top */
			document.getElementById(box2).style.zIndex = toplevel;

			showSelects(box2);
			hideSelects(box1);
    		return true;
  }  else {
	UI.notify_dialogError(errorMess, "200");
    return false;
  }
}