jQuery(function() {

	// Dynamic Zipcode replacement for (external) content link (i.e. ecommerce)
	jQuery("a").each(function() {
		// zipcode is defined in internet-head.ftl
		if (this.href.indexOf("$zipcode$") > 0)
			this.href = this.href.replace("$zipcode$", zipcode);
	});

	// Initialize search form submit.
	jQuery('a#submitSearch').click(function() {
		jQuery('#searchForm').submit();
	});

	/*** Sign In box ***/

	jQuery('#signIn').show();

	// Initialize "sign in" open.
	jQuery('#signInOpen').click(function() {
		if (jQuery('#signIn').css('visibility') == 'visible') {
			jQuery('#signIn').css('visibility','hidden');
			jQuery('#signIn').css('z-index','-1');
			jQuery('#header').append(jQuery('#signIn'));
		} else {
			jQuery('#signIn').css('visibility','visible');
			jQuery('#signIn').css('z-index','100');
			jQuery('body').append(jQuery('#signIn'));
		}
	})

	// Initialize "sign in" close button.
	jQuery('#signInClose').click(function() {
		jQuery('#signIn').css('visibility','hidden');
		jQuery('#signIn').css('z-index','-1');
		jQuery('#header').append(jQuery('#signIn'));
	});

	// Close the sign in box if it's open and you click outside it
	jQuery(document.body).click(function(event){
	    var target = jQuery(event.target);
	    if ( !target.is("#signInOpen") && !target.is("#signIn") && !target.is("#signIn *") && jQuery('#signIn').css('visibility') == 'visible' ) {
	    	jQuery('#signIn').css('visibility','hidden');
	    }
	});

	/*** Zip Code Box ***/

	// Initialize zip code open.
	jQuery('#zipCodeOpen').click(function() {
		jQuery('#zipCodeText').val("");
		jQuery('#invalidZipCodeFormat').hide();
		jQuery('#zipCode').show();
		jQuery('#zipCodeText').focus();
	})

	// Initialize zip code close arrow (for initial zip code overlay).
	jQuery('#zipCode .arrowUp').click(function() {
		jQuery('#zipCode').hide();
	});

	// Initialize zip code close arrow (for "invalid zip code" box).
	jQuery('#zipCodeInvalid .arrowUp').click(function() {
		jQuery('#zipCodeInvalid').hide();
	});

	// Initialize zip code close button (for "invalid zip code" box).
	jQuery('#zipCodeInvalidClose').click(function() {
		jQuery('#zipCodeInvalid').hide();
	});

	// Override form submit
	jQuery('#zipCodeForm').submit(function() {
		jQuery('#zipCodeFormSubmit').trigger("click");
		return false;
	});

	// form submit
	jQuery('#zipCodeFormSubmit').click(function() {

		// validate zip code
		var zipCodeEntry = jQuery('#zipCodeText').val();
		var zipExp = /^\d{5}([\-]\d{4})?$/;

		// if this is not a proper 5-digit or 9-digit zip code...
		if (zipCodeEntry.search(zipExp) == -1) {
			jQuery('#invalidZipCodeFormat').show();
		} else {

			jQuery.ajax({
				type: 'POST',
				url: contextPath + '/ajax/zipredirect',
		        dataType : 'json',
				data: jQuery('#zipCodeForm').serialize(),

				error: function(XMLHttpRequest, textStatus, errorThrown) {
					// TODO: handle errors.
				},
				success: function(data) {

					var queryString = window.location.search.replace(/zipcode=\d{0,5}/,'');

					switch(data.type) {
						case "unknown":
							jQuery('#zipCode').hide();
							jQuery('#zipCodeInvalid').show();

							jQuery('#zipCodeClose').click(function() {
								jQuery('#invalidZipCodeMessage').hide();
								jQuery('#zipCodeFormContainer').show();
							});

							if (window.location.pathname.indexOf("-zip-code.html") > 0) {
								jQuery('#zipCodeInvalidClose').attr("href", contextPath + "/allied-internet.html");
							}
							else {
								jQuery('#zipCodeInvalidClose').attr("href",
									window.location.protocol + "//" + window.location.host + window.location.pathname + queryString);
							}
							break;

						case "migratedZipCodes":
							// Send to home page if they are on on of the zip code pages, otherwise stay on same page
							if (window.location.pathname.indexOf("-zip-code.html") > 0) {
								window.location = contextPath + "/allied-internet.html";
							}
							else {
								window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + queryString;
							}
							break;

						default:
							if (data.redirect == undefined) {
								data.redirect = false;
							}
							window.location = contextPath + '/allied-internet/unauthorized-zip-code.html?zipcode=' + data.zipcode + '&redirect=' + data.redirect + '&url=' + encodeURIComponent(data.url);
							break;
					}
				}
			});

		}
	});

	// Close the zip code box if it's open and you click outside it
	jQuery(document.body).click(function(event){
	    var target = jQuery(event.target);
	    if ( !target.is("#zipCodeOpen") && !target.is("#zipCode")  && !target.is("#zipCode *") ) {
	    	jQuery('#zipCode').hide();
	    }
	});

	// Close the second zip code box if it's open and you click outside it
	jQuery(document.body).click(function(event){
	    var target = jQuery(event.target);
	    if ( !target.is("#zipCodeInvalid") && !target.is("#zipCodeInvalid *") ) {
	    	jQuery('#zipCodeInvalid').hide();
	    }
	});

	/*** Login Form (for both "My Account" and "Sign In" boxes) ***/

	// Login Form: if user hits "username" field...
	jQuery('.loginForm .inputUsername').click(function() {
		// clear out the input field
		if (jQuery(this).val() == 'username') {
			jQuery(this).val('');
		}
		// if the password field is blank, switch it out with the text field with the "password" text filled in
		if (jQuery(this).siblings('.inputPassword').val() == '') {
			jQuery(this).siblings('.inputPassword').hide();
			jQuery(this).siblings('.inputPasswordInitial').show();
		}

		return false;
	});

	// Login Form: if username loses focus while blank, add username
	jQuery('.loginForm .inputUsername').focusout(function() {
		// on lose focus if username field blank, input username
		if (jQuery(this).val() == '') {
			jQuery(this).val('username');
		}

		return false;
	});


	// Login Form: if user hits initial "password" text field...
	jQuery('.loginForm .inputPasswordInitial').focus(function() {
		// clear out the input field (or, more accurately, replace this text field with a password field)
		jQuery(this).hide();
		jQuery(this).siblings('.inputPassword').show();
		jQuery(this).siblings('.inputPassword').focus();
		// if the username field is blank, fill it with the "username" text filled in
		if (jQuery(this).siblings('.inputUsername').val() == '') {
			jQuery(this).siblings('.inputUsername').val('username');
		}

		return false;
	});

	//Login Form: if password field loses focus and is blank, add password.
	jQuery('.loginForm .inputPassword').focusout(function() {
		// if the password field loses focus and is blank, switch it out with the text field with the "password" text filled in
		if (jQuery(this).val() == '') {
			jQuery(this).hide();
			jQuery(this).siblings('.inputPasswordInitial').show();
		}
		return false;
		});

	// Login Form: if user hits "password" password field...
	jQuery('.loginForm .inputPassword').click(function() {
		// if the username field is blank, fill it with the "username" text filled in
		if (jQuery('.loginForm .inputUsername').val() == '') {
			jQuery('.loginForm .inputUsername').val('username');
		}
		return false;
	});

	//open store locator links in custom-sized window
	jQuery('.innerPopup').each(function(){
		var url = "";
		var width = 800;
		var height = 600;
		var minWidth = 400;
		var minHeight = 300;

		if (jQuery(this).attr('target') != null){
			jQuery(this).removeAttr('target');
		}
		if (jQuery(this).attr('href') != null){
			url = jQuery(this).attr('href');
			jQuery(this).removeAttr('href');
		}
		jQuery(this).click(function(){
			width = jQuery(window).width() - 200;
			width = Math.max(minWidth, width);

			height = jQuery(window).height() - 200;
			height = Math.max(minHeight, height);

			openNewWindow(url, width, height, "location=1, menubar=1, status=1, toolbar=1, titlebar=1, scrollbars=1");
		});
	});



});


