/*
*	Compares zip code with database to validate
*/
function validateZip(zip, id)
{
	var x, timestamp = Math.round(new Date().getTime() / 1000);
	
	if (window.XMLHttpRequest)
  	{
  		x = new XMLHttpRequest();
  	}
	else
  	{
  		x = new ActiveXObject("Microsoft.XMLHTTP");
  	}

	x.onreadystatechange = function()
  	{
		$('#ajax').attr('data-running', 'true');

  		if (x.readyState == 4 && x.status == 200)
    	{
    		if (x.responseText == true)
    		{
    			$('#' + id).attr('data-valid', 'true');
    		}
    		else
    		{
    			$('#' + id).attr('data-valid', 'false');
    		}

    		$('#ajax').attr('data-running', 'false');
    	}
  	}
	
	x.open("GET","includes/ajax/validate-zip.php?zip=" + zip + '&t=' + timestamp, true);
	x.send();
}


/*
*	Grabs top populated cities for state user selects
*/
function getCitiesFromState(state, select)
{
	if (window.XMLHttpRequest)
	{
		x = new XMLHttpRequest();
	}
	else
	{
		x = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	var ran = Math.round((new Date()).getTime() / 1000),
	terms = "state="+state+'&r='+ran, loader, id;
	
	x.open("POST", "includes/ajax/cities-from-state.php", true);
	x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

	select === 'fzip-state'
	? loader = 'fzip-loader'
	: loader = 'tzip-loader';
	
	$('#'+loader).show();
	$('#ajax').attr('data-running', 'true');

	x.onreadystatechange = function()
	{
		if (x.readyState==4 && x.status==200)
		{
			select === 'fzip-state'
			? id = 'fzip-city'
			: id = 'tzip-city';

			$('#' + id).html(x.responseText);

			$('#'+loader).hide();
			$('#ajax').attr('data-running', 'false');
		}
	}

	x.send(terms);
}

/*
*	Care of the nice chaps down at php.js
*/
function strpos (haystack, needle, offset) {
    // Finds position of first occurrence of a string within another  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/strpos
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}


/*
*	Replication of PHP's in_array() function
*/
function inArray(needle, haystack)
{
    var length = haystack.length;
    
    for (var i = 0; i < length; i++)
    {
        if(haystack[i] == needle) return true;
    }

    return false;
}


/*
*	Restricts user to only number characters in appropriate fields
*/
function returnNum(e)
{
	var key = (e.charCode) ? e.charCode : e.keyCode;

	if (!(key > 47 && key < 58))
	{
		e.preventDefault();
		return false;
	}
}


/*
*	Restricts user to only alpha characters
*/
function returnAlpha(e)
{	
	var key = (e.charCode) ? e.charCode : e.keyCode;

	var blacklist = [96, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 92, 93, 91, 39, 59, 47, 46, 44]

	if (inArray(key, blacklist))
	{
		e.preventDefault();
		return false;
	}	
}


/*
*	Restricts space bar usage
*/
function returnAllButSpace(e)
{
	var key = (e.charCode) ? e.charCode : e.keyCode;

	if (key == 32)
	{
		e.preventDefault();
		return false;
	}
}


/*
*	Main Validation Logic
*/
function validate()
{
	var invalidEls = [];

	validateZip($('#fzip').val(), 'fzip');
	validateZip($('#tzip').val(), 'tzip');

	$('#date').val() === '' || $('#date').val().length !== 10
	? invalidEls.push('Date:invalid')
	: invalidEls.push('Date:valid');

	$('#fzip').attr('data-valid') !== 'true'
	? invalidEls.push('Pickup Zip:invalid')
	: invalidEls.push('Pickup Zip:valid');

	$('#tzip').attr('data-valid') !== 'true'
	? invalidEls.push('Delivery Zip:invalid')
	: invalidEls.push('Delivery Zip:valid');

	/^\S/.test($('#name').val()) !== true
	? invalidEls.push('Name:invalid')
	: invalidEls.push('Name:valid');

	$('#email').val().match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9]){1,}?/)
	? invalidEls.push('Email:valid')
	: invalidEls.push('Email:invalid');

	$('#phone').val().match(/^(1-?)?([2-9]\d{2}|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)
	? invalidEls.push('Phone:valid')
	: invalidEls.push('Phone:invalid');

	return invalidEls;
}


