var active_step = 0;
var max_step = 9;
var form_copy_default = "<strong>Answer the following questions</strong> so that we can find schools that are right for you.";
var processing_step = 0;
var pixel_dropped = 0;
var completed_apps = 0;

/*
 * Ensure the user doesn't accidentally close the window before completing at
 * least one application
 */
function preventClose() {
	if (allowPreventClose && completed_apps == 0) {
		return "You have not asked any schools to send you information.\n\nDid you know that people with college degrees earn more money that those without a degree? All it takes is a few minutes to request information from a few schools, so you can learn about what they can offer you to help you get a more advanced degree…";
	}
}
window.onbeforeunload = preventClose;

$(function() {
	init_step(1);
	init_controls();

  $('input[name=country],select[name=lead[age]]').change(function() {
  	go_to_next_step();
  });

  $('select[name=degree_level]').change(function() {
     if ( $('select[name=degree_level]').val() == 1) {
         $('#hsgrad-year').show();
     }
     else {
         $('#hsgrad-year').hide();
         if ( $('select[name=degree_level]').val() > 1) {
             go_to_next_step();
         }
     }
  });

  $('select[name=hsgrad_year]').change(function() {
     go_to_next_step(); 
  });

  $('input[name=same_number]').change(function() {
     if ( $('#step6 input[name=same_number]:checked').val() ) {
          $('input[name=phone_work[area]]').val( $('input[name=phone_home[area]]').val() );
          $('input[name=phone_work[prefix]]').val( $('input[name=phone_home[prefix]]').val() );
          $('input[name=phone_work[suffix]]').val( $('input[name=phone_home[suffix]]').val() );
      }
      else {
          $('input[name=phone_work[area]]').val('');
          $('input[name=phone_work[prefix]]').val('');
          $('input[name=phone_work[suffix]]').val('');
     }
	});   
});

function form_vars_to_get(form_var_names)
{
    var get_string = "";
    var counter = 0;

    for(var_name in form_var_names)
    {
        var form_var_name = form_var_names[var_name];

        if( counter > 0)
            get_string += '&' + form_var_name + '=';
        else
            get_string += '?' + form_var_name + '=';

        if( $('input[name='+form_var_name+']').length )
        {
            get_string += $('input[name='+form_var_name+']').val();  
        }        
        counter++;        
    }

    return get_string;
}

function init_controls() {
    var previousActions;
	$('#main-form form').submit(function() {
		go_to_next_step();
		return false;
	});

    previousActions = function() {
        // If it's 7, then we are going through apps, so don't go back to the form.
		if (active_step == 7) {
			if (allow_previous) {
				$('#previous-application').val(1);
				go_to_next_step();
			}
			else {
				alert('There are no skipped applications to show.');
			}
		}
		else if (active_step > 1) {
			init_step(active_step - 1);
		}
    };

    // For original markup
	$('#controls img[src*=previous_on], #controls #step7-buttons img[src*=previous]').click(function() {
	   previousActions();
	});
    $('#controls #path-buttons img[src*=next], #controls img[src*=submit]').click(function() {
       go_to_next_step();
    });
    $('#controls #step7-buttons img[src*=next]').click(function() {
		if (active_step == 7) {
			$('#skip-application').val(1);
			go_to_next_step();
		}
	});

    // For new markup
    $('#controls div.button_back, #controls #step7-buttons div.button_back').click(function() {
	   previousActions();
	});
    $('#controls #path-buttons div.button_next, #controls div.button_submit').click(function() {
        go_to_next_step();
    });
    $('#controls #step7-buttons div.button_next').click(function() {
		if (active_step == 7) {
			$('#skip-application').val(1);
			go_to_next_step();
		}
	});
}

function go_to_next_step() {
	if (!processing_step && (active_step < max_step) ) {
	  if (validate_step(active_step)) {
	    ajax_lead_send(active_step);
	  }
  }
}

function init_step(i) {
	$('div.steps').hide();
	$('#step' + i).show();
	active_step = i;
	$('input#step').val(active_step);

	update_progress_bar(i);
	
	if (i == 1) {
		disable_prev_button();
	}
	else {
		enable_prev_button();
	}

	// Do this here, so we don't have to do it 10 times, as it only gets overridden on step 7 and 8.
	$('#form-copy').html(form_copy_default);

	if (window["setup_step" + i]) {
		window["setup_step" + i]();
	}
	
	// Google Analytics Code
	try {
		pageTracker._trackPageview('/step' + i);
	} catch(err) {}
}

