/*
 * ??/??/???? JMH Initial Version
 * 09/03/2008 RD  Added showBullets()
 * 09/16/2008 JMH Modified showBullets() to use Prototype
 *                Removed most static variables used by showBullets()
 *                Added toggleRecyclerListByState() and expandState()
 * 10/02/2009 JLB optional waitToFinish parameter for ajax calls.  Otherwise
 *                form validation could complete successfully before ajax
 *                errors are returned.
 * 02/17/2010 JLB modified updated fields after getCouponInfo
 * 03/01/2010 JLB getCouponInfo changes
 */

var passwordTimerID = 0;

var bulletIndex = 2;

var statesLoaded = false;
var stateIsLoaded = $H();

function getPassTimerID() {
	return passwordTimerID;
}

function setPassTimer(timerID) {
	passwordTimerID = timerID;
}

function checkPasswordsMatch(formID) {
	var theForm = $(formID);
	
	if (theForm.password.value != theForm.passwordConfirmation.value) {
		$('passwordsDoNotMatch').show();
		$(theForm.password).addClassName("badField");
		$(theForm.passwordConfirmation).addClassName("badField");
	} else {
		$('passwordsDoNotMatch').hide();
		$(theForm.password).removeClassName("badField");
		$(theForm.passwordConfirmation).removeClassName("badField");
	}
}

function openYardComments(yardID) {
	openPopWin("/popups/yardComments.jsp?ID="+yardID,
	           1000,
	           512,
	           ",scrollbars=1,resizable=1",
	           320,
	           125,
	           "yardComments"+yardID);
}

function openYardRatingForm(replyID, yardName) {
	openPopWin("/live/rateYard.jsp?replyID=" + replyID + "&yardName=" + yardName,
	           1000,
	           512,
	           ",scrollbars=0,resizable=1",
	           220,
	           100,
	           "yardRatingsForm"+ replyID);
}

function popupRequestYardEmail(formID) {
	var theForm = $(formID);
	
	if ($F(theForm.zipcode) != "") {
		openPopWin("/popups/addRecycler.jsp?senderName=" +
		                                    $F(theForm.lastName) + ", " + $F(theForm.firstName) +
		                                    "&senderBusiness=" + $F(theForm.shopName) +
		                                    "&senderAddress1=" + $F(theForm.address1) +
		                                    "&senderAddress2=" + $F(theForm.address2) + 
		                                    "&senderCity=" + $F(theForm.city) +
		                                    "&senderState=" + $F(theForm.state) +
		                                    "&senderZip=" + $F(theForm.zipcode) +
		                                    "&senderPhone=" + $F(theForm.phoneNumber) +
		                                    "&senderPhoneExt=" + $F(theForm.phoneExtension) +
		                                    "&senderEmail=" + $F(theForm.email),
		           640,
		           600,
		           ",scrollbars=1,resizable=1",
		           200,
		           20,
		           "realpartsRequestNewSeller");
	} else {
		alert("Please enter your contact information before requesting a new recycler.");
	}
}


function checkUsernameInUse(usernameField, waitToFinish) {
	var errorDiv = $(usernameField.name + 'ErrorMessage');
	var processingImg = $(usernameField.name + 'InUseProcessing');

processingImg.setStyle({visibility: 'visible'});
	var myAJAXRequest = new Ajax.Request("/includes/AJAX_Utility.jsp", {
                                             asynchronous: !waitToFinish,
	                                     parameters: {
	                                                  checkUsername: 'true',
	                                                  username: $F(usernameField)
	                                                 },
	                                     onSuccess:  function(transport) {
	                                                     if (transport.responseXML.getElementsByTagName("response")[0].firstChild.nodeValue == "false") {
	                                                         usernameField.removeClassName("badField");
	                                                     } else {
	                                                         usernameField.addClassName("badField");
                                                                 
                                                                 if(errorDiv.innerHTML == null || errorDiv.innerHTML == "") {
                                                                    errorDiv.innerHTML = "This username is already in use";
                                                                 }
	                                                     }
	                                                 },
	                                     onComplete: function(transport) {
	                                                     processingImg.setStyle({visibility: 'hidden'});
	                                                 }
	                                   });
}