/*
*	Shows/Hides Error Display Div
*/
function showErrors(errors)
{	
	var winH           = $(window).height();
	var winW           = $(window).width();
	var output         = '';
	var elsToHighlight = [];

	var i = 1;
	for (x = 0; x <= (errors.length - 1); x++)
	{
		if (strpos(errors[x], 'invalid') !== false)
		{
			if (strpos(errors[x], 'Date') !== false) {elsToHighlight.push('date');}
			else if (strpos(errors[x], 'Pickup Zip') !== false) {elsToHighlight.push('fzip');}
			else if (strpos(errors[x], 'Delivery Zip') !== false) {elsToHighlight.push('tzip');}
			else if (strpos(errors[x], 'Name') !== false) {elsToHighlight.push('name');}
			else if (strpos(errors[x], 'Email') !== false) {elsToHighlight.push('email');}
			else if (strpos(errors[x], 'Phone') !== false) {elsToHighlight.push('phone');}

			output += i + ') <span class="errors_g">' + errors[x] + "</span><br />\n";
			i++;
		}
	}

	$('#errors-content').html(output);

    $('#errors').css('top',  winH/2-$('#errors').height()/2);
    $('#errors').css('left', winW/2-$('#errors').width()/2);
 
    $('#errors').fadeIn(500);

    for (x = 0; x <= (elsToHighlight.length - 1); x++)
    {
    	highlight(elsToHighlight[x]);
    }


    colorDaemon = window.setTimeout(function() {backToWhite()}, 3000);
}

function highlight(el)
{
	var _el = '#' + el;

	$('#' + el).css('background', '#e94253');
}
 
function backToWhite()
{
	$('input:not(#submit, #fzip-close, #tzip-close, #errors-close)').each(function()
	{
		$(this).animate({ backgroundColor: "#fff" }, 1000);
	});
}


/*
*	-= Doc Ready Routines =-
*
*	Note: $(function()){}); is identical to $(document).ready(function(){}); 
*
*	see http://rpheath.com/posts/403-jquery-shorthand-for-document-ready for further clarification.
*/
$(function()
{
	$('#submit').hover(
		function()
		{
			$(this).removeClass('button').addClass('button_hover');
		},
		function()
		{
			$(this).removeClass('button_hover').addClass('button');	
		}
	);

	// User Key Restricts
	$('#date').keypress(function(){return false;});
	$('#fzip, #tzip, #phone').keypress(function(e){return returnNum(e);});
	$('#name').keypress(function(e){return returnAlpha(e);});
	$('#email').keypress(function(e){return returnAllButSpace(e);});

	// Zip Lookup Div Show/Hide Logic
	$('#fzip-trigger, #tzip-trigger').click(function()
	{
		var ids = [];
		
		$(this).attr('id') === 'fzip-trigger'
		? ids = ['fzip-lookup', 'tzip-lookup']
		: ids = ['tzip-lookup', 'fzip-lookup'];

		$('#' + ids[0]).show(150);
		$('#' + ids[1]).hide(50);
	});

	$('#fzip-close, #tzip-close').click(function()
	{
		var id;

		$(this).attr('id') === 'fzip-close'
		? id = 'fzip-lookup'
		: id = 'tzip-lookup';

		$('#' + id).hide(150);
	});

	$('#errors-close').click(function(){$('#errors').fadeOut(200);});

	// Event Driven Validation
	$('#date').datepicker({
		minDate: '+1',
		onSelect: function()
		{
			$('#date').attr('data-valid', 'true');
		}
	});

	$('#fzip, #tzip').keyup(function()
	{
		validateZip($(this).val(), $(this).attr('id'));
	});

	$('#fzip-state, #tzip-state').change(function()
	{
		$(this).attr('id') === 'fzip-state' ? id = 'fzip' : id = 'tzip';
		$('#' + id).attr('data-valid', 'false');

		getCitiesFromState($(this).val(), $(this).attr('id'));
	});

	$('#fzip-city, #tzip-city').change(function()
	{
		var ids = [];

		$(this).attr('id') === 'fzip-city'
		? ids = ['fzip', 'fzip-lookup'] 
		: ids = ['tzip', 'tzip-lookup'];

		$('#' + ids[0]).val($(this).val()).attr('data-valid', 'true');
		$('#' + ids[1]).hide(100);
	});

	$('#lead-form').submit(function(e)
	{
		var x = 0;

		yourneck:
		while (x < 1)
		{
			// if ($('#ajax').attr('data-running') === 'true')
			// {
			// 	e.preventDefault();
			// 	alert('One moment your data is still validating');
			// 	break yourneck;
			// }

			invalidEls = validate();

			var i = 0;
			for (x = 0; x <= (invalidEls.length -1); x++)
			{
				if (strpos(invalidEls[x], 'invalid') !== false)
				{
					i++;	
				}
			}

			if (i > 0)
			{
				e.preventDefault();
				showErrors(invalidEls)
			}
			else
			{
				$('#lead-form').submit();
			}
			x++
		}
	});
});
