// This is a file to hold helper functions for the calendar
//
// Just a bunch of wrapper functions, maybe it will be inheritance one day

//Global Variables
var saved_requests = new Array;  //this is an array to store each ajax request 
//to retrieve the dates based on zipcode and product id.  This way we can reuse 
//requests and not have to hit the server everytime.

//this is our array with all our open calendars
//this way if the user quickly clicks on the submit button we won't open 2 at
//once.  We store an object with a reference to the open calendar and the zipcode
//used for that calendar.  This way if the zipcode changes we can close down 
//the open calendar.
var calendars_open = new Object();


/*
	Calendar.setup(
	{
		datestatusfunc: ourdatestatusfunc,
		onupdate: datechanged,
		position: position,
		show_legend: show_legend,
		weeknumbers: false,
		inputfield: inputfield,
		hiddenlayer: hiddenlayername,
		startyear: startyear,
		startmonth: startmonth,
		endyear: endyear,
		endmonth: endmonth,
		footer: footer,
		nofootermessages: nofootermessages,
		heading: heading,
		mouseoffclose: mouseoffclose, 
		button: triggername,
		date: document.getelementbyid(inputfield).value,
		flat: flatid,    //this is if we want the calendar to be inside a parent
        specialflat: specialflat || false,  //this is if we want a special flat calendar
										   //this is basically a mix of the
										   //flat calendar and the popup
										   //calendar
		loading_calendar: loading_cal					
	}
	);
*/

/*
	This is a wrapper function for Calendar.setup
	- it's really trying to rewrite buildCalendar() to make it easier to override, and set defaults
*/
Calendar.wrapperSetup = function (params) {
    function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

	// default postion should be the x and y coords, can i find it at this location?
	param_default("position", new Array(0,0));

	//default for onClose
	var _onClose = function (cal)
    {//we want to set the let everyone know that 
	//our calendar is closed by calling this function
	 setCalendarClosed(cal); //this should be called in all
	 cal.hide();  //we have to hide as well
	 cal.destroy();
	 //onClose handlers.  So if you override this
	 //then add setCalendarClosed(cal)
	 //unless you don't care about multiple calendars open at once
	}
													   
	// dateChanged

	param_default("show_legend", 0);
	param_default("mouseOffClose", false);
	param_default("noFooterMessages", false);
	param_default("onClose", _onClose);
	//param_default("wrapperSetup_TEST", "Hi World");


	// default, just gives an alert, so you can see what it does
	var _onUpdate = function (calendar) {
		if (calendar.dateClicked) {
			// get new form data dates (pretty one for display and one for submission 
			var formattedDate = calendar.date.print("%a %m/%d/%y");
			var deldate = calendar.date.print("%Y/%m/%d");

		}
	}
	param_default("onUpdate", _onUpdate);



	// What is the ourExtraDateStatusFunc
	// Well this is sort of another call back that is called
	// so ourDateStatusFunc calls

	return Calendar.setup( params );
}






/* This is for setting up the calendar on the product page
	currently this is called by both the international and 
	regular products.
	takes in our params object and returns a ref to our calendar
	object
*/
Calendar.productPageSetup = function (params) {

function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

	//function to be called when they select a date
	var _dateSelected = function (calendar) {
		if (calendar.dateClicked) {
			var formattedDate = calendar.date.print("%a %m/%d/%y");
			var deldate = calendar.date.print("%Y/%m/%d");
			var dateField = document.getElementById(calendar.params.inputFieldID);
			var displayField = document.getElementById("display_" + calendar.params.inputFieldID);
			var shippingDisplayField = document.getElementById(calendar.params.shippingDisplayField);
			var delDateRange = calendar.params.delDateRange;
			var displayDelDateRange = calendar.params.displayDelDateRange;
			
			if (delDateRange[deldate]) {
				dateField.value = delDateRange[deldate];
				displayField.value = displayDelDateRange[deldate];
			} else {
				dateField.value = deldate;
				displayField.value = formattedDate;
			}
			shippingDisplayField.value = 'Shipping - ' + calendar.params.shipping_methods_by_date[deldate];
			// removed radio options code			
			if (theIOTWDateArray) updateProductPagePrices();

		    document.getElementById("display_" + calendar.params.inputFieldID).blur();
		}
	}

		var _onclose = function (cal)
		{
		 setCalendarClosed(cal); //this should be called in all
        //onClose handlers.  So if you override this
       //then add setCalendarClosed(cal)
        //unless you don't care about multiple calendars open at once
         cal.hide();
         cal.destroy();  //no longer call destroy Must call it in IE!
		 //right now the calendar is shown on focus of the display field.
         //so this means that when they click on the field again to choose another
         //date then it already has focus so this even is not fired therefore
         //the calendar is not shown.  This way when they click on the field
         //again we will show the calendar.
         document.getElementById("display_" + calendar.params.inputFieldID).blur();
		}

param_default("onUpdate", _dateSelected);  //setting our on update if not set yet
param_default("onClose", _onclose);  //setting our onclose handler



/* 
	calendar.js forces a padding of 4 pixels for the calendar div (and you can't turn it off)
	and each orderbox-step has a padding of 5 pixels and a border of 1 pixel

	We want it to cover the whole of delivery date dropdown and have it displayed vertically
	aligned with the rest of the orderbox 
*/
var offset = $("#dropdown_deldate_product").offset();
offset.left -= 10;
offset.top -= 6;

params.forceShowAt = true;
params.position = new Array( offset.left, offset.top );

return Calendar.wrapperSetup( params );

}





