var jsonData;
var jsonCampusData;

$(function() {
    try {
        /*$('body').css("backgroundColor", "red");*/
        $('body').css("backgroundColor", bodyColor);			
        if( $('select.programCategoryGroups').val() != '' && ($('select.programCategoryGroups').length > 0) ){
            if (programOfInterest.checkDependency()) {
                programOfInterest.getPrograms();
            }
        }				
		    //Run if Devry and has campusLocation select
		    if($("select#campusLocationId").length > 0) {
			      campusLocation.getCampuses();
		    }            
        if (prePopDayPhone != '') {
            $("input#daytime_phone_feed").val(prePopDayPhone);
            $("input#daytime_phone").val(prePopDayPhone);
        }
        if (prePopEveningPhone != '') {
            $("input#eveningtime_phone_feed").val(prePopEveningPhone);
            $("input#eveningtime_phone").val(prePopEveningPhone);
        }                                      
    } catch(ex) {}
	//can't .hide() because of focus events on validation error messages
    $('input#daytime_phone').css({
    	position: 'absolute',
    	top: '-999999px',
    	overflow: 'hidden'
    	});
    $('input#eveningtime_phone').css({
    	position: 'absolute',
    	top: '-999999px',
    	overflow: 'hidden'
    	});   
});


var dayPhoneValue;
var eveningPhoneValue;
var re = /^(?:\([0-9]\d{2}\)\ ?|[0-9]\d{2}(?:\-?|\ ?))[0-9]\d{2}[- ]?\d{4}$/;

$('input#daytime_phone_feed').keyup(function(){	
	if(!re.test($(this).val())) {
		//do nothing except clear phone field for next input
		$(this).prev('input').val('');
		$(this).parent('p').next('p#errorMessage').remove();	
		return false;	
		}
	else {
		dayPhoneValue = $(this).val().replace(/[^0-9]/g,'');
		$(this).prev('input').val(dayPhoneValue);
		$(this).parent('p').next('p#errorMessage').remove();			
	}
});

$('input#eveningtime_phone_feed').keyup(function(){
	if(!re.test($(this).val())) {
		//do nothing except clear phone field for next input
		$(this).prev('input').val('');
		$(this).parent('p').next('p#errorMessage').remove();	
		return false;
	}
	else {
		eveningPhoneValue = $(this).val().replace(/[^0-9]/g,'');
		$(this).prev('input').val(eveningPhoneValue);
		$(this).parent('p').next('p#errorMessage').remove();
	}
});


$('input#daytime_phone_feed').prev('input').focus(function(){
	//pass focus
	$('input#daytime_phone_feed').focus();
});


$('input#eveningtime_phone_feed').prev('input').focus(function(){
	//pass focus
	$('input#eveningtime_phone_feed').focus();
});


$('select.programCategoryGroups').change(function(){
    if (programOfInterest.checkDependency()) {
        programOfInterest.getPrograms();
    }
});

$('select.programOfInterest').change(function(){
    var programId = $(this).val();

    if(nursingProgramIds && nursingProgramIds.nursingProgramIds) {
        $.each(nursingProgramIds.nursingProgramIds, function(i, obj) {
            if(obj.programId == programId) {
                if($('.nursingQuestion')[0] == null) {
                    dynamicQuestions.revealNursingQuestion();
                }
                return false;
            } else {
                if($('.nursingQuestion')[0] != null) {
                    dynamicQuestions.removeNursingQuestion();
                }
            }
        });
    }
        
    //show relevant questions
    if (programId != ""){
        sidebar.update.byProgramOfInterest();
		dynamicQuestions.reset();
        dynamicQuestions.reveal(programId);        
    } else {
        dynamicQuestions.reset();
        sidebar.showDefault();
    }
});

$('select#campusLocationId').change(function(){
    campusLocation.getCampuses();
});

  var str1;
  var str2 = '...'
  var cut;
  