function setHiddenField(selId, hidId)
{
    var selObj = document.getElementById(selId);
    var hidObj = document.getElementById(hidId);

    hidObj.value = selObj.value;
    return true;
}

function checkLoginForm(form) {
	// set variable to blank
	var loginErrorMessage = "";
	// if username is missing.....
	if (form.pwd.value.length != 0 && (form.id.value.length == 0 || form.id.value == "username")) {
		loginErrorMessage = "Please enter username";
	}
	// if password is missing...
	if (form.pwd.value.length == 0 && !(form.id.value.length == 0 || form.id.value == "username")) {
		loginErrorMessage = "Please enter password";
	}
	// if username and password are both missing...
	if (form.pwd.value.length == 0 && (form.id.value.length == 0 || form.id.value == "username")) {
		loginErrorMessage = "Please complete both fields";
	}
	// if there is a valid login error message...
	if (loginErrorMessage != "") {
		jQuery(form).siblings(".loginMessage").html(loginErrorMessage);
		//document.getElementById("loginMessage").innerHTML = loginErrorMessage;
		return false;
	}else{
		//submit form, then blank password field, add username and clear error messages.
		form.submit();
		form.pwd.value="";
		form.id.value="username";
		form.pass.value="password";
		jQuery(form).siblings(".loginMessage").html("");
		//show password after signin
		if (jQuery('.loginForm .inputPassword').val() == '') {
			jQuery('.loginForm .inputPassword').hide();
			jQuery('.loginForm .inputPasswordInitial').show();
		}
		//close signin popup on form submit

	    	jQuery('#signIn').css('visibility','hidden');

		return false;
	}

}