/*
	A rather descriptive name of something does what it says it does
	- really just buildCalendar() with some tweaks

	Sets:
		1) dateStatusFunc
		2) onUpdate
		3) footer
		4) startYear
		5) startMonth
		6) endYear
		7) endMonth
*/
function buildCalendarParamsFromAjax( responseText ) {
	// Stores everything into the param data structure that you can pass directly
	// into a Calendar.XXXsetup function
	var params = {};
	var json = eval('(' + responseText + ')');

	var startDay				= json.calendar_start_day;
	var startMonth				= json.calendar_start_month;
	var startYear				= json.calendar_start_year;
	var endDay					= json.calendar_end_day;
	var endMonth				= json.calendar_end_month;
	var endYear					= json.calendar_end_year;
	// one day, remove the need for the extra evals
	var undeliverable			= eval('(' + json.unavailable_dates + ')');
	var saturday				= eval('(' + json.saturday_dates + ')');
	var twoday					= eval('(' + json.twoday_dates + ')');
	var nextday					= eval('(' + json.nextday_dates + ')');
	var delDateRange			= eval('(' + json.del_date_range + ')');
	var displayDelDateRange		= eval('(' + json.display_del_date_range + ')');
	var footer					= eval('(' + json.footer_messages + ')'); 
	var shipping_methods_by_date = eval('(' + json.shipping_methods_by_date + ')');
	var zip_availability         = json.zip_availability;
	var zip_error_message        = json.zip_error_message;

	/*
		dateStatusFunc:  returns false for any unavailable day, use to grey out the date
	
		dateIsSpecial allows us to mark specific dates as being *special*
		so this function is dynamic and actually changes with each callback
		it's used by ourDateStatusFunc  
	*/
	var _dateIsSpecial = function (year, month, day) {
		if ( (year < startYear) || (year == startYear && month < startMonth) || (year == startYear && month == startMonth && day < startDay) ||
			year > endYear || (year == endYear && month > endMonth) || (year == endYear && month == endMonth && day > endDay)
		) return "date_unavailable";

		for (var i in undeliverable[month]) {
			if (undeliverable[month][i] == day) return "date_unavailable";
		}
		for (var i in saturday[month]) {
			if (saturday[month][i] == day)  return "saturday_delivery";
		}
		for (var i in twoday[month]) {
			if (twoday[month][i] == day) return "twoday_delivery";
		}
		for (var i in nextday[month]) {
			if (nextday[month][i] == day) return "nextday_delivery";
		}
		return false;
	}

	var _ourDateStatusFunc = function (date, y, m, d) {
		m = m+1;
		var isSpecial = _dateIsSpecial(y, m, d);
		if (isSpecial) 
			return isSpecial;
		else
			return false; // other dates are enabled
	}
	
	params.dateStatusFunc = _ourDateStatusFunc;

	/* and now just values, not more dynamic function references */
	params.startYear = startYear;
	params.startMonth = startMonth;
	params.endYear = endYear;
	params.endMonth = endMonth;
	params.footer = footer;
	params.shipping_methods_by_date = shipping_methods_by_date;
	
	
	/* store the date ranges, needed for the onUpdate function */
	params.delDateRange = delDateRange;
	params.displayDelDateRange = displayDelDateRange;

    /* store zip errors */
	params.zip_availability = zip_availability;
	params.zip_error_message = zip_error_message;

	/* Added for design2007. Parsing fees out of footer, but we need to know what to parse out */
	/* Also get date from server not untrusty client */
	params.today_date = json.today_date;
	params.dropdown_dates = eval('(' + json.dropdown_dates + ')');

	return params; 
}