function update_progress_bar(i) {
    var mult = Math.floor($('#progress-bar').width() / (max_step)); //14;
	//$('#progress-bar img').css("margin-left", -120 + i*mult)
    $('#progress-bar img').animate({'left': -120 + i*mult}, 500, 'swing');
}

function disable_prev_button() {
    // Original markup
	$('#controls img[src*=previous_on]').hide();
	$('#controls img[src*=previous_off]').show();
    // New markup
    $('#controls div.button_back').each(function(){
        $(this).removeClass('on').addClass('off');
        //$(this).addClass('off');
    });
}

function enable_prev_button() {
    // Original Markup
	$('#controls img[src*=previous_on]').show();
	$('#controls img[src*=previous_off]').hide();
    // New markup
    $('#controls div.button_back').each(function() {
       $(this).removeClass('off').addClass('on');
    });
}

function disable_next_button() {
    // Original markup
	$('#controls img[src*=next]').hide();
    // New markup
    $('#controls div.button_next').each(function() {
       $(this).removeClass('on').addClass('off');
    });
}

function enable_next_button() {
    // Original markup
	$('#controls img[src*=next]').show();
    // New markup
    $('#controls div.button_next').each(function() {
       $(this).removeClass('off').addClass('on');
    });
}

function validate_step(i) {
	return window["validate_step" + i]();
}

function setup_step1() {
	$('#right .element').hide();
	$('#right #main-image').show();
}
function validate_step1() {
	if ($('#step1 select[name=lead[age]]').val() != 'Select') {
		return true;
	}
	else {
		alert("You must select your age");
		return false;
	}
}

function setup_step2() {
	$('#right .element').hide();
	$('#right #school-count').show();
}
function validate_step2() {
	if ($('#step2 input[name=country]:checked').val()) {
		return true;
	}
	else {
		alert("You must select a country");
		return false;
	}
}

function validate_step3() {
	var valid = true;
	var messages = '';

	var val = $('#step3 input[name=lead[zip]]').val();
	if (! /^\d{5}/.test(val) ) {
		messages += "You must provide a valid zip code.\n";
		valid = false;
	}

	var val = $('#step3 input[name=lead[email]]').val();
	if (! /^.+@.+/.test(val) ) {
		messages += "You must provide a valid email address.\n";
		valid = false;
	}

	val = $('#step3 select[name=degree_level]').val();
	if( val == undefined || val == '0' ) {
    messages += "You must select your highest level of education.\n";
    valid = false;
    }

    val = $('#step3 select[name=hsgrad_year]').val();
    if (($('#step3 select[name=degree_level]').val() == 1) && (val == undefined || val == '')) {
        messages += "You must select your high school graduation year\n";
        valid = false;
    }

	if (!valid) {
		alert(messages);
	}
	return valid;
}

function setup_step4() {
  $('select[name=area_of_study]').change(function() {
    var val = $(this).val();
    if (val > 0 || $(this).children().size() < 2) {
      $.getJSON('/school-browser/concentrations/' + $(this).val() + '/?' + $('#lead_form').serialize(), inject_divs);
    }
  });

	//
	// If we have pre-selected a vertical ala-server-side, then go ahead and fire off
	// the AJAX request to load the concentrations.
	//
	if ($('select[name=area_of_study]').val() > 0) {
		var val = $('select[name=area_of_study]').val();
		$.getJSON('/school-browser/concentrations/' + val + '/?' + $('#lead_form').serialize(), function(data) {
			inject_divs(data);
			$('#concentration').focus();
		});
	}
}

function validate_step4() {
	var valid = true;
	var messages = '';

	var area_val = $('#step4 select[name=area_of_study]').val();
	if ( area_val == undefined || area_val == '0') {
		messages += "You must select an area of study.\n";
		valid = false;
	}

	val = $('#step4 select[name=concentration]').val();
	if( val == undefined || val == '0' ) {
    messages += "You must select a concentration.\n";
    valid = false;
  }
    
	if (!valid) {
		alert(messages);
	}

	return valid;
}

function setup_step5() {        
	$('#step5 select[name=degree_type]').change(function() {
		go_to_next_step();
	})
}

function validate_step5() {
	var valid = true;
	var messages = '';

	var val = $('#step5 select[name=degree_type]').val();
	if ( val == undefined || val == '0' ) {
		messages += "You must select a degree type.\n";
		valid = false;
	}

	if (!valid) {
		alert(messages);
	}

	return valid;
}