function checkEmailInUse(emailField, currentValue, waitToFinish) {
	if (currentValue == undefined) {
		currentValue = "";
	}
	
	var errorDiv = $(emailField.name + 'ErrorMessage');
	var processingImg = $(emailField.name + 'InUseProcessing');
	
	processingImg.setStyle({visibility: 'visible'});
	if ($F(emailField) != currentValue) {
		var myAJAXRequest = new Ajax.Request("/includes/AJAX_Utility.jsp", {
                                                     asynchronous: !waitToFinish,
		                                     parameters: {
		                                                     checkEmail: 'true',
		                                                     email: $F(emailField)
		                                                 },
		                                     onSuccess:  function(transport) {
		                                                     if (transport.responseXML.getElementsByTagName("response")[0].firstChild.nodeValue == "false") {
		                                                         emailField.removeClassName("badField");
		                                                     } else {
		                                                         emailField.addClassName("badField");
                                                                         if(errorDiv.innerHTML == null || errorDiv.innerHTML == "") {
                                                                            errorDiv.innerHTML = "This email address is already in use!  If it is yours, click " +
                                                                                "<a href='/popups/recoverPW.jsp?username_email=" + $F(emailField) + "'>here</a> to recover your password.";
                                                                            
                                                                         }
		                                                     }
		                                                 },
		                                     onComplete: function(transport) {
		                                                     processingImg.setStyle({visibility: 'hidden'});
		                                                 }
		                                   });
	} else {
		emailField.removeClassName("badField");
		processingImg.setStyle({visibility: 'hidden'});
	}
}

function getZipInfo(zipcodeField, waitToFinish) {
	var theForm = zipcodeField.form;
	
	var errorDiv = $(zipcodeField.name + 'ErrorMessage');
	var processingImg = $(zipcodeField.name + 'InvalidProcessing');
	
	var countryField = theForm.country;
	var cityField = theForm.city;
	var stateField = theForm.state;
	var stateNameField = theForm.stateName;
	var skipToField = theForm.phoneNumber;
	
	if (zipcodeField.name == "billingZipcode") {
		countryField = theForm.billingCountry;
		cityField = theForm.billingCity;
		stateField = theForm.billingState;
		stateNameField = theForm.billingStateName;
		skipToField = theForm.creditType;
	}

	if ($F(countryField) == "US") {
		processingImg.setStyle({visibility: 'visible'});
		var myAJAXRequest = new Ajax.Request("/includes/AJAX_Utility.jsp", {
                                                     asynchronous: !waitToFinish,
		                                     parameters: {
		                                                     getZipInfo: 'true',
		                                                     zipcode: $F(zipcodeField)
		                                                 },
		                                     onSuccess:  function(transport) {
		                                                     var response = transport.responseXML.getElementsByTagName("response")[0];
		                                                     if (response.firstChild != null) {
		                                                         cityField.value = response.getElementsByTagName("city")[0].firstChild.nodeValue;
		                                                         stateField.value = response.getElementsByTagName("state")[0].firstChild.nodeValue;
		                                                         stateNameField.value = response.getElementsByTagName("stateName")[0].firstChild.nodeValue;
		                                                         skipToField.focus();
		                                                         
		                                                         /* Update the recycler list */
                                                                         zipcodeField.removeClassName("badField");
		                                                         updateRecyclerChecklist_Zip(theForm.recyclerMaxDistance);
		                                                     } else {
		                                                         zipcodeField.addClassName("badField");
                                                                         if(errorDiv.innerHTML == null || errorDiv.innerHTML == "") {
                                                                            errorDiv.innerHTML = "The zip code is invalid."
                                                                         }
		                                                     }
		                                                 },
		                                     onComplete: function(transport) {
		                                                     processingImg.setStyle({visibility: 'hidden'});
		                                                 }
		                                   });
	}
}