var programOfInterest = {
    element: $('select.programOfInterest'),
    reset: function(){
        programOfInterest.element.empty();
        programOfInterest.element.append('<option value="">---Choose a Program of Interest---</option>');
    },
    update: function(programs){
        programOfInterest.reset();
        if(programs.length == 0) {
        	alert('We\'re sorry, there are no programs that match your criteria.');
        }
        else {					
			$(programs).each(function(){
				str1 = this.label;
				if(str1.length > 55) {
					cut = str1.slice(0,55);
					this.label = cut.concat(str2);
				}	
				//if DEVERY AND HAS CAMPUS LOCATION 		
				if( isDevry == true && (typeof(selectedCampus) !== 'undefined') ) {
				  if((this.campusId == selectedCampus) || (this.campusId == null) || (this.campusId == '25285') ) {
				    programOfInterest.element.append('<option value="'+this.value+'">'+this.label+'</option>');
				  }
				}
				else {
					  programOfInterest.element.append('<option value="'+this.value+'">'+this.label+'</option>');
					}
				
			});		
        }

        /*Preselect if the option exists.*/
        if(preSelectedProgram != "") {
            $('select.programOfInterest')[0].value = preSelectedProgram;
			dynamicQuestions.reveal(preSelectedProgram);						
        }
    },
    checkDependency: function(){
        if (programOfInterest.getAreaOfStudy() == ""){
            programOfInterest.reset();
            return false;
        }

        return true;
    },
    getPrograms: function(){
        cursor.busy();
        $.ajax({type: 'POST', url: '/dynamic/school-form/uopPrograms', data: 'programCategoryGroups='+programOfInterest.getAreaOfStudy(),
            success: function(jsonObject){
                jsonData = eval('(' + jsonObject + ')');
                programOfInterest.update(jsonData.uopPrograms);
                cursor.reset();							
            }
        });
    },
    getAreaOfStudy: function(){
        return $('select.programCategoryGroups').val();
    }
};


var dynamicQuestions = {
    reset: function(){
        $('.questions').hide();
        $('input#directoryQuestions').val('');
        dynamicQuestions.resetQuestionValues();
    },

    resetQuestionValues: function() {
        $("select[name^='answersMap[']").each(function() {
            this.value = "";
        });

        $("input[name^='answersMap[']").each(function() {
            this.checked = false;
        });
    },

    reveal: function(programId){

        
        if(jsonData!=null){
        $(jsonData.questionIdsByProgramId[programId]).each(function(){
            $('.dynamicQuestion\\['+this+'\\]').parents('.questions').show();
            $('.dynamicRadio\\['+this+'\\]').show();
        });
        } else {
        $.each(questionIdsByProgramIdJson, function(i, obj) {
            $('.dynamicQuestion\\['+this+'\\]').parents('.questions').show();
            $('.dynamicRadio\\['+this+'\\]').show();
        });
        }

        //populate hidden field for validation
        var questionIds = new Array();

        //determine the question number by parsing class name
        $('[class*="dynamicQuestion"]').parents(':visible.questions').each(function(){
            $(this).children('p[class!="label"]').children('select');
            var selectorClass = $(this).children('p[class!="label"]').children('select').attr('class');
            var regEx = new RegExp("dynamicQuestion\\[(\\d\*)\\]");
            var matchArray = regEx.exec(selectorClass);
            selectorClass = matchArray[1];
            questionIds.push(selectorClass);
        });

        $(':visible[class*="dynamicRadio"][class^="radioQuestions"]').each(function(){
            var selectorClass = $(this).attr('class');
            var regEx = new RegExp("dynamicRadio\\[(\\d\*)\\]");
            var matchArray = regEx.exec(selectorClass);
            selectorClass = matchArray[1];
            questionIds.push(selectorClass);
        });

        /*if the nusring question exists, then prepend 3.*/
        if($("div.nursingQuestion").length > 0 && $("div.nursingQuestion").children('.radioQuestions').is(':visible')){
            if(jQuery.inArray("3", questionIds) != -1) {
                questionIds.unshift(questionIds.splice(jQuery.inArray("3", questionIds),1)[0]);
            } else {
                questionIds.unshift("3");
            }
        }
        var questionOrder = '';
        $(questionIds).each(function(index){
            questionOrder += this;
            if (index != ($(questionIds).length - 1)){
                questionOrder += ',';
            }
        });
        $('input#directoryQuestions').val(questionOrder);
    },

    nursingQuestion : null,

    revealNursingQuestion: function() {
        try {
            if(dynamicQuestions.nursingQuestion == null) {
                var divcontainer = document.createElement("div");
                divcontainer.className = "nursingQuestion";

                var nurseQuestionElements = $("div[class*='dynamicRadio[3]']").remove();
                nurseQuestionElements.each(function() {
                    divcontainer.appendChild(this);
                });

                dynamicQuestions.nursingQuestion = divcontainer;
            }

            $('.programOfInterestQuestion').after(dynamicQuestions.nursingQuestion);
        } catch(ex) {
            //the nursing quetsion is malformed.
        }
    },

    removeNursingQuestion: function() {
        try {
            var nurseQuestion = $('.nursingQuestion');
            if (nurseQuestion != null) {
                dynamicQuestions.resetQuestionValues();
                $(nurseQuestion).remove();
            }
        } catch(ex) {
            //the nursing quetsion is malformed.            
        }
    }
};

