var zipcode = '';
var chapcode = '';

function setGlobalVariables() {
	zipcode=readCookie("zipcode");
	chapcode=readCookie("chapcode");
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setCookie(name, value, duration) {
  var cookieValue= name + "=" + escape(value);
  var date = new Date();
  date.setDate(date.getDate() + duration);
  document.cookie = (cookieValue + "; expires=" + date.toUTCString()); 
}

function trim(str) {
	return str.replace(/^\s+/g,'').replace(/\s+$/g,'');
}



function searchForChapter() {
	zipcode=trim(zipcode);
	$.get('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getChapterCode&value='+zipcode, function(data) {
		chapcode=trim(data);
		if (chapcode.length==5) {
			setCookie('chapcode',chapcode,1);
			setCookie('zipcode',zipcode,3650);
			$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIChapterInfo&value='+chapcode);
		} else {
			$('#userZip').val('');
			$('#zipLocatorMessage').html('<span style="color: FF0000;">Could not locate Chapter</span>');
		}
	});
}

function doZipSearch() {
	var enteredZip = $('#userZip').val();
	if (enteredZip.length == 5&&parseInt(enteredZip)==enteredZip) {
		zipcode=enteredZip;
		searchForChapter();
		$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIChapterInfo&value='+chapcode);
	} else {
		$('#userZip').val('');
		$('#zipLocatorMessage').html('<span style="color: FF0000;">The Zipcode you entered was invalid</span>');
		
	}
}

function changeZip() {
	chapcode='';
	zipcode='';
	setCookie('chapcode','',-1);
	setCookie('zipcode','',-1);
	$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIForm');
}

$(document).ready(function() {
	setGlobalVariables();
	if (chapcode!=null&&chapcode!='') {
		$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIChapterInfo&value='+chapcode);
	} else {
		if (zipcode!=null&&zipcode!='') {
			searchForChapter();
			$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIChapterInfo&value='+chapcode);
		 } else {
			$('li.find_tool').load('/vgn-ext-templating/jsp/mi/LocalContentProcessor.jsp?action=getMIForm');
		 }
	}
		
});
