var prog_field = new Array();
var confirmed = false;

// ignore enter key presses
$(document).keypress(function(key) {
	if(key.keyCode == 13) {
		return false;
	}
});

$(document).ready(function() {
    /*
    jQuery.validator.addClassRules({
        zipcode: {
            minlength: 5,
            maxlength: 5
        },
        required: {
            required: true
        }
    });
    */
	
    $("form").validate({
        debug: true,
        errorElement: "div",
        errorClass: "error",
        validClass: "success",
		ignore: ":hidden",
        onkeyup: false,
        errorPlacement: function(error, element) {
            $(error).hover(
                function(){
                    if($("div div", error).length == 0) $("div", error).prepend("<div></div>");
                    $('.errormessage', error).topZIndex();
                    $('.errormessage', error).fadeIn();
                },
                function(){
                    $('.errormessage', error).fadeOut();
                }
            );
                if($(element).attr('type') == 'radio') {
                    $(element).parent().after(error);    
                }
                else {
                    $(element).after(error);
                }
        },
        success: function(label) {
            label.addClass("success");
        },
        submitHandler: function(form) {
        	$('select:[name=state]','.formrow').removeAttr('disabled');
            if($('.schoolquestions').length > 0) {
                if($('.checkdiv input:checked').length < 1) {
                    showError('Please select <span>at least one school</span>.');
                }
                else if(numAllowedSchools > 1 && $('.checkdiv input:checked').length == 1 && $('.schoolquestions').length > 1) {
                    if(!confirmed){
                        confirmed = true;
                        showConfirm('Selecting <span>more than one school</span> will help you find the <span>best program</span>.', 'Select More Schools');
                    }
                    else {
                        $('.checkdiv input:not(:checked)').each(function(i,elem) {  
                            //schoolquestions = $(elem).parents('.schoolquestions');
                            school = $(elem).parents('.school');
                            $('.schoolquestions select', school).remove();
                        });
                        $('.loading_img').show();
						form.submit();
                    }
                }
                else {
                    $('.checkdiv input:not(:checked)').each(function(i,elem) {  
                        //schoolquestions = $(elem).parents('.schoolquestions');
                        school = $(elem).parents('.school');
                        $('.schoolquestions select', school).remove();
                    });
                    $('.loading_img').show();
					form.submit();   
                }
            }
            else {
                $('.loading_img').show();
				form.submit();
            }
        },
        highlight: function(element, errorClass) {
            $(element).addClass('error');
            school = $(element).parents('.school')
            if($('.schoolquestions', school).length > 0) {
                school.addClass('active');
                $('.schoolquestions', school).slideDown();
            }
        }
    });
    
    jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, ""); 
            return this.optional(element) || phone_number.length > 9 &&
                    phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, '<div class="errormessage">Please specify a valid phone number</div>');
    
    jQuery.validator.addClassRules({
    	 zipcode: {
            minlength: 5,
            maxlength: 7,
            remote: "/schooldegrees/forms/checkpostalcode.php?type=fusion"
        },
		/*state: {
			remote: "/schooldegrees/forms/checkpostalcode.php?type=fusion"
		},*/
       phone: {
            phoneUS: true,
            remote: "/schooldegrees/forms/checkphone.php?type=fusion&country=US"
        },
        email: {
            onkeyup: false,
            remote: "/schooldegrees/forms/pingmx.php?type=fusion"    
        },
        required: {
            required: function(element) {
                schoolquestions = $(element).parents('.schoolquestions');
                school = schoolquestions.parent('.school');
                if(schoolquestions.length > 0) {
                    if($('.checkdiv input', school).is(':checked')) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    return true;
                }
            }
        }
    });
    
    $(".phone").mask("(999) 999-9999",{placeholder:"x"});
    if($('select:[name=state]','.formrow').val() !='')
    	$('select:[name=state]','.formrow').attr('disabled','disabled');

	$('input:[name=zipcode]').change(function(){
		$.ajax({
			type: "GET",
			url: "forms/modifystatecountry.php",
			data: 'postalCode=' + $('input:[name=zipcode]','.formrow').val() + '&stateToModify=state&cityToModify=city',
			success: function(result){
				var cityState = eval('(' + result + ')');
				$('#city','.formrow').val(cityState.city.city);
				$('select:[name=state]','.formrow').val(cityState.state.state);
				if(cityState.state.state)
					$('select:[name=state]','.formrow').attr('disabled','disabled');
				else
					$('select:[name=state]','.formrow').removeAttr('disabled');
			}
		});
		return true;
	});
   
});

function changeProgram(element) {
    var schoolquestions = $(element).parents('.schoolquestions');
    $('.customquestiondiv', schoolquestions).hide();
    $('.customquestion', schoolquestions).removeClass('required');
     
    if($.isArray(prog_field[$(element).val()])) {
        $(prog_field[$(element).val()]).each(function(i, val){
            //$('#' + val, schoolquestions).addClass('required');
            
            $('.' + val + 'item', schoolquestions).addClass('required');
            $('.' + val, schoolquestions).show();
        });
    }
}

function showError(message) {
    $('#overlay').height($('.form').height());
    $('#overlay').width($('.form').width())
    $('#errorbox .confirm-message').html(message);
    pos = $('.form').offset();
    $('#errorbox').css('top', pos.top);
    if(!$.browser.msie && parseInt(jQuery.browser.version) != 6) {
        $('#errorbox').css('left', pos.left + (($('.form').width() - 333) / 2));
    }
    $('#overlay').fadeIn();
    $('#errorbox').fadeIn();
    $('#errorbox').topZIndex();
}

function showConfirm(message) {
    $('#overlay').height($('.form').height());
    $('#overlay').width($('.form').width())
    $('#confirmbox .confirm-message').html(message);
    pos = $('.form').offset();
    $('#confirmbox ').css('top', pos.top);
    if(!$.browser.msie && parseInt(jQuery.browser.version) != 6) {
        $('#confirmbox ').css('left', pos.left + (($('.form').width() - 333) / 2));
    }
    $('#overlay').fadeIn();
    $('#confirmbox').fadeIn();
    $('#confirmbox').topZIndex();
}