/* this will save our request object into a global array
   so that when a user wants to search on dates for a 
	zipcode and product that they have already searched on
	then we don't have to hit the server again
*/
function saveRequest(req,params) {
	var zipFieldElem = document.getElementById(params.zipField);
	var product_id = params.product_id || document.getElementById(params.productField).value;
	var zip_code = params.zip_code || ( zipFieldElem ? zipFieldElem.value : new String () );

	if (zip_code.length > 5) {
		zip_code = zip_code.substring(0,3);
	}
	
	var key = zip_code+"_"+product_id;
	saved_requests[key] = req;
}

/* This will return a saved request for a given
   zipcode and product id if it exists.  If not
   we just return false.

*/
function getSavedRequest(params) {
	var zipFieldElem = document.getElementById(params.zipField);
	var product_id = params.product_id || document.getElementById(params.productField).value;
	var zip_code = params.zip_code || ( zipFieldElem ? zipFieldElem.value : new String () );
	// this is a hack for International Products, params.zip_code == country_id

	if (zip_code.length > 5) {
		zip_code = zip_code.substr(0,3);
	}
	
	var key = zip_code+"_"+product_id;
	var req = saved_requests[key];

	//should we test for a timestamp value here??? Just to make sure
	//the request is not too old??.
	if(req //first are we defined
	   && req.readyState == 4 //now check our ready state and status 
	   && req.status == 200)
	{
		return req;
	}

	return false;
}

/* This is for showing the calendar on the product page
for regular products.  International products have their own
function
*/
function showProductCalendar(params)
{
	/* if we have a zip error than we don't want to show the 
	calendar
	onload our calendar params has zip error set to true
	only by entering a valid zip code in the zip field
	will the zip error be set to false.  This is all handled
	by the js functions called zipSuccess and zipFailure
	which are currently defined in product.epl
	*/

	if(params.invalidZip) {
		//if the ajax call is still running for validating zip
		//then we will display the zip error even if there isn't one!
	 	if(document.getElementById(params.zipField).value == '') {
			//this is for the case when they don't enter a zip
			//and therefore the ajax call in not called.
			hideElement(params.zipErrorID,true);
			return;
		}

		if(params.validating_zip) {
			//we are going to the server to validate
			//so comeback later
			var _func = function () { showProductCalendar(params);};

			window.setTimeout(_func,50);
		}
		return;
	}
	
	/* incase you click on the link twice before it popups */
    if (isCalendarOpen(params)) {
        return;
    }
    //we don't have an actual reference to our calendar so just
    //send in 1 for the second param.  This way if the user
    //quickly clicks the button then we won't open 2 calendars at once
	//alert('Hello');
	setCalendarOpen(params,1);

	// no loading calendar

	//if the calendar pops up over the input field while they have focus
	//on the field then the cursor peeks through into the calendar.
	//so we will shift focus off the input field
	document.getElementById("display_" + params.inputFieldID).blur();

	//build our ajax call back to get all our dates
	var ajaxCallBack = function (req) {
		if (req.readyState == 4 && req.status == 200) {
			// process the parameters	
			var calendar_params = buildCalendarParamsFromAjax(req.responseText);	
			   /* only copy values into the calendar object
               that has not been set by the ajax call back */
               for (i in params)
                if (typeof calendar_params[i] == "undefined")
                    calendar_params[i] = params[i];
			/* setup the other params form the input 
			 */
			calendar_params.inputField = params.inputField;
			calendar_params.button = params.button || params.triggerName; 
			calendar_params.displayField = params.displayField; // for showing the resulting date

			// make a calendar
			if(calendar_params.zip_availability > 0){
		 	    var new_cal = Calendar.productPageSetup(calendar_params);
			}else{
			    calendar_params.loading_className = "loading_msg_zipError";
			    var new_cal = Calendar.unavailableSetup(calendar_params);
			}
			//now that we have our actual reference to our calendar object
			//then we will properly set the calendar to open.
			setCalendarOpen(params,new_cal);
	
			//save our request for later use
			saveRequest(req,params); //should we see if it is already saved??
		}
	}

 /* get the vars */
	var product_id;
    var master_product_id = "";

	if (Ftd.product.cfg.master) {
		product_id = $(".prices-orderbox :radio:checked").val();
		master_product_id = $("#product_id").val();
	}
	else {
		product_id = $("#product_id").val();;
	}

	params.product_id = product_id;
	
	var saved_req = getSavedRequest(params);
	if (saved_req)
		ajaxCallBack(saved_req);

	// it must be saved, no AJAX
}

