$(document).ajaxError(function () {
    alert("We were unable to process your request. Please try again.");
});

$.urlParam = (function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
});

function isValidZip(zip) {
	var re = /^\d{5}$/;
	return (re.test(zip));
}

function showLongForm(fadeForm) {
	$("#userZip").attr("readOnly", true);
	$("#userZip").css("background-color","white");
	$("#userZip").css("font-style","italic");
	$("#otherInfo").hide();
	if (fadeForm) {
		$("#zipCodeSubmit").fadeOut("fast");
		$("#longForm").fadeIn("slow");
		$(".longform").fadeIn("slow");
	} else {
		$("#zipCodeSubmit").hide();
		$("#longForm").show();
		$(".longform").show();
	}
}

function fillForm() {
	showLongForm(false);
	$("#userZip").val($.urlParam("zipcode"));
	$("#zipcode").val($.urlParam("zipcode"));
	$("#startdate").val($.urlParam("startdate"));
	$("#enddate").val($.urlParam("enddate"));
	$("#latitude").val($.urlParam("latitude"));
	$("#longitude").val($.urlParam("longitude"));
	$("#radius").val($.urlParam("radius"));
	$("#userRadius").val($.urlParam("radius"));
	$("#category").val($.urlParam("category"));
	$("#delivery").val($.urlParam("delivery"));
}

function checkForm() {
	if ($("#category").val().length == 0) {
		alert("Please select a Course Category.");
		return false;
	}
    if ($("#startdate").val().length != 10) {
        alert("Please select a Start Date.");
        return false;
    }
    if ($("#enddate").val().length != 10) {
        alert("Please select an End Date.");
        return false;
    }
    var d1 = new Date($("#startdate").val());
    var d2 = new Date($("#enddate").val());
    if (d2 < d1) {
        alert("You cannot choose an End Date which precedes the Start Date.");
        return false;
    }
	$("#radius").val($("#userRadius").val());

	// 02/16/11 - Concatenate form values to form Saba URL
	var baseURL = "https://classes.redcross.org/Saba/Web/Main/goto/"; 
	var fullURL = baseURL + "showMap?zipcode=" + $("#userZip").val() + "&category=" + $("#category").val() + "&startDate=" + $("#txtStartDate").val() + "&endDate=" + $("#txtEndDate").val();
	fullURL = fullURL + "&radi=" + $("#userRadius").val() + "&language=" + $("#language").val() + "&delivery=" + $("#delivery").val();

	window.open(fullURL);

	return false;
}

function displayJSONData(jsonResponse) {
    if (jsonResponse == undefined || jsonResponse == null) {
        alert("We were unable to process your request. Please try again.");
        return;
    }
    if (jsonResponse.inLMS) {
        var geo = jsonResponse.geocodeValues;
        showLongForm(true);
		$("#zipcode").val(geo.zipCode);
		$("#latitude").val(geo.latitude + '');
		$("#longitude").val(geo.longitude + '');
    } else {
        var chapter = jsonResponse.chapterInfo;
        if (chapter != undefined) {
        	var chapterAddress='<p>Your local chapter does not offer online course registration at this time. Please contact the chapter directly to register.</p>';
            chapterAddress += '<p><strong>' + chapter.entityName + '</strong><br />';
            chapterAddress += chapter.addressStreet + '<br />';
            chapterAddress += chapter.addressCity + ', ' + chapter.addressState + ' ' + chapter.zipCode + '<br />';
			if (chapter.addressPhone!=null && chapter.addressPhone.length > 0) {
                chapterAddress += 'Phone: ' + chapter.addressPhone + '<br />';
            }
            if (chapter.addressFax!=null && chapter.addressFax.length > 0) {
                chapterAddress += 'Fax: ' + chapter.addressFax + '<br />';
            }
            if (chapter.emailIsURL == 'Y') {
                chapterAddress += '<a href="' + chapter.addressEmail + '">Email the Chapter</a><br />';
            } else {
            	if (chapter.addressEmail!=null && chapter.addressEmail.length>0) {
					chapterAddress += '<a href="/portal/site/en/template.MAXIMIZE/ziplocator/?javax.portlet.tpst=2bd907ea326f7e9e934afa36c23f78a0_ws_MX&javax.portlet.prp_2bd907ea326f7e9e934afa36c23f78a0_viewID=email_view&javax.portlet.begCacheTok=com.vignette.cachetoken&javax.portlet.endCacheTok=com.vignette.cachetoken&maximize=false&vgnextoid=6d65e821cbdf9110VgnVCM1000002bf3870aRCRD&chapcode=' + jsonResponse.geocodeValues.entityID + '&zip=' + jsonResponse.geocodeValues.zipCode + '">Email the chapter</a><br />';
                }
            }
            if (chapter.websiteActive!=null && chapter.websiteActive == 'Y') {
                chapterAddress += '<a href="' + chapter.addressURL + '">Visit their Website</a>';
            }
            $("#sorryp").append($("<div id='sorryMessage'><br/>"+chapterAddress+"</p></div>").fadeIn("slow"));
        } else {
            alert("We're sorry, but this zip code was not found.  Please check the zip code and try again.");
        }
    }
}

$(document).ready(function () {
	$("#btnSubmit").attr('disabled', '');
    if ($.urlParam('fillForm') != 0) {
		fillForm();
	} else if (($.cookie('zipcode') != undefined) && ($.cookie('zipcode').length > 0)) {
        $("#userZip").val($.cookie("zipcode"));
        $("#zipcode").val($.cookie("zipcode"));
    }

    $(function () {
	    $("#startdate").datepicker({
			altField: '#txtStartDate',
	        altFormat: 'yy-mm-dd',
	        showAnim: 'fadeIn',
	        showSpeed: 1000
	    });
	    $("#enddate").datepicker({
	        defaultDate: +30,
			altField: '#txtEndDate',
			altFormat: 'yy-mm-dd',
	        showAnim: 'fadeIn',
	        showSpeed: 1000
	    });
	});

	$("#zipForm").submit(function(event){
		 var zipCodeField=$("#userZip");
		 if (zipCodeField.length && isValidZip(zipCodeField.val()))  {
		 	if($("#sorryMessage").length) {
		 		 $("#sorryMessage").fadeOut("fast",function() {
				 	 $("#sorryMessage").remove();
		 		 });
		 	}
			var zipCheckURL = "/apps/ChapterInLMS/";
			if (window.location.host.search("redcross.org") < 0) {
				zipCheckURL = "http://" + window.location.host + zipCheckURL;
			}
			$.getJSON(zipCheckURL, { zip: zipCodeField.val() }, displayJSONData);
		 } else {
			alert("Please enter a valid zip code.");
		}
		event.preventDefault();
	});
});

