// requires that the YUI script already be loaded...

///////////////////////////
// define some variables //
///////////////////////////
var sUrl_filename	= 'js/pricing.php';

// get the domain info dynamically
var cur_location			= window.location;
var pattern					= new RegExp("^https?://[^/]+/", "i");
var protocol_plus_domain	= pattern.exec(cur_location); 
var sUrl					= protocol_plus_domain[0] ? protocol_plus_domain[0] + sUrl_filename : null;

// this is a hash table containing information about each unit

///////////////////////////////////////////////////////////////////
// define the callback functions -- these are internal functions //
///////////////////////////////////////////////////////////////////
var handleSuccess = function(o) {
	var jsonString	= o.responseText;
//	alert(jsonString);
	var priceList	= YAHOO.lang.JSON.parse(jsonString);
	buildTable(priceList);
};

var handleFailure = function(o) {
	var p	= document.createElement('p');
	var txt	= document.createTextNode('Prices could not be retrieved at this time. Please call 1-877-269-9352.');
	p.appendChild(txt);
	wrapper.appendChild(p);
};

var callback = {
	success:handleSuccess,
	failure:handleFailure
};


/////////////////////////////
// more internal functions //
/////////////////////////////

//helper function
function in_array(string, array) {
	for (i = 0; i < array.length; i++) {
			if (array[i] == string) {
				return true;
			}
	}
	return false;
}

function formatDate (someDate) { // expected format is mm-dd-yyyy
	var months = new Array();
	months[1]	= "Jan";
	months[2]	= "Feb";
	months[3]	= "Mar";
	months[4]	= "Apr";
	months[5]	= "May";
	months[6]	= "Jun";
	months[7]	= "Jul";
	months[8]	= "Aug";
	months[9]	= "Sep";
	months[10]	= "Oct";
	months[11]	= "Nov";
	months[12]	= "Dec";
	
	dateArr		= someDate.split('-');
	var month	= ( dateArr[1].indexOf("0") !== 0 ) ? dateArr[1] : dateArr[1].substring(1); // strip leading zeroes
	var month	= months[ month ];
	var day		= ( dateArr[2].indexOf("0") !== 0 ) ? dateArr[2] : dateArr[2].substring(1); // strip leading zeroes
	var year	= dateArr[0].substring(2);
	
	return month + ' ' + day + '/' + year;
}

function formatUnit (someUnit) {
	var units	= new Object();
	units["1"]		= "Unit 1";
	units["2"]		= "Unit 2";
	units["3"]		= "Unit 3";
	units["4"]		= "Unit 4";
	units["5"]		= "Unit 5";
	units["6"]		= "Unit 6";
	units["11101"]	= "11101";
	units["11103"]	= "11103";
	units["villa"]	= "Villa del Mar";
	
	return units[someUnit];
}

////////////////////////
// external functions //
////////////////////////

function switchPrices (e) {
	var ps			= document.getElementById('price_switcher');
	data.stayLength	= ps.options[ps.selectedIndex].value;
	makeRequest(data);
}

function makeRequest (data) {
	var stayLength	= (data.stayLength) ? data.stayLength : null;
	var unit		= (data.unit) ? data.unit : null;
	var postData	= "length=" + stayLength + "&unit=" + unit;

	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

// here's the HTML generator
function buildTable (dataObj) {
	// initialize some variables
	var wrapper				= document.getElementById('price_wrapper');
	var flag_stayLen_col	= false; // set to boolean true if rows should include this column
	var normal_stayLen		= ['Daily', '3 Days', 'Weekly']; // "normal" values for stayLen
	var row					= null;
	var col					= null;
	var txt					= null;
	var div					= null;

	// define some HTML elements
	var html_table			= document.createElement('table');
	var html_thead			= document.createElement('thead');
	var html_thead_tr		= document.createElement('tr');
	var html_tbody			= document.createElement('tbody');

	// define some arrays for later generation of HTML elements
	var html_thead_cols_arr	= new Array(); // each item in the array is a THEAD element
	var html_tbody_rows_arr	= new Array(); // each row represents a season, and each item in the array is TR element 

	// iterate through all the units
	var firstLoop = true; // set up a counter; there are some things we'll only need to do the first time through
	var ctr = 1; // used to apply different classes to different rows
	for (var unit in dataObj) {

		// add a column for this unit in the header
		col = document.createElement('th');
		txt	= document.createTextNode( formatUnit(unit) );
		col.appendChild(txt);
		html_thead_cols_arr.push(col);

		// iterate through all the seasons for the given unit
		for (season in dataObj[unit]) {

			// do this only the first time through the first season
			if (firstLoop == true) {

				/*
				 * determine if the "Longer" stay length is in use, in which we should
				 * flip a flag so that the rows we build have this column
				 */

				if ( !in_array(dataObj[unit][season].stayLen, normal_stayLen) ) {
					flag_stayLen_col = true;
				}
				firstLoop = false;
			}

			// check if this row (aka season) is already accounted for
			if (!html_tbody_rows_arr[season]) {
				row		= document.createElement('tr');
				row.className = (ctr++ % 2 == 0) ? "even" : "odd";				
				col		= document.createElement('td');
				
				// if the season has a label
				if (dataObj[unit][season].label) {
					div				= document.createElement('div');
					div.className	= 'season_label';
					txt				= document.createTextNode(dataObj[unit][season].label);
					div.appendChild(txt);
					col.appendChild(div);
				}
				
				// add the date range
				txt		= document.createTextNode( formatDate(dataObj[unit][season].start) + ' - ' + formatDate(dataObj[unit][season].end) );
				col.appendChild(txt);

				// add the TD to the TR
				row.appendChild(col);
				
				// add length of stay column if necessary
				if (flag_stayLen_col === true) {
					col = document.createElement('td');
					txt = document.createTextNode(dataObj[unit][season].stayLen);
					col.appendChild(txt);
					row.appendChild(col);
				}

				// add the TR to our array of rows, with the appropriate key
				html_tbody_rows_arr[season] = row;
			}

			col = document.createElement('td');
			col.className = "price";
			txt = document.createTextNode('$' + dataObj[unit][season].price);
			col.appendChild(txt);
			html_tbody_rows_arr[season].appendChild(col);
		}
	}
	
	// now that all of junk is built, let's add it to the table

	// create the "length of stay" column (if necessary) for the header row
	if (flag_stayLen_col === true) {
		col = document.createElement('th');
		txt	= document.createTextNode('Length of Stay');
		col.appendChild(txt);
		html_thead_cols_arr.unshift(col);
	}

	// create the left-most column for the header row
	col = document.createElement('th');
	col.className = "season_column";
	txt	= document.createTextNode('Rental Dates');
	col.appendChild(txt);
	html_thead_cols_arr.unshift(col);

	// add each thead to the tr in the thead
	for (t in html_thead_cols_arr) {
		html_thead_tr.appendChild(html_thead_cols_arr[t]);
	}
	
	// add the thead's tr to the thead
	html_thead.appendChild(html_thead_tr);
	
	// add the thead to the table
	html_table.appendChild(html_thead);
	
	// add each row to the tbody
	for (r in html_tbody_rows_arr) {
		html_tbody.appendChild(html_tbody_rows_arr[r]);
	}
	
	// add the tbody to the table
	html_table.appendChild(html_tbody);

	// check to see if table is already on the page, and if so, remove it
	if ( document.getElementById('price_table') ) {
		wrapper.removeChild( document.getElementById('price_table') );
	}
	
	// add the table to the page
	html_table.setAttribute("id", "price_table");
	wrapper.appendChild(html_table);
}