var sidebar = {
    update: {
        byProgramOfInterest: function(){
            sidebar.reset();
            sidebar.hideAll();
            $('div.description').after('<div class="programCopy"><h4>'+programCopy[$('select.programOfInterest').val()].title+'</h4><p>'+programCopy[$('select.programOfInterest').val()].description+'</p></div>');
        }
    },
    reset: function(){
        $('div.programCopy').remove();
        $('div[class^="programType"]').show();
    },
    hideAll: function(){
        $('div.description').hide();
        $('div.description').children().each(function(){
            $(this).hide();
        });
    },
    showDefault: function() {
        sidebar.reset();
        $('div.description').show();
        $('div.description').children().each(function(){
            $(this).show();
        });        
    }
};

var cursor = {
    busy: function(){
        $('body').addClass('operationBusy');
    },
    reset: function(){
        $('body').removeClass('operationBusy');
    }
};

var filterDesiredAreaOfStudy = {
		inTheDropDown : function(campusId) {
				var currentvalue = $('select.programCategoryGroups')[0].value;
				if(jsonCampusData.categoryGroupIdsByCampusId != null) {
						if(jsonCampusData.categoryGroupIdsByCampusId[campusId] != null) {
								$('select.programCategoryGroups').empty();
								$('select.programCategoryGroups').append('<option value="">---Select---</option>');
								$(jsonCampusData.categoryGroupIdsByCampusId[campusId]).each(function() {
										if(this.value != null & this.label != null) {
												$('select.programCategoryGroups').append('<option value="'+this.value+'">'+this.label+'</option>');
										}
								});

								$('select.programCategoryGroups')[0].value = currentvalue;              
								return false;
						}

						$('select.programCategoryGroups')[0].value = currentvalue;
				}
		}
}

var campusLocation = {
		element: $('select.campusLocation'),
		reset: function(){
				campusLocation.element.empty();
			 // campusLocation.element.append('<option value="">---Select---</option>');
		},
		checkDependency: function(){
				//only process 5 digit zipcodes
				if (campusLocation.getZipCode().length != 5){
						campusLocation.reset();
						return false;
				}
				
				return true;
		},
		getCampuses: function(){
				$.ajax({type: 'POST', url: '/dynamic/school-form/campusesByZip', data: 'searchZipCode='+campusLocation.getZipCode()+'&clientId='+clientId,
						success: function(jsonObject){
								jsonCampusData = eval('(' + jsonObject + ')');
								
								if (jsonCampusData.message){//message returned on zipcode lookup errors only
										campusLocation.renderError(jsonCampusData.message);
								} else {
										if(jsonCampusData.campuses.length > 0) {
											campusLocation.update(jsonCampusData.campuses);
											selectedCampus = campusLocation.getCampusLocation();
											//console.log('selectedCampus: '+selectedCampus);
											if($("input#uopCampusType").val() == 'campus') {
											filterDesiredAreaOfStudy.inTheDropDown(selectedCampus);
											}
										}
										else {
											selectedCampus ='';
											$("select#campusLocationId").parents(".question").remove();
											}
								}
						}
				});
		},
		getZipCode: function(){
				return campusZipLookup;
		},
		getCampusLocation: function(){
				return $('select.campusLocation').val();
		},
		update: function(campuses){
				campusLocation.reset();
				if(campuses.length == 0) {
					alert('We\'re sorry, there are no Campus Locations in your area. Please try a different Zip Code.');           	
				}  
				$(campuses).each(function(){
						var selected = '';
						if (campusLocationId == this.value || campusLocationIdFromBrowse == this.value) {
								selected = 'selected="selected"';
						}
						campusLocation.element.append('<option value="'+this.value+'" '+selected+'>'+this.label+'</option>');
				});
		},
		renderError: function(message){
				//reuse existing validation decorator with constructed error object   xc
				var error = {
						first: true,
						errorField: $('.zipfield').get(0),
						errorFocusField: $('.zipfield').get(0),
						errorMessage: message
				};
			 
				lmbValidationErrorDisplayer.showFirstError.render(error);
		}
}; 