function getCouponInfo(couponField) {
	var processingImg = $(couponField.name + 'InvalidProcessing');
	
	if ($F(couponField) != "") {
		processingImg.setStyle({visibility: 'visible'});

                var myAJAXRequest = new Ajax.Request("/includes/AJAX_Utility.jsp", {
		                                     parameters: {
		                                                  getCouponInfo: 'true',
		                                                  couponCode: $F(couponField)
		                                                 },
		                                     onSuccess:  function(transport) {
		                                                     var response = transport.responseXML.getElementsByTagName("response")[0];
		                                                     if (response.firstChild.nodeValue == "invalid") {
                                                                         $("yourPrice").innerHTML = $F(couponField.form.defaultPrice);
                                                                         $("formSubmitPrice").value = $F(couponField.form.defaultPrice);
		                                                         $("couponDescription").innerHTML = " - Invalid coupon.";
		                                                     } else {
                                                                         $("yourPrice").update(response.getElementsByTagName("price")[0].firstChild.nodeValue);
                                                                         $("formSubmitPrice").value = response.getElementsByTagName("price")[0].firstChild.nodeValue;
		                                                         $("couponDescription").innerHTML = response.getElementsByTagName("description")[0].firstChild.nodeValue;
		                                                     }
		                                                 },
		                                     onComplete: function(transport) {
		                                                     processingImg.setStyle({visibility: 'hidden'});
		                                                 }
		                                   });
	} else {
		$("yourPrice").innerHTML = $F(couponField.form.defaultPrice);
                $("formSubmitPrice").value = $F(couponField.form.defaultPrice);
		$("couponDescription").innerHTML = " - No coupon entered.";
	}
}

function updateRecyclerChecklist(maxDistanceField) {
	if (maxDistanceField.form.id == "profileForm") {
		updateRecyclerChecklist_CompanyCode(maxDistanceField);
	} else {
		updateRecyclerChecklist_Zip(maxDistanceField);
	}
}

function updateRecyclerChecklist_Zip(maxDistanceField) {
	var theForm = maxDistanceField.form;
	
	var fieldName = "recyclerList";
	
	/* Save currently selected yards */
	var selectedYardsParam = null;
	
	if ($$("#" + theForm.id + " input[name=\"" + fieldName + "\"]").length == 0) {
		/* If no inputs with the name 'fieldName' exist, use the yard selections
		   from the database */
		selectedYardsParam = "useDB";
	} else {
		var currentYards = $$("#" + theForm.id + " input[name=\"" + fieldName + "\"]:checked");
		if (currentYards.length > 0) {
			selectedYardsParam = currentYards[0].value;
			for (var i = 1; i < currentYards.length; i++) {
				selectedYardsParam += "," + currentYards[i].value;
			}
		} else {
			selectedYardsParam = "";
		}
	}
	
	var processingImg = $('recyclerChecklistProcessing');
	
	if ($F(theForm.zipcode) == "") {
		alert("Please enter a zipcode to determine recycler proximity.");
	} else {
		processingImg.setStyle({visibility: 'visible'});
		var myAJAXRequest = new Ajax.Updater("recyclerChecklist",
		                                     "/includes/AJAX_Utility.jsp", {
		                                     parameters: {
		                                                     getRecyclersChecklist: 'true',
		                                                     zipcode: $F(theForm.zipcode),
		                                                     maxDistance: $F(maxDistanceField),
		                                                     fieldName: fieldName,
		                                                     startTabIndex: ($(maxDistanceField).readAttribute("tabindex") + 1),
		                                                     currentSelections: selectedYardsParam
		                                                 },
		                                     onComplete: function(transport) {
		                                                     processingImg.setStyle({visibility: 'hidden'});
		                                                     $("secondAddFormNotice").show();
		                                                 }
		                                   });
	}
}

function updateRecyclerChecklist_CompanyCode(maxDistanceField) {
	var theForm = maxDistanceField.form;
	
	var fieldName = "recyclerList";
	
	/* Save currently selected yards */
	var selectedYardsParam = null;
	
	if ($$("#" + theForm.id + " input[name=\"" + fieldName + "\"]").length == 0) {
		/* If no inputs with the name 'fieldName' exist, use the yard selections
		   from the database */
		selectedYardsParam = "useDB";
	} else {
		var currentYards = $$("#" + theForm.id + " input[name=\"" + fieldName + "\"]:checked");
		if (currentYards.length > 0) {
			selectedYardsParam = currentYards[0].value;
			for (var i = 1; i < currentYards.length; i++) {
				selectedYardsParam += "," + currentYards[i].value;
			}
		} else {
			selectedYardsParam = "";
		}
	}
	
	var processingImg = $('recyclerChecklistProcessing');
	
	processingImg.setStyle({visibility: 'visible'});
	var myAJAXRequest = new Ajax.Updater("recyclerChecklist",
	                                     "/includes/AJAX_Utility.jsp", {
	                                     parameters: {
	                                                     getRecyclersChecklist: 'true',
	                                                     companyID: $F(theForm.companyCode),
	                                                     maxDistance: $F(maxDistanceField),
	                                                     fieldName: fieldName,
	                                                     startTabIndex: ($(maxDistanceField).readAttribute("tabindex") + 1),
	                                                     currentSelections: selectedYardsParam
	                                                 },
	                                     onComplete: function(transport) {
	                                                     processingImg.setStyle({visibility: 'hidden'});
	                                                 }
	                                   });
}