/*  This is called on the product page to show the calendar for
international products.  There isn't that much difference from the
regular products but we don't have a zip code 
and we do have a country id
*/
function showInternationalProductCalendar(params)
{
/* incase you click on the link twice before it popups */
     if (isCalendarOpen(params)) {
        return;
    }
    //we don't have an actual reference to our calendar so just
    //send in 1 for the second param.  This way if the user
    //quickly clicks the button then we won't open 2 calendars at once

//setCalendarOpen(params,1);
//call the loadCalendar setup.  Which will return a reference to
//our loading calendar object which we will add to params
//so we can close it within calendar.js

// skip loading Calendar, AJAX already fired

//if the calendar pops up over the input field while they have focus
//on the field then the cursor peeks through into the calendar.
//so we will shift focus off the input field
document.getElementById("display_" + params.inputFieldID).blur();

//build our ajax call back to get all our dates
	var ajaxCallBack = function (req) {
		if (req.readyState == 4 && req.status == 200) {
			// process the parameters	
			var calendar_params = buildCalendarParamsFromAjax(req.responseText);	
			   /* only copy values into the calendar object
               that has not been set by the ajax call back */
               for (i in params)
                if (typeof calendar_params[i] == "undefined")
                    calendar_params[i] = params[i];
			/* setup the other params form the input 
			 */
			calendar_params.inputField = params.inputField;
			calendar_params.button = params.button || params.triggerName; 
			calendar_params.displayField = params.displayField; // for showing the resulting date

			// make a calendar
		 	var new_cal = Calendar.productPageSetup(calendar_params);
			//now that we have our actual reference to our calendar object
			//then we will properly set the calendar to open.
			setCalendarOpen(params,new_cal);
			//save our request for later use
			saveRequest(req,params); //should we see if it is already saved??
		}
	}

	//var saved_req = getSavedRequest(params);
	var saved_req = ProductPage.deliveryDatesRequest;

	if(saved_req)
	{//if we have a saved request then just do
		 //that will be the same as if we went to the 
		 //server e.g. same zip and product id
		 //our ajax callback and don't bother going to the server
		 ajaxCallBack(saved_req);
	} else {
		alert("Something is wrong, not AJAX delivery date data");
   }
}





/* ****************************************************************************** */
//  Ftd contains the main functions:
//  Ftd.shipping
//  Ftd.product
var Ftd  = new Object();
/* ****************************************************************************** */



/* ****************************************************************************** */
    Ftd.product  = new Object();