function ie6Positioning() {
	if ('\v'=='v') {
		var h = $('#main-form').height();
		$('#main-form').height(h);
		$('#controls').css('bottom', '10px');
	}
}

function setup_step6() {
}

function validate_step6() {
	var valid = true;
	var messages = '';

	var val = $('#step6 input[name=lead[first_name]]').val();
	if (val == undefined || $.trim(val).length < 2) {
		messages += "You must provide your first name.\n";
		valid = false;
	}
	
	var val = $('#step6 input[name=lead[last_name]]').val();
	if (val == undefined || $.trim(val).length < 2) {
		messages += "You must provide your last name.\n";
		valid = false;
	}
	
	var val = $('#step6 input[name=lead[address1]]').val();
	if (val == undefined || $.trim(val) == '') {
		messages += "You must provide your address.\n";
		valid = false;
	}
	
	var phone_home = $.map(['phone_home[area]', 'phone_home[prefix]', 'phone_home[suffix]'], function(str) {
		return $.trim( $('#step6 input[name=' + str +']').val() );
	}).join('-')
	var phone_work = $.map(['phone_work[area]', 'phone_work[prefix]', 'phone_work[suffix]'], function(str) {
		return $.trim( $('#step6 input[name=' + str +']').val() );
	}).join('-')
	
	if ( ! /^[1-9]{1}\d{2}-\d{3}-\d{4}$/.test(phone_home) ) {
		messages += "You must provide your home phone number.\n";
		valid = false;
	}
	if ( ! /^[1-9]{1}\d{2}-\d{3}-\d{4}$/.test(phone_work) ) {
		messages += "You must provide your work phone number.\n";
		valid = false;
	}

	if (!valid) {
		alert(messages);
	}

	return valid;
}

function setup_step7() {	
	$('#right .element').hide();
	$('#right #school-details').show();
	
	$('#form-copy').html("You're so close! Please finish the following questions to request information from this school");
	
	$('#path-buttons').hide();

    // If there is a hs graduation year input box with name=data[hsgrad]
    if ($('#step7 input[name=data[hsgrad]]').val() != undefined) {
        // Then pre-populate it with a _valid_ value if we have one
        var grad_year = $('select[name=hsgrad_year]').val();
        if ((grad_year != undefined) && (grad_year != '') && (grad_year > 1)) {
            $('#step7 input[name=data[hsgrad]]').val(grad_year);
        }
    }

    // Show the congrats div if they submitted already
    if (completed_apps > 0) {
        $('#congrats').show();
    }
    
    $('#step7-buttons').show();
}

function validate_step7() {
	// If they are skipping this application, don't bother validating it.
	if ($('#skip-application').val() == 1 || $('#previous-application').val() == 1) {
		return true
	}
	
	var valid = true;
	var messages = [];

    var program_val = $('#program_id select[name=program_id]').val();
	if( program_val == undefined || program_val == '' ) {
        messages = add_err_message("You must select a program", messages)
        valid = false;
    }

    $('#additional_data_table input[name*=data], #additional_data_table select[name*=data]').each(function()
    {
        $(this).removeClass("error_element");

        if( !valid_add_data_field($(this)) )
        {
    	    var field_label  = $(this).closest("tr").prev().children('td:first').text();
            $(this).addClass("error_element");

            if( field_label && field_label != '' )
            {
      	        field_label = field_label.replace('*', '');
                field_label = field_label.replace(':', '');
                field_label = jQuery.trim(field_label);

                if( field_label.length >= 3 )
                {
        	        messages = add_err_message(field_label + " is not valid", messages);
                }
				else if ($(this).attr('type') == "checkbox") {
					messages = add_err_message("You must check any required checkboxes to submit this application", messages);
				}
            }
			else if ($(this).attr('name') && $(this).attr('name').match(/birth/)) {
				messages = add_err_message("You must select your birthday", messages);
			}

			valid = false;
        }
    });

	if (!valid && messages.length > 0) {
		alert(messages.join("\n"));
	}
    else
    {
	    completed_apps++;
  	    valid = true;
    }

    return valid;
}

function setup_step8() {
	$('#form-copy').html("");
	$('#controls').hide();
}

function add_err_message(m, arr) {
	if ( $.inArray(m, arr) == -1 ) {
		arr.push(m);
	}
	return arr;
}