function showRecyclerChecklist(showChecklist) {
	var recyclerListRelated = $$('.recyclerListRelated');
	
	if (showChecklist) {
		for (i = 0; i < recyclerListRelated.length; i++) {
			recyclerListRelated[i].show();
		}
	} else {
		for (i = 0; i < recyclerListRelated.length; i++) {
			recyclerListRelated[i].hide();
		}
	}
}

function toggleCityState(countrySelect) {
	var theForm = countrySelect.form;
	
	var countryField = theForm.country;
	var cityField = $(theForm.city);
	var stateField = $(theForm.stateName);
	var zipField = theForm.zipcode;
	
	if (countrySelect.name == "billingCountry") {
		countryField = theForm.billingCountry;
		cityField = $(theForm.billingCity);
		stateField = $(theForm.billingStateName);
		zipField = theForm.billingZipcode;
	}
	
	var recyclerListOptions = $$(".recyclerListOptions");
	
	if ($F(countryField) == "US") {
		cityField.writeAttribute({readonly: 'readonly'});
		stateField.writeAttribute({readonly: 'readonly'});
		
		cityField.value = "";
		stateField.value = "";
		
		if (countrySelect.name != "billingCountry") {
			getZipInfo(zipField);
			
			for (i = 0; i < recyclerListOptions.length; i++) {
				recyclerListOptions[i].show();
			}
		}
	} else {
		cityField.writeAttribute({readonly: null});
		stateField.writeAttribute({readonly: null});
		
		if (countrySelect.name != "billingCountry") {
			for (i = 0; i < recyclerListOptions.length; i++) {
				recyclerListOptions[i].hide();
			}
		}
	}
}

function copyStateValue(stateNameField) {
	var theForm = stateNameField.form;
	
	var stateField = theForm.state;
	
	if (theForm.country != undefined &&
	    stateNameField.name == "billingStateName") {
		stateField = theForm.billingState;
	}
	
	stateField.value = stateNameField.value;
}

function toggleFoundThrough(foundThroughField) {
	var theForm = foundThroughField.form;
	
	if ($F(foundThroughField) != "Other") {
		theForm.foundThrough2.disabled = true;
	} else {
		theForm.foundThrough2.disabled = false;
	}
}

function xhtmlLinksTargetFix() {
	var anchors = $$("a[href][rel='external']");
	for (var i = 0; i < anchors.length; i++) {
		anchors[i].target = "_blank";
	}
}

function showBullets () {
	var bullets = $('flashText').firstDescendant().childElements();
	var numBullets = bullets.length;
	
	/* Hide the currently displayed bullets */
	if (bulletIndex == 0) {
		bullets[numBullets - 2].hide();
		bullets[numBullets - 1].hide();
	} else if (bulletIndex == 1) {
		bullets[numBullets - 1].hide();
		bullets[bulletIndex - 1].hide();
	} else {
		bullets[bulletIndex - 2].hide();
		bullets[bulletIndex - 1].hide();
	}
	
	/* Loop 2 times to get 2 bullet points */
	for (var i = 0; i < 2; i++) {
		if (bulletIndex >= numBullets) {
			bulletIndex = 0;
		}
		
		bullets[bulletIndex].show();
		
		bulletIndex++;
	}
	
	setTimeout('showBullets();', 6000);
}

function expandState(state) {
	var stateToFill = $(state);
	
	if (stateToFill.visible()) {
		stateToFill.hide();
		$(state + "_Link").src = "/images/plus_icon.gif";
	} else {
		$(state + "_Link").src = "/images/minus_icon.gif";
		if (stateIsLoaded.get(state) != true) {
			stateIsLoaded.set(state, true);
			var processingImg = $(state + "Processing");
			
			processingImg.setStyle({visibility: 'visible'});
			var myAJAXRequest = new Ajax.Updater(state,
			                                     "/includes/AJAX_Utility.jsp", {
			                                     parameters: {
			                                                     expandState: 'true',
			                                                     state: state
			                                                 },
			                                     onComplete: function(transport) {
			                                                     processingImg.setStyle({visibility: 'hidden'});
			                                                     stateToFill.show();
			                                                 }
			                                   });
		} else {
			stateToFill.show();
		}
	}
}