/* ****************************************************************************** */
	
    Ftd.product.cfg = {}; // href for storing configuration key/value pairs

	// Bad name... this calls the AJAX for delivery dates
	// why not call it requestForDeliveryDates() ??
	// so want to rewrite this soon
	Ftd.product.updateSelectedDate = function (productField, priceField, zipField, inputField, country_id , countError, extra_params) {
		if(extra_params == null) { extra_params = {}; }

        // Since serveral items on the product page call this function, lets keep track if it's called.
		if(Ftd.product.cfg.updateSelectedDateCalled) return;
        Ftd.product.cfg.updateSelectedDateCalled = 1;
		setTimeout("Ftd.product.cfg.updateSelectedDateCalled = 0",6000);

		calendar_params_product.validating_zip = true;

		if(zipField) { 
			if (!validateZip(zipField)) {
				$("#zipcode-error-message").html("Please enter a valid zipcode.");
				ProductPage.goToState("ZIPCODE_ERROR");
				//we don't want the calendar to be able to open
				//so set invalid zip to true;
				calendar_params_product.invalidZip = true;
				calendar_params_product.validating_zip = false;
				Ftd.product.cfg.updateSelectedDateCalled = 0;
				return;
			} 
		}
		
		// Hide error divs for user messaging, such as calendar loading and zip error 
		ProductPage.goToState("WAITING_FOR_AJAX");

		var product_id;
		var master_product_id = "";

		if (Ftd.product.cfg.master) {
			product_id = $(".prices-orderbox :radio:checked").val();
			master_product_id = $("#product_id").val();
		}
		else {
			product_id = $("#product_id").val();
		}
		var res = getSavedRequest( {'product_id': product_id, 'zipField': zipField } )

		//AJAX callback function, which will reset the defined parameters above with new calendar attributes
		function showParameters (req) {
			if (req.readyState == 4 && req.status == 200) {
				var json = eval('(' + req.responseText + ')');

				var next_available_date     = json.next_available_date;
				var next_available_date_display = json.next_available_date_display;

				var dateField = document.getElementById(inputField);
				var displayField = document.getElementById("display_"+inputField);


				// Changing date field value according to AJAX call
				// If zip is invalid then don't change the values
				if(json.zip_availability > 0){
					
					//if(Ftd.product.cfg.dropdown_count>0 && extra_params.updateDeliveryDropdown){
					var dropdown = Ftd.product.updateDeliveryDropdown(req, {'dropdown_field': "dropdown_"+inputField, 
						'display_fee':Ftd.product.cfg.display_dropdown_fee});
					// Set index to first available date
					if (dropdown) { 
						dropdown.selectedIndex = 1;
						dateField.value = dropdown.options[1].value;
						// Take care of date range, if the first date is part of one
						var dropdownFirstDate = dropdown.options[1].value.split(":");	
						displayField.value = new Date(dropdownFirstDate[0]).print("%a %m/%d/%y");
					}
					//}

					// replace with with jQuery later
					if (document.getElementById("sameday-delivery-available-messsage")) {
						if(json.available_today) {
							hideElement('sameday-delivery-available-messsage', 1);
						} else {
							hideElement('sameday-delivery-available-messsage', 0);
						}
					}

					// do we need this really?
					if (document.getElementById("display_deldate_product")) {
						if (json.has_date_ranges && document.getElementById("display_deldate_product")) {
							document.getElementById("display_deldate_product").style.width = "14em";
						} else {
							document.getElementById("display_deldate_product").style.width = "110px";
						}
					}
			
					// not sure what this is
					product_page_submit = 0;

					ProductPage.goToState('SHOW_DELIVERY_DATE_DROPDOWN');

				//Product not available for given zipcode.
				}else{
					// Display zip code error message
					$("#zipcode-error-message").html( json.zip_error_message );

					// This causes it to remove all the values from the dropdown
					if(Ftd.product.cfg.dropdown_count>0 && extra_params.updateDeliveryDropdown){
						Ftd.product.updateDeliveryDropdown(req, {'dropdown_field': "dropdown_"+inputField, 
							'zip_error':1});
					}

					// Clear date field value
					displayField.value = "";

					product_page_submit = 1;
					
					ProductPage.goToState('ZIPCODE_ERROR');
				}

                     
				 saveRequest(req, {'product_id': product_id, 'zipField': zipField } );
				
				 //we want the calendar to be able to open
				 //so we will set our zip error to false for the calendar
				 //params.  Since we are on the product page we know that we only have
				 //one calendar_params object.
				 calendar_params_product.invalidZip = false;
				 calendar_params_product.validating_zip = false;
			}

			Ftd.product.cfg.updateSelectedDateCalled = 0;  // unlock
		} // end showParameters


		if (res) {
			showParameters(res);
		} else {
			// do AJAX call
			//request = "/" + markcode + "/json/delivery_data.epl?country_id="+country_id +"&zip_code="+document.getElementById(zipField).value+"&product_id="+product_id+"&master_product_id="+master_product_id+"&product_price="+document.getElementById(priceField).value+"&date="+dateField.value+"&show_abbreviated_date_ranges=1&rand="+Math.round((Math.random()*999999)+1)+"&counterror="+countError;

			// update the AJAX call in the future to not need this field
			var dateField = document.getElementById(inputField);	

			request = "/" + markcode + "/json/delivery_data.epl?"
				+ "country_id=" + country_id 
				+ "&zip_code=" + document.getElementById(zipField).value
				+ "&product_id=" + product_id
				+ "&master_product_id=" + master_product_id
				+ "&product_price=" + document.getElementById(priceField).value
				+ "&date=" + dateField.value 
				+ "&show_abbreviated_date_ranges=1"
				+ "&rand="+Math.round((Math.random()*999999)+1) 
				+ "&counterror="+countError;
			ajaxLoader(request, showParameters);
			// AJAX will return to function to set the above variables
		}

        } // end Ftd.product.updateSelectedDate



    /* 
	  Builds the design2007 date drop down
	  Input: req from ajax call, dropParams
	  dropParams: dropdown_field, display_fee, zip_error 

	  Notes: Keep generic so it can be used on any page, not just the product page. Currently there is nothing that ties this function to the product page, it is only associated with the product namespace since this is where it is first used.

	*/
    Ftd.product.updateDeliveryDropdown = function(req, dropParams) {
    var dropdown = document.getElementById(dropParams.dropdown_field);

	// this could be an actual value	
	var responseText;
	if (typeof req == 'object') 
		responseText = req.responseText;
	else
		responseText = req;

	if(dropdown && responseText){
		// Remove all options
		for(var i=dropdown.length-1 ; i>=0 ; i--){
		    dropdown.remove(i);
		}

		// Add first drop down element
		var dropdown_option = document.createElement('option');
		if (dropParams.zip_error) 
			dropdown_option.text = 'Invalid Zip Code';
		else 
			dropdown_option.text = 'Select Date';
		dropdown_option.value = ""; // blank value
		try{ dropdown.add(dropdown_option,null); }
        // IE only
		catch(ex){ dropdown.add(dropdown_option); }	

		if(dropParams.zip_error) return;

		params = buildCalendarParamsFromAjax(responseText);
		if(params.dropdown_dates && params.today_date){
			var date = new Date(params.today_date);

			var success_count = 0;
			var fail_count = 0;
			var day_counter = date.getDate();
			var month_counter = date.getMonth()+1;
			var year_counter = date.getFullYear();
			
			// Go through params.footer one day at a time
			// Stop if we hit desired available dates or a certain number of unavailable dates
			while(success_count<Ftd.product.cfg.dropdown_count && fail_count<150){

            if(day_counter>31){
				day_counter = 1;
				month_counter++; 
			}
			if(month_counter>12){
				month_counter = 1;
				year_counter++;
			}
			
			// Setup the footer key
			var curr_day = day_counter;
			var curr_month = month_counter;
			if(curr_day<10) curr_day = '0'+ curr_day;
			if(curr_month<10) curr_month = '0'+ curr_month;
			var curr_date = year_counter + '/' + curr_month + '/' + curr_day;
				
			// Is the date available
			if(params.dropdown_dates[curr_date] != null){
				var fee = params.dropdown_dates[curr_date];	
				// Create the pretty date
				var pretty_date = new Date(curr_date);
			    
				// Create the option element
	            // Check for a date range
							var dropdown_value = curr_date;
							var dropdown_text = pretty_date.print("%b %e - %A");
							if(params.delDateRange[curr_date]){
							    var begin_date = params.delDateRange[curr_date].split(":")[0];
							    var end_date = params.delDateRange[curr_date].split(":")[1];

								// Last date in a range
								if(end_date == curr_date){
								    var pretty_begin_date = new Date(begin_date);
									var pretty_end_date = new Date(end_date);
								    dropdown_text = pretty_begin_date.print("%b %e %a.")+" to "+pretty_end_date.print("%b %e %a."); 
									dropdown_value = params.delDateRange[curr_date];
							    // First or middle date in a range
								}else{
								    dropdown_text = "";
								}
							}

							if(dropdown_text){
								// Add fee 
								if(dropParams.display_fee) dropdown_text =  dropdown_text + " - $" + fee;
								
								dropdown_option=document.createElement('option');
								dropdown_option.value= dropdown_value;
								dropdown_option.text= dropdown_text;
								try{ dropdown.add(dropdown_option,null); }
								// IE only
								catch(ex){ dropdown.add(dropdown_option); }	
							
							    success_count++;
							}

						}else{
						    fail_count++;
						}

						day_counter++;
					}
					
				} // end if params.footer


				// Add last drop down element
				var dropdown_option=document.createElement('option');
				dropdown_option.text='view more delivery dates';
				dropdown_option.value='showCal';
				try{ dropdown.add(dropdown_option,null); }
                // IE only
				catch(ex){ dropdown.add(dropdown_option); }	

				// Set the selected date to default
				dropdown.selectedIndex=0;
				if( getBrowserTypeNew() == "Opera") {
				    dropdown.size = success_count + 2;
				    dropdown.length = success_count + 2;
				}

				return dropdown;
	} // end if responseText
	} // end Ftd.product.updateDeliveryDropdown







 


