/** Very IMP!!! Do not delete comments meant to describe code.* */
// populated by PHP script

var schoolMatches = [];
var lastSchoolInList;
var navigationSchoolCount;

var currentStep;
var secondPage = 'view-school-questions-form-system';

var interstitialAcceptURL;
var interstitialRejectURL;
var interstitialIframeBreakout;

/**
 * Populates *selectedSchoolIds* Array.
 */
function saveSelectedSchoolIds(schoolIds)
{
    // alert(schoolIds);
    selectedSchoolIds = schoolIds;
}

/**
 * Email validation
 */
function IsValidEmail(email)
{
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return filter.test(email);
}

/**
 * Check to contain only characters.
 */
function isChar(val)
{
    var filter = /^([a-zA-Z]+[\s]*)+$/;
    return filter.test(val);
}

/**
 * Check to contain only characters and punctuation.
 */
function isCharPunc(val)
{
    var filter = /^([a-zA-Z_\s.\'])*$/;
    return filter.test(val);
}

/**
 * phone validation validation
 */
function isInteger(s, lengthval)
{
    var i;
    if (s.length!=lengthval)
    	return false;

    for (i = 0; i < s.length; i++)
    {
    	// Check that current character is number.
    	var c = s.charAt(i);
    	if (((c < "0") || (c > "9")))
    		return false;
    }

    // All characters are numbers.
    return true;
}

var stillProcessing = false; // global to keep track of which steps are still processing
/**
 * idVal - Div id of the container whose field data has to sent to the Server.
 * submitForm - Should the Prelead form be submitted. Default is false.
 */
function nextbtnAjax(idVal, submitForm, noOfSteps)
{
    var fieldVals;

    for (var i=1; i<=idVal; i++)
    {
    	jQuery('#step_'+i+' .form-item > *').each(function()
    	{
		    var fieldVal, fieldName;

		    fieldName = jQuery(this).attr('name');

    		if (jQuery(this).attr('type') == 'checkbox')
    			fieldVal = this.checked ? 'Y' : 'N';
    		else
    			fieldVal = jQuery(this).val();

			if (jQuery.trim(fieldVal) && fieldName)
			{
	    		if (fieldVals)
	    			fieldVals += '&'+fieldName+'='+fieldVal;
	    		else
    				fieldVals = fieldName+'='+fieldVal;
			}
    	});
    }

    // last submission has completed or this is the last step
    if ((!stillProcessing) || (noOfSteps==idVal))
   	{
    	stillProcessing = true;

	    $.ajax(
	    {
		    type: 'POST',
		    url: 'api/savePreleadField.php',
		    data: fieldVals,
		    dataType: 'html',
		    success: function(response)
			{
				stillProcessing = false;

				if (submitForm)
					submitFormData(noOfSteps);

				return true;
		    }
		});
   	}
}



function submitFormData(noOfSteps)
{
	var fieldVals;

    jQuery('#surveyForm .form-item > *').each(function()
    {
	    var fieldVal,fieldName;
	    fieldName = jQuery(this).attr('name');

	    if(jQuery(this).attr('type') == 'checkbox')
	    	fieldVal = this.checked?'Y':'N';
	    else
	    	fieldVal = jQuery(this).val();

		if(jQuery.trim(fieldVal) && fieldName)
		{
    		if(fieldVals)
    			fieldVals += '&'+fieldName+'='+fieldVal;
    		else
				fieldVals = fieldName+'='+fieldVal;
		}
	});

	jQuery.ajax(
	{
		type:		'POST',
		url:		'api/TestData.php',
		data:		fieldVals,
		dataType:	'json',
	    success:	function(response) { PreleadResponseCallback(response, noOfSteps); }
	});
}

function PreleadResponseCallback(response, noOfSteps)
{
	if (response.Error)
	{
		// IF Error return user to first step with a error.
		for (i=0; i<noOfSteps; i++)
		{
			var step = i+1;
			for (k=0; k<response.Errors.length; k++)
			{
				var stepElm = jQuery('#step_'+step+' .form-item > *[name='+response.Errors[k]['@attributes']['Type']+']');
				var errorField;
				if (stepElm.length > 0)
				{
					var dummyStep = noOfSteps + 1;
					jQuery('#step_'+dummyStep).hide();
					jQuery('#step_'+step).show();
					jQuery('.form_progress').show();
				    jQuery('.form_message').show();
				    jQuery('.form_footer').show();
				    updateSchoolMatches(step);
				    currentStep = step;
				    updateWizardProgress(noOfSteps,currentStep);

				    var label = jQuery(stepElm).parent().prev().text();
				    var error = response.Errors[k][0];

				    errorField = response.Errors[k]['@attributes']['Type'];
					if (errorField == "EmailAddress")
					{
						errorMsg = error;
					}
					else if (errorField == "Phone")
					{
						errorMsg = error;
					}
					else
					{
						error = error.split(' ');
					    error.shift();
						label = label.split('*');
						errorMsg = label[0] + ' ' + error.join(' ');
					}
					var formElement = jQuery(stepElm).parent().parent();
					formElement.find('.error-message').remove();
					jQuery(stepElm).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
					return;
				}
			}
		}
	}
	else
	{
		window.location = secondPage;
	}
}

/**
 * Update the progress of the Form Wizard.
 */
function updateWizardProgress(noOfSteps, currentStep)
{
    var oneStep = (100/noOfSteps);
    var percentComplete = parseInt(oneStep * (currentStep-1));
    var barWidth = (360*percentComplete)/100;

	if(percentComplete == 0)
		jQuery('.back').html('').show();
	else
		jQuery('.back').html('<a href="#">&lt; Back</a>').show();

	jQuery('.form_progress').show();
	jQuery('.percent_complete').html(percentComplete+'% Complete').show();
	jQuery('.progress_bar').css("width", barWidth).show();
}


/**
 * currentStep - The current step for which random school matches is being
 * calculated getFromCookie - Update the school matches from cookie values
 */
function updateSchoolMatches(currentStep, getFromCookie)
{
    if (!schoolMatches[currentStep])
    {
		if (getFromCookie)
		{
		    schoolMatches[1] = $.cookie("total-school-count");
		    jQuery('.school_matches_results .schools-total').text(schoolMatches[1]);
		    for (var i = 2;i <= 30;i++)
		    {
				var temp = $.cookie("total-school-count-"+i);
				if (temp)
				    schoolMatches[i] = temp;
				else // exit the loop as no more cookies are available.
				    break;
		    }
		}
		else
		{
		    var seed;
		    if (currentStep == 1)
		    {
				while (1)
				{
				    seed = Math.random();
				    if (seed > 0.8)
				    	break;
				}
				schoolMatches[currentStep] = Math.floor(seed*350);
				jQuery('.school_matches_results .schools-total').text(schoolMatches[1]);
				$.cookie("total-school-count", schoolMatches[1]);
		    }
		    else
		    {
				while (1)
				{
				    seed = Math.random();
				    if (seed < 0.4)
				    	break;
				}
				schoolMatches[currentStep] = (schoolMatches[currentStep-1] - Math.floor(seed*100));

				$.cookie("total-school-count-"+currentStep,schoolMatches[currentStep]);
		    }
		}
    }
    jQuery('.school_matches_results .schools-sub').text(schoolMatches[currentStep]);
}


/**
 * Displays the complete Profile Form in steps 4th page - email 5th page - phone
 */
function enableFormWizard(noOfSteps, errors)
{
    currentStep = 1;
    var getSchoolMatchesFromCookie = false;
    if (!noOfSteps)
    	alert("Specify the no. of steps in the Wizard.");

    if (errors['phoneError'] || errors['emailError'])
    {
    	jQuery("#step_"+currentStep).hide();

    	if (errors['phoneError'])
		{
		    currentStep = 6;
		    jQuery('#phone_one').parent().append("<span class='error-message'>Phone is missing valid data .</span>").parent().addClass('form-element-error');
		}
		if (errors['emailError'])
		{
		    currentStep = 6;
		    jQuery('#email').parent().append("<span class='error-message'>Email is missing valid data.</span>").parent().addClass('form-element-error');
		}

		jQuery("#step_"+currentStep).show();
		updateWizardProgress(noOfSteps, currentStep);
		getSchoolMatchesFromCookie = true;
    }

    updateSchoolMatches(currentStep, getSchoolMatchesFromCookie);

	jQuery('#'+noOfSteps).after("<div id='"+(noOfSteps+1)+"'></div>");

    jQuery("#next-button").click(function()
    {
	    var validationStatus = validateStep(currentStep);
	    if (validationStatus['flag'])
	    {
			// this condition becomes true when user clicks on Next button of the laststage
			if (currentStep == noOfSteps)
			{
			    // second parameter to submit the form when AJAX request completes
			    nextbtnAjax(currentStep, 1, noOfSteps);
			    jQuery("#step_"+currentStep).hide();
			    currentStep++;

			    // show ajax loader here
			    jQuery("#step_"+currentStep).show().html("<div style='text-align:center;padding-top:100px;'><img src='includes/media/images/ajax-loader-transparent.gif'/></div>");
			    jQuery('.form_progress').hide();
			    jQuery('.form_message').hide();
			    jQuery('.form_footer').hide();

			    updateSchoolMatches(currentStep);
			}
			else
			{
				// send the field data, of that section of the Wizard that the user has currently entered.
				nextbtnAjax(currentStep);
				
				jQuery("#step_"+currentStep).hide();
				currentStep++;
				jQuery("#step_"+currentStep).show();
	
				updateWizardProgress(noOfSteps,currentStep);
				updateSchoolMatches(currentStep);
			}
	    }
 	});

    jQuery(".back").click(function()
    {
	    if (currentStep == 1)
	    	return;

	    jQuery("#step_"+currentStep).hide();
		currentStep--;
		jQuery("#step_"+currentStep).show();

		updateWizardProgress(noOfSteps, currentStep);
		updateSchoolMatches(currentStep);
	});
}

function validateStep(step)
{
    var returns = {'flag':true, 'message':''};

    jQuery('#step_'+step+' .mandatory').each(function() { ValidateMandatoryField(this, returns); });
    jQuery('#step_'+step+' .email').each(function() { ValidateEmailField(this, returns); });
    jQuery('#step_'+step+' .zip').each(function() { ValidateZipField(this, returns); });
    jQuery('#step_'+step+' .dateOfBirth:first').each(function() { ValidateDateOfBirthField(this, returns); });
    jQuery('#step_'+step+' .varchar').each(function() { ValidateVarcharField(this, returns); });
	jQuery('#step_'+step+' input:text').each(function() { ValidateNoAmpersandField(this, returns); });

    return returns;
}

function ValidateMandatoryField(field, returns)
{
    var errorMsg;
    var val = jQuery.trim(jQuery(field).val());
    var label = jQuery(field).parent().prev().text();

    if (!val)
    {
		label = label.split('*');
		returns.message += label[0] + " is mandatory!\n";
		errorMsg = label[0] + " is mandatory.";
		var formElement = jQuery(field).parent().parent();
		formElement.find('.error-message').remove();
		jQuery(field).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
		returns.flag = false;
    }
    else
    {
    	jQuery(field).parent().parent().removeClass('form-element-error').find(".error-message").remove();
    }
}

function ValidateEmailField(field, returns)
{
	var errorMsg;
    var val = jQuery.trim(jQuery(field).val());
	if (!IsValidEmail(val))
	{
		returns.message += "Enter a valid email address!\n";
	    errorMsg = "Enter a valid E-mail address.";
	    var formElement = jQuery(field).parent().parent();
	    formElement.find('.error-message').remove();
	    jQuery(field).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
	    returns.flag = false;
	}
	else
	{
		jQuery(field).parent().parent().removeClass('form-element-error').find(".error-message").remove();
	}
}

function ValidateZipField(field, returns)
{
	var errorMsg;
	var val = jQuery.trim(jQuery(field).val());
	
	if (!isInteger(val,5))
	{
		returns.message += "Enter a valid 5 digit zip code!\n";
		errorMsg = "Enter a valid 5 digit zip code.";
		var formElement = jQuery(field).parent().parent();
		formElement.find('.error-message').remove();
		jQuery(field).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
		returns.flag = false;
	}
	else
	{
		if (val < 1)
		{
			var formElement = jQuery(field).parent().parent();
			formElement.find('.error-message').remove();
			jQuery(field).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
			jQuery('#step_'+step+' #zip').parent().append("<span class='error-message'>NULL values are not allowed.</span>").parent().addClass('form-element-error');
			returns.flag = false;
		}
		else
		{
			jQuery(field).parent().parent().removeClass('form-element-error').find(".error-message").remove();
		}
	}
}

function ValidateDateOfBirthField(field, returns)
{
	var graduateYear = jQuery('#GraduationYear option:selected').val();
	//we are assuming most users would graduate in June, since we only ask graduation year on the form
	var graduateMonth = "6";
	//set the day to the first of the month, we would pass these values to set the Date object in javascript
	var graduateDay = "1";

	//create a date object and set the date so graduation date can be compared with birth date.
	var graduation= new Date();
	graduation.setFullYear(graduateYear,graduateMonth-1,graduateDay);

	var birthYear = jQuery('#DateOfBirth_2 option:selected').val();
	var birthMonthAndDay = jQuery('#DateOfBirth_1 option:selected').val();
	var birthDay = "1";

	//since the value for the month on the form also sets the day we need to strip out just the month
	monthVal = birthMonthAndDay.indexOf("-");
	birthMonth = (birthMonthAndDay.substring(0,monthVal));

	//create a date object and set the date so date of birth can be compared with graduation date.
	var dateOfBirth = new Date();
	dateOfBirth.setFullYear(birthYear, birthMonth-1, birthDay);

	graduationAgeInMonths = calculateMonthDiff(graduation, dateOfBirth);

    //16*12 = 192, user has to be atleast 16 years old at date he / she received HS degree.
	if(graduationAgeInMonths < 192)
	{
		var gradAgeLessThan16 = "yes";
		jQuery('#GraduationYear').parent().parent().removeClass('form-element-error').find(".error-message").remove();
		jQuery('#DateOfBirth').parent().parent().removeClass('form-element-error').find(".error-message").remove();
		jQuery('#GraduationYear').parent().append("<span class='error-message'>Your High School graduation year does not match your Date of Birth.</span>").parent().addClass('form-element-error');
		jQuery('#DateOfBirth').parent().append("<span class='error-message'>Your Date of Birth does not match your High School graduation year.</span>").parent().addClass('form-element-error');
		returns.flag = false;
	}
	else
	{
		var gradAgeLessThan16 = "";
		jQuery('#GraduationYear').parent().parent().removeClass('form-element-error').find(".error-message").remove();
		jQuery('#DateOfBirth').parent().parent().removeClass('form-element-error').find(".error-message").remove();
	}

	currentDate = new Date();
	currentAgeInMonths = calculateMonthDiff(currentDate, dateOfBirth);

	//User has to be less than 16 years old to apply.
	if(currentAgeInMonths < 192)
	{
		//If there is no error on graduation date then only remove the error box.
		if (gradAgeLessThan16 != "yes")
		{
			jQuery('#DateOfBirth').parent().parent().removeClass('form-element-error').find(".error-message").remove();
		}
		jQuery('#DateOfBirth').parent().append("<span class='error-message'>You must be 16 or older to apply.</span>").parent().addClass('form-element-error');
		alert('You must be 16 or older to apply.')
		returns.flag = false;
	}
	else
	{
		//If there is no error on graduation date then only remove the error box.
		if (gradAgeLessThan16 != "yes")
		{
			jQuery('#DateOfBirth').parent().parent().removeClass('form-element-error').find(".error-message").remove();
		}

	}
}

function ValidateVarcharField(field, returns)
{
	var errorMsg;
	var val = jQuery.trim(jQuery(field).val());
	if (!isCharPunc(val))
	{
		returns.message += "Only Whitespaces &amp; alphabetic Chars are allowed!\n";
	    errorMsg = "Only Whitespaces &amp; alphabetic Chars are allowed.";
	    var formElement = jQuery(field).parent().parent();
	    formElement.find('.error-message').remove();
	    jQuery(field).parent().append("<span class='error-message'>"+errorMsg+"</span>").parent().addClass('form-element-error');
	    returns.flag = false;
	}
	else
	{
		jQuery(field).parent().parent().removeClass('form-element-error').find(".error-message").remove();
	}
}

function ValidateNoAmpersandField(field, returns)
{
	var ele = jQuery(field);
	var eleVal = jQuery.trim(ele.val());
    if (ele.parent().parent().hasClass('form-element-ampersand-error'))
    {
    	ele.parent().parent().removeClass('form-element-ampersand-error').find(".ampersand-error-message").remove();
    }
    if (eleVal)
    {
    	var filter = /[\&]/;
		var testFlag = filter.test(eleVal);
		if (testFlag)
		{
    		ele.parent().append("<span class='ampersand-error-message'>Ampersand(&) is not allowed.</span>").parent().addClass('form-element-ampersand-error');
    		returns.flag = false;
    	}
    }
}

/**
 * Calculated difference in Month for 2 dates.
 */
function calculateMonthDiff(beginningDate, endDate)
{

	//get the difference in years and multiply by 12
	var months = (beginningDate.getFullYear() - endDate.getFullYear()) * 12;

	//get the difference between months
    months += beginningDate.getMonth() - endDate.getMonth();

    return months;
}


/**
 * Opens the Versign website in a new browser window.
 */
function VeriOpen()
{
	window.open("https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=www.top-colleges.com&lang=en" , null, "height=450,width=525,status=no,toolbar=no,menubar=no,location=no,scrollbars=no");
}


function updateTotalSchoolCount()
{
    var count = $.cookie("total-school-count");
    jQuery('.schools-total').text(count);
}

function resizeFormSystemIframe(newHeight)
{
	document.getElementById('formSystemFrame').style.height = (parseInt(newHeight)+15)+'px';
}

