var phpLoc = "http://shipmpg.com/php/PHPRateQuote/";
var unloadEmailCust = function () {
	
	if (quote && emailGiven) {
		var postObject = {
			'type' : 'emailQuoteCust',
			'quoteId' : quote.quoteNumber,
			'userName' : $('#userName').text(),
			'userEmail' : userEmail
			}
		
		var postString = JSON.stringify(postObject);
		
		
		$.post(phpLoc + "emailCustQuote.php", "data=" + postString, function (data) {
			
			}, "text");
		
		
		}	
	}

function anonString () {
	var string = this.toString().split('\n');
	string = string.slice(1, string.length);
	string[string.length-1] = string[string.length-1].replace('}', '');
	string = string.join('\n');
	
	return string;
	}


Function.prototype.anonString = anonString;

$(document).ready( function () {

var phpLoc = "http://" + document.location.host + "/php/PHPRateQuote/";


//$('.formPanel').hide();
startQuote();




/////FirstPanel::: Date and Cargo

function setCurrentDate() {
	var curDate = new Date();
	$("input[name='month']").val(curDate.getMonth() + 1);
	$("input[name='day']").val(curDate.getDate());
	$("input[name='year']").val(curDate.getFullYear());
	}

setCurrentDate();

function setRemove() {
	
	$('.removeCargo').click( function () {
		if ( $(this).parent().parent().children().length > 1) {
			
			$(this).parent().remove();
			
			}
		$('.addCargo').show();	
			
			
		
		});
	}


$('.addCargo').click( function () {
	
	setRemove();
	$('.cargoItem:first').clone().appendTo('.cargoItems:first');
	setRemove();
	
	if ($('.cargoItems').children().length == 5) {
		$(this).hide();
		}
	});

//http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
////Second and Third Panels: from and to addresses and accessorials

$('.country').change( function () {
	
	zipBox = $(this).parent().children('.zipcode:first');
	errorbox = $(this).parent().children('.error:first');
	errorbox.attr('valid', 'false');
	zipBox.val('');
	
	if ($(this).val() == 'US') {
		zipBox.attr('maxlength', 5);
		}
	if ($(this).val() == 'CA') {
		zipBox.attr('maxlength', 7);
		}
	});

$('.zipcode').keyup( function () {
	country = $(this).parent().children('.country:first').val();
	if (country == 'US') {
		activeLength = 5;
		}
	if (country == 'CA') {
		activeLength = 6;
		}
	errorbox = $(this).parent().children('.error:first');
	ziptype = $(this).attr('name');
	var zipcode = $(this).val();
	zipcode = zipcode.replace(' ', '');
	
	if (zipcode.length >= activeLength) {
		
		activeNext = $(this).parents('.formPanel').children('.nextButton');
		activeNext.hide();
		errorbox = $(this).parent().children('.error:first');
		ziptype = $(this).attr('name');
		errorbox.text('Validating Zipcode...');
	
		if (zipcode == ''){
			$(errorbox).attr('valid', 'false');
			$(errorbox).text('Not a valid zipcode');
			} else {
			$.post(phpLoc + "lib/forms.php", "zipcode=" + zipcode + "&country=" + country, function(data) {
				
				if (!data.success) { 
					
					$(errorbox).attr('valid', 'false');
					$(errorbox).text('Invalid Zipcode');
					} else {
					if (ziptype == 'to-zip') {
						parameters['to-country'] = country;
						parameters['to-zip'] = data.zipcode;
						parameters['to-city'] = data.city;
						parameters['to-state'] = data.state_code;
						}
					if (ziptype == 'from-zip') {
						parameters['from-country'] = country;
						parameters['from-zip'] = data.zipcode;
						parameters['from-city'] = data.city;
						parameters['from-state'] = data.state_code;
						
						}
					
					$(errorbox).attr('valid', 'true');
					$(errorbox).text('[' + data.city + ', ' + data.state_code + ']');
					activeNext.show();
					}
				
								
				}, 'json');
			
				}
			}		
		}); 
		

errorArray = new Array();


$(".nextButton").click(function () {
	var errorArray = [];
	
	$(this).parents(".formPanel").children('form').children().each( function () {
		
		errorArray.push(errorCheck(this));	
		
		
		});
	
	var errors = errorArray.join(',').lastIndexOf('true');
	
	if (errors == -1) { 
		$(this).parents('.formPanel').hide();
		$(this).parents('.formPanel').next().show();	
		
		if ($(this).attr('id') == 'submitButton') {
			submitHTTP();
			}
		if ($(this).attr('id') == 'emailResults') {
			emailResults();
			}
		
		if ($(this).attr('id') == 'emailUnbooked') {
			emailGiven = true;
			userEmail = $('*[name="cust-email"]').val();
			emailUnbooked();	
			}
		
		if ($(this).attr('id') == 'bookFastest') {
			cust_parameters['cust-selectedQuote'] = 'fastestResult';
			
			}
		if ($(this).attr('id') == 'bookCheapest') {
			cust_parameters['cust-selectedQuote'] = 'cheapestResult';
			
			}
		if ($(this).attr('id') == 'bookBest') {
			cust_parameters['cust-selectedQuote'] = 'bestResult';
			}
		
		}
	
	});

$(".backButton").click(function () {
	
	$(this).parents('.formPanel').hide();
	$(this).parents('.formPanel').prev().show();
		
		
	
	
	
	
	});



$('.restartQuote').click( function () {
	startQuote();
	
	});


function errorCheck(input){
	var error = false;
	var type = $(input).attr('class');	
	
	if (type == 'date') {
		var curDate = new Date();
		var verDate = new Date();
		
		var year = $(input).find("input[name='year']").val();
		var month = parseInt($(input).find("input[name='month']").val()) - 1;
		var day = $(input).find("input[name='day']").val();
		
		
		if (month < 0 || month > 11) {
			month = Number.NaN;
			}
		if (day < 1 || day > 31) {
			day = Number.NaN;
			}
		verDate.setFullYear(year, month, day);
		
				
		if (isNaN(verDate.getFullYear()) || verDate < curDate) {
			error = "Not a valid shipping date";
			}		
		}	
	
	if (type == 'cargo') {
		$(input).find('.cargoItems').find('.cargoItem').each( function () {
			var weight = $(this).find("input[name='weight']").val();
			var Class  = $(this).children('select').val();
			
			
			if (isNaN(weight) || weight < 1 || weight > 9999) {
				error = 'Invalid Cargo Weight or Class';
				$(this).find("input[name='weight']").css('background-color','red');
				
				} else {
				$(this).find("input[name='weight']").css('background-color','white');			
				}
			
			if (Class == '') {
				error = 'Invalid Cargo Weight or Class';
				}
			
			
			});
			
		
		}
	
	if (type == 'address-zipcode') {
		var zipcode = $(input).find(".zipcode:first").val();
		var valzip = $(input).find(".error:first").attr('valid');
		
		if (zipcode.length < 5 || valzip != 'true') {
			error = 'Not a valid zipcode';
			
			} else {
				
				}
		}
	
	if (type == 'cust-address') {
		
		$(input).find(".cust-addr-input").each( function () {
			
			var value = $(this).val();
			
			if (value == '') {
				error = 'One or more fields are blank';
				
				}
			
			});
		
		
		}
	if (type == 'cust-info') {
		
		$(input).find(".cust-info-input").each( function () {
			
			var type = $(this).attr('name');
			var value = $(this).val();
				
			if (value == '') {
				error = 'One or more fields are blank';
				
				}
			
			if (type == 'cust-email') {
							
				var emailRegex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
				if (!value.match(emailRegex)) {
					error = 'Not a valid email address';					
					}
								
				}
			
			
			});
		}
	
	
	
	if (error) {
		$(input).find('.error').text(error);
		return "true";
		} else { 
		$(input).find('.error').empty();
		return "false";
		}
	
	}

////Gather Varables and Submit

var parameters = {
		  'from-country' : '',
		  'from-zip' : '',
		  'from-city': '',
		  'from-state': '',
		  'to-country' : '',
		  'to-zip' : '',		  
		  'to-city' : '',
		  'to-state' : '',
		  'ship-date': ''
		}



function submitHTTP() {

	var accessorials = new Array();
	$('.accessorials > input').each( function () {
		
		if ($(this).attr('checked')) {
			accessorials.push($(this).attr('name'));
			
			}
			
		});
	
	
			

	var shipdate = Array();
	
	shipdate.push($("input[name='month']").val());
	shipdate.push($("input[name='day']").val());
	shipdate.push($("input[name='year']").val().substring(2,4));
	shipdate = shipdate.join('/');
	
	parameters['ship-date'] = shipdate;
	
	
	
		
	var cargo = new Array();
	function cargoItemClass(weight, Class){
		this.weight = weight;
		this.Class = Class;
		  }
	
	$('.cargoItem').each( function () {
		
		var weight = $(this).children("input[name='weight']").val();
		var Class = $(this).children("select").val();
		
		var cargoItem = new cargoItemClass(weight, Class);
		cargo.push(cargoItem);
		
		
		});	
	
	var userName = $('#userName').text();
	
	if (!userName) {
		var userName = null;
		} else {
		var userName = userName;
		}
	
	parameters['cargo-type'] = 'ltl';
	
	var postData = { 
			 'userName'     : userName,
			 'accessorials' : accessorials,
			 'parameters'   : parameters,
			 'cargo'	: cargo
			 }
	
	postData = JSON.stringify(postData);
	

	$('.quoteResult').hide();
	$('#emailResults').hide();
	$('.quoteLoading').show();
	
	$.post(phpLoc + "getRateQuotes.php", "data=" + postData , function (data) {
		quote = data;
		
		$('.result * tr').hide();
		$('.abortBook').show();
		if (data.error == false) {
			
			$('.resultHeader').show();
			
			if (data.bestResult) {
				$('.bestResult').show();
				$('.bestResultPrice').text("$" + data.bestResult.userPrice);
				$('.bestResultTime').text(data.bestResult.time);
				
				} else {
				
				$('.cheapestResult').show();
				$('.cheapestResultPrice').text("$" + data.cheapestResult.userPrice);
				$('.cheapestResultTime').text(data.cheapestResult.time);
				$('.fastestResult').show();
				$('.fastestResultPrice').text("$" + data.fastestResult.userPrice);
				$('.fastestResultTime').text(data.fastestResult.time);
				
				}
			
			
			} else {
			$('.quoteError').show();
			
			}
		
		
		$('.quoteLoading').hide();
		$('.quoteResult').show();
		$('#emailResults').show();
		resultsGiven = true;
		emailUnbooked();
		
		}, 'json');
	
	
	}


var cust_parameters = {		  
		  
		  
		  'cust-from-name'   : '',
		  'cust-from-street' : '',
		  'cust-from-street2': '',
		  'cust-from-city'   : '',
		  'cust-from-state'  : '',
		  'cust-from-phone'  : '',
		 
		  'cust-to-name'   : '',
		  'cust-to-street' : '',
		  'cust-to-street2' : '',
		  'cust-to-city'   : '',
		  'cust-to-state'  : '',
		  'cust-to-phone'  : '',
		 
		  		  
		  'cust-firstname'   : '',
		  'cust-lastname'    : '',
		  'cust-email'       : '',
		  'cust-phone'       : '',
		  'cust-selectedQuote': 'none'
		  }



function emailResults() {
	for (key in cust_parameters) {
		if ($("input[name='" + key + "']").val()) {
			cust_parameters[key] = $("input[name='" + key + "']").val();
			}
		}
	
	cust_parameters['cust-from-state'] = $("select[name='cust-from-state'] > option:selected:first").val();
	cust_parameters['cust-to-state'] = $("select[name='cust-to-state'] > option:selected:first").val();
	//cust_parameters['cust-selectedQuote'] = $(".selectedQuote:checked").attr('id');
	
	var postData = {'quoteNumber' : quote.quoteNumber,
			'cust_parameters' : cust_parameters,
			'quote' : quote
			}
	
	

	postData = JSON.stringify(postData);
	$.post(phpLoc + 'emailRateQuote.php', "data=" + postData, function (data) {
		
		
		
		}, 'text');
	
	}

function emailUnbooked() {
	if (resultsGiven && emailGiven) {
		emailResults();
		}
	}


function startQuote() {
	$('.country').val('US');
	
	$('.formPanel').hide();
	$('#ltlFormPanel1').show();
	$('#ltlFormPanel1').show();
	$('input').val('');
	$("input[name='weight']").val('');
	$(".cust-addr-input").val('1');
	$(".cust-info-input").val('');
	emailGiven = false;
	resultsGiven = false;
	
		}

});