/* If you only want 1 calendar open at a time then this should be called
	before you show any loading calendars or do any ajax calls. 
	Send in your calendar_params object.
	It will return true if a calendar is already open.
	However, if a calendar is open for the inputField you are submitting
	for, then we will check to see if our zip codes match.  If the zip
	code for the currently open calendar is different than the 
	new calendar we are trying to open then we will close down
	the currently open calendar and return false to let you know
	that the calendar is no longer open so you can open the new 
	calendar
*/
function isCalendarOpen(params)
{
	/* 
		International Product page doesn't have a zipcode field (STZIP)
		Instead of creating a fake on, let's just update this function 
		to work with something else
	*/

	if (typeof(calendars_open[params.inputFieldID]) == "undefined") {
		//we don't exist so open right away
		return false;
	}
	
	if (typeof(params.zipField) !="undefined") {
		var el = document.getElementById(params.zipField);

		//calendars_open contains a zipCode value
		if (el && el.value == calendars_open[params.inputFieldID].zipCode) {
			alert("calendar is already open!, quitting ");
			//same zipcode so stay open
			return true;
		}
	}

	//we are submitting a new zipcode so we should close down the 
	//open cal and return false
	closeOpenCalendar(params);

	return false;
}

/* This is for closing down whatever calendar is currently open
   for the corresponding inputFieldID sent in via params object.
   we test to make sure anything is open and that we have a valid
   calendar object before we do anything so you don't have to 
   worry about calling this with the calendar already closed

*/
function closeOpenCalendar(params)
{
	if(typeof(calendars_open[params.inputFieldID]) != "undefined"  //make sure we have somthing 
	   && typeof(calendars_open[params.inputFieldID].calendar) == "object") 
	{//make sure we have a calendar object
	 //NOTE: should we call the calendar.callCloseHandler here??
	 //that way if any cleaning up needs to be done it can be done 
	 //in onClose of the calendar.
	 calendars_open[params.inputFieldID].calendar.hide();
	 calendars_open[params.inputFieldID].calendar.destroy();
	 //calendars_open[params.inputFieldID].calendar.callCloseHandler();
	}
calendars_open[params.inputFieldID] = undefined; //clearing out our array for this inputField
}