function valid_add_data_field(field) {
	var val = field.val();
	var valid = true

	if (val == undefined || $.trim(val) == '') {
		valid = false;
	}
	else if ( $(field).attr('type') == "checkbox" && !$(field).attr('checked') ) {
        var c = $(field).closest('tr').prev().find('.red').html();
        if (c == null) {
            c = $(field).closest('tr').find('.red').html();
        }
        if (c && c.indexOf('*') >= 0)
		    valid = false;
	}
	else if ( $(field).attr('type') == 'radio' ) {
		var fname = $(field).attr('name');
		if ( $('input[name=' + fname + ']:checked').size() == 0 ) {
			valid = false;
		}
	}
	else {
		valid = test_special_cases(field);
	}

	return valid;
}

function number_from_field(field) {
	var val = field.val();
	if (val == parseFloat(val)) {
		return val;
	}
	else {
		return false;
	}
}

function selectHasAnyNumericOptions(field) {
    if(!field.attr('type').match(/select/)) return false;

    var hasNumericOpt = false;
    field.find("option").each(function(opt){
       var val = $(this).val();
       if (!isNaN(parseFloat(val)) && isFinite(val))
            hasNumericOpt = true;
    });
    return hasNumericOpt;
}

function test_special_cases(field) {
	var field_label  = field.closest("tr").prev().children('td:first').text();
	var type = field.attr('type');
	var name = field.attr('name');
	var num_val = number_from_field(field);
	
	switch (name) {
		case 'data[hsgrad]':
			return (num_val && (num_val > 1900)) ? true : false
			break;
		case 'data[yrsExperience]':
			return (num_val && (num_val >= 0)) ? true : false
			break;
	}
	
	if (field_label.match(/GPA/)) {
        if (type.match(/select/)) {
            if(selectHasAnyNumericOptions(field)) {
                return (num_val && (num_val > 0) && (num_val < 5));
            }
        }
        else {
		    return (num_val && (num_val > 0) && (num_val < 5)) ? true : false
        }
	}
	else if (name == 'data[gmat]' || (field_label.match(/GMAT/) && !(field_label.match(/date/))) ) {
		return (num_val && (num_val >= 200) && (num_val <= 800)) ? true : false
	}

	return true;
}

//
// Before the request is sent, set processing_step to 1, to block other requests.
// After the request is complete, the success or failure callback will set
// processing_step back to 0.
//
function ajax_lead_send()
{
	if (active_step == 7) {
		$('div#controls img[src*=ajax]').css('visibility', 'visible');
	}
	
	var options = {
  	dataType: 'json',
  	success:  ajax_lead_response,
		complete: function() {
			processing_step = 0;
			$('div#controls img[src*=ajax]').css('visibility', 'hidden');
		}
	};

	processing_step = 1;
  $('#lead_form').ajaxSubmit(options);
}

function ajax_lead_response(data)
{
	// Tell the page that processing is done.
	processing_step = 0;
	
	inject_divs(data);
	
	if (typeof data.allow_previous != "undefined" && data.allow_previous) {
		allow_previous = true;
	}
	else {
		allow_previous = false;
	}

    // Bring user back to top after school load
    if (active_step === 7) {
        $('body').scrollTop(0);
    }
	
	if (typeof data.force_step != "undefined")
	{
  	    init_step(data.force_step);
	}
	else
	{
  	    init_step(active_step + 1);
	}

	if (data.lead) {
		update_lead_form(data.lead);
	}

	if (data.errors) {
		alert(data.errors);
	}
}

function update_lead_form(lead) {
	$('#lead_city').val(lead.city);
	$('#lead_zip_value').html(lead.zip);
	$('#lead_state').val(lead.state);
}

function inject_divs(data)
{
	if (typeof data.divs != "undefined")
	{
		for(div_id in data.divs)
	  {
			if (div_id == 'concentrations') {
				var content = $(data.divs[div_id]).change(function() {go_to_next_step();});
				$('#'+div_id).html(content);
				continue;
			}
			
			if (div_id == 'pixel_holder') {
				if ( pixel_dropped == 0) {
					pixel_dropped = 1;
					$('#'+div_id).html(data.divs[div_id]);
				}
			}
            else {
				$('#'+div_id).html(data.divs[div_id]);
			}
		
		  if( div_id == 'school_form_fields')
		  {
		  	$('#school_form_fields .label').each(function() {
		    	var label_data = '<tr><td class="label"><br /><br />' + $(this).html() + '</td></tr>';
		    	$(this).parent().before(label_data);
		    	$(this).remove();
		    });
		  }
		}
	}
}