/* this will set our calendars_open array to let us know
	that our calendar is open for the corresponding inputFieldID
	sent in through our params object.  This should be called
	right away even before you have a valid calendar object
	open, just send in a 1 for the cal object.  We do this because
	we want to quickly set the calendar to open before any ajax calls.
	then once our ajax calls our complete we should call this function again
	but this time with a proper calendar object so we can properly
	close down later
	
*/
function setCalendarOpen(params,cal) {
	calendars_open[params.inputFieldID] = 1;  //quickly set to true in case we have a race condition
	var open_cal = new Object;
	open_cal.calendar = cal;

	if(typeof (params) != "undefined"  && typeof (params.zipField) != "undefined") {
		var zipFieldElem = document.getElementById(params.zipField);
		if (zipFieldElem) 
			open_cal.zipCode = zipFieldElem.value;	 
	} else if (typeof (params) != "undefined" && typeof (params.zipCode) != "undefined") {
		//we may not have a zipFied but we might have a zipCode
		open_cal.zipCode = params.zipCode;
	}

	calendars_open[params.inputFieldID] = open_cal;  //setting our calendar to open
}

//simple function to set our calendar closed.
//just in case in the future we want to do more when we close
function setCalendarClosed(cal)
{
calendars_open[cal.params.inputFieldID] = undefined;
}



