//****************************************************
//                         Global vars
//****************************************************
res = new Reservation();
G = new G();
navButtons = new ResNavButtons();
today = new Date();
maxSledWeight = 350;
maxCartWeight = 450;
maxScooterWeight = 300;

function loadRes()
{
   res.loadProgress();
   res.showProgress('newOrUsed');
   res.presetVals();
   res.showRiders();
   res.showMatchRiders();
   
   if(res.newOrUsed == 1) {
		// We were sent some values (possibly from a partial res), so advance a bit
	}
}

//****************************************************
//                         Object definitions
//****************************************************

//
//    Object that holds all the selected sleds in an array
//


// Functions that do some preprocessing on user actions
function serviceSelected() {
   var
      newService = getSelectValue('serviceSEL'),
      x = document.getElementById('servicePic');
   
	if(newService == "0") {
		x.src = '';
	} else {
		x.src = wroot + '/images/' + newService + '.jpg';
	}
   res.setResType(newService);
   res.showDescription('resDescription');
	changeView(1);
}

//*****************************************************************
//          Kennel Tour handling methods of the reservation object
//*****************************************************************

function addKT(ktID, day, time, adult, child, free)
{
   var
		i=0,
		ind = -1,
		l = this.kts.length;

   // See if this tour has already been selected
   for(i=0; i<l; i++) {
      if(this.kts[i].id == ktID) {
         ind = i;
         break;
      }
   }

   if(ind >= 0) {
      // Kennel tour with this id already selected.  Just update the counts
      this.kts[ind].adult = adult;
      this.kts[ind].child = child;
      this.kts[ind].free = free;
      this.kts[ind].cost = 15*adult + 8*child;
   } else {
      // Kennel tour with this id has not been selected yet.  Add it.
      this.kts.push(new ktObj(ktID, day, time, adult, child, free));
   }
}

function removeKT(i)
{
   this.kts.splice(i,1);
}

function resetSelectedKT()
{
   var
		i = 0,
		kt,
		l = this.kts.length;

   for(i = 0; i < l; i++) {
      kt = this.kts[i];
      setSelectValue('ktAdult'+kt.id, kt.adult);
      setSelectValue('ktChild'+kt.id, kt.child);
      setSelectValue('ktFreee'+kt.id, kt.free);
   }
}

function showSelectedKT()
{
   var
		i = 0,
		out = '',
		l = this.kts.length;
   
   for(i = 0; i < l; i++) {
      out += '<p><button type="button" onclick="removeKTour('+i+')">X</button>';
      out += this.kts[i].displayText();
   }
   
   if(out === '') {
      out = '<p>You have no kennel tours selected.</p>';
   }
   
   document.getElementById('selectedStuff').innerHTML = out;
}

//*****************************************************************
//          Sled handling methods of the reservation object
//*****************************************************************

function checkStoredSleds()
{
	var i = 0, x = null;
	
   for(i = 0; i < this.numSleds(); i++) {
      this.sleds[i].toggleDisplay(true);
   }
}

function getSledByIndex(i)
{
   return this.sleds[i];
}

function findSledIndex(id)
{
   var i = 0, found = false;

   for(i = 0; i < this.numSleds(); i++) {
      if(this.sleds[i].id == id) {
         found = true;
         break;
      }
   }

   return found ? i : -1;
}

function removeSled(oldSled)
{
   var i = this.findSledIndex(oldSled.id);

   if(i >= 0) {
      this.sleds.splice(i,1);
   }
}

function sortSleds(a, b)
{
   return ((a.id < b.id) ? -1 : ((a.id > b.id) ? 1 : 0));

}

function drawMatchSledsTable()
{
   var sledIndex = 0, seatIndex = 0, k = 0, output = '', remaining = 0, x;

   if(this.numSleds() === 0) {
      output = "<h1>No "+this.type+"s selected</h1>";
   } else {
      output = '<h1>Your ' + this.type + 's</h1>\n<dl class="seatSelection">';

      for(sledIndex = 0; sledIndex < this.numSleds(); sledIndex++) {
         output += "<dt id=\"m" + this.sleds[sledIndex].id + "\">" + G.capitalize(this.type) + " " + (sledIndex + 1)  + ": " + this.sleds[sledIndex].sdate + " at " + this.sleds[sledIndex].stime + "</dt>";
         if(this.sleds[sledIndex].weight === 0) {
            output += "<dd>There are no riders in this "+this.type+".  Add up to 3 people and " + this.maxWeight + " pounds.</dd>";
         } else {
            remaining = this.maxWeight - this.sleds[sledIndex].weight;
            output += "<dd>Cost: $" + this.sleds[sledIndex].cost + ".  Weight: " + this.sleds[sledIndex].weight + " pounds.  You have "+remaining+" pounds left.</dd>";
         }

			// Draw sled (in a table format)
         output += "<table class='sledSeating'><tr><th>Seat 1</th><th>Seat 2</th><th>Seat 3</th></tr><tr>";
         for(seatIndex = 0; seatIndex < 3; seatIndex++) {
            k = seatIndex + 1;
            if(this.sleds[sledIndex].seats[seatIndex]) {
               output += "<td class=\"sledStatus1\" id=\"seat" + seatIndex + sledIndex + "\" onclick=\"res.unSeatRider('"+this.sleds[sledIndex].seats[seatIndex]+"')\">" + this.sleds[sledIndex].seats[seatIndex].substring(2) + "</td>";
            } else {
               output += "<td class=\"pointer\" onclick=\"highlightSeat(" + sledIndex + ", " + seatIndex + ");res.showMatchRiders(" + sledIndex + ")\" id=\"seat" + seatIndex + sledIndex + "\" value=\""+seatIndex+this.sleds[sledIndex].id+"\">Empty</td>";
            }
         }
         output += "</tr></table>";
      }
      output += "</dl>";
   }

   x = document.getElementById("matchSledsDIV");
   x.innerHTML = output;
}

function highlightSeat(sledIndex, seatIndex)
{
	var x = null;
	
	if(res.selectedSeat) {
		x = document.getElementById('seat' + res.selectedSeat);
		if(x) {
			x.className = "pointer";
		}
	}

	x = document.getElementById('seat' + seatIndex + sledIndex);

	if(x) {
		x.className = "sledStatus0";
	}

	res.selectedSeat = '' + seatIndex + '' + sledIndex + '';
}

function allSledsFull()
{
   var i = 0, result = true;

   if(this.numSleds() > 0) {
      for(i = 0; i < this.numSleds(); i++) {
         if(!this.sleds[i].seats[0] && !this.sleds[i].seats[1] && !this.sleds[i].seats[2]) {
            result = false;
         }
      }
   } else {
      result = false;
   }

   return result;
}

//*****************************************************************
//          Review tab handling methods
//*****************************************************************

function showKTReview()
{
   var i = 0, l = this.kts.length, out = this.resInfoText();
   
   this.totCost = 0;
   out += '<h1>Please review your kennel tour selection</h1>\n';
   out += '<table cellspacing="0" cellpadding="0" class="reviewTable">';
   for(i = 0; i<l; i++) {
      this.totCost += this.kts[i].cost;
      out += '<tr><th>'+this.kts[i].displayText()+'</th></tr>';
   }
   out += '</table>';
   out += this.resInfoFooter();
   document.getElementById("resReviewDIV").innerHTML = out;
}

function showSledReview()
{
   var out = '', i = 0;

   if(res.allRidersSeated() && res.allSledsFull()) {
      res.totCost = 0;
      out += this.resInfoText();
      out += '<h1>Please review your '+this.type+' information</h1>';
      out += '<table cellspacing="0" cellpadding="0" class="reviewTable">';
      var num = res.numSleds();
      for(i = 0; i < num; i++) {
         res.totCost += res.sleds[i].cost;
         out += '<tr><th>'+res.sleds[i].riderNameText()+' riding on '+res.sleds[i].sdate+' at '+res.sleds[i].stime+' weighing '+res.sleds[i].weight+' and costs $'+res.sleds[i].cost+'</th></tr>';
      }
      out += '</table>';
      out += this.resInfoFooter();
      document.getElementById("resReviewDIV").innerHTML = out;
   } else {
      if(!res.allRidersSeated()) {
         alert('Not all of your riders have been seated.  Please put each rider in a seat.');
      } else if(!res.allSledsFull()) {
         alert('Not all of your sleds have riders.  Please put at least one rider in each sled.');
      }
   }
}

function resInfoText()
{
   var output = '<p class="c"><button class="bigButt" type="button" onclick="doResHold()">Make Reservation</button></p>';
   output += '<h1>Please review your contact information</h1>\n';
   output += '<table cellspacing="0" cellpadding="0" class="reviewTable">';
   output += '<tr><th>Reservation Name:</th><td>'+this.name+'</td></tr>';
   output += '<tr><th>Traveling from Denver:</th><td>';
   output += (this.travelDay) ? "Yes" : "No";
   output += '</td></tr>';
   output += '<tr><th>Confirmed email address:</th><td>'+this.email+'</td></tr>';
   output += '<tr><th>Mobile Phone Number:</th><td>'+this.mobilePhone+'</td></tr>';
   output += '<tr><th>Local Phone Number:</th><td>'+this.localPhone+'</td></tr>';
   output += '<tr><th>Lodging:</th><td>'+this.lodgingText+'</td></tr>';
   if(this.affCode) { output += '<tr><th>Referral Code:</th><td>'+this.affCode+'</td></tr>'; }
   output += '<tr><th>Optional Comment:</th><td>'+this.comment+'</td></tr>';
   output += '</table>';

   return output;
}

function resInfoFooter()
{
   var output = '</ol></li>';
   output += '<li>The total cost of this reservation is $'+this.totCost+'</li>';
   output += '<p class="c"><button class="bigButt" type="button" onclick="doResHold()">Make Reservation</button></p>';
   output += '<br />(If your reservation details are not correct, go back to the appropriate section and make your changes.)';

   return output;
}

function getRiderByIndex(i)
{
   return this.riders[i];
}

function addRider(newRider)
{
   this.riders.push(newRider);
   this.riders.sort(this.sortRiders);
}

function removeRider(i)
{
   this.riders.splice(i,1);
}

function sortRiders(b, a)
{
   return ((a.rweight < b.rweight) ? -1 : ((a.rweight > b.rweight) ? 1 : 0));

}

function showRiders()
{
   var
		x = null,
		i = 0,
		output = '',
		num = this.numRiders(),
		num2 = this.numSleds();

   if(num === 0) {
      //      output = "<h1>You have no riders entered.</h1>";
      output = "";
   } else {
      output = "<h1>You have " + num + " rider";
		if(num > 1) {
			output += "s";
		}
      output += " entered.</h1><br /><br />";

      if(num < num2) {
         output += '<h2>You have ' + num2 + ' ' + this.type + 's selected, so you need to enter at least ' + (num2 * 1 - num) + ' more riders</h2>';
      } else {
         output += '<h2>Enter more riders or click the continue button above.</h2>';
      }

      output += '<br /><br /><table cellspacing="0" cellpadding="0"><tbody>';
      output += "<tr><th>Name</th><th>Weight (pounds)</th><th>Height</th><th>Age</th><th>&nbsp;</th></tr>";

      for(i = 0; i < this.numRiders(); i++) {
         output += "<tr><th>" + this.riders[i].rname + "</th><td>" + this.riders[i].rweight + "</td><td>" + this.riders[i].rheightText + "</td><td>" + this.riders[i].rageText + "</td>";
         output += '<td><button onclick="doRemoveRider('+i+')" type="button">Remove ' + this.riders[i].rname + '</button></td></tr>';
      }

      output += "</tbody></table>";
   }

   x = document.getElementById("viewRiderDIV");
   x.innerHTML = output;
}

function showMatchRiders(sledIndex)
{
   var output = '', i = 0, limit = 0, rows = '';

   if(this.numRiders() === 0) {
      output = "<h1>Enter rider info and press Add Rider</h1>";
   }
   else {
      limit = calculateWeightLimit(sledIndex);
      rows = '';                         // string for the table rows of unseated riders
      output = '<table cellspacing="0" cellpadding="0"><tbody>';
      output += "<tr><th>&nbsp;</th><th>Name</th><th>Weight (pounds)</th><th>Height</th><th>Age</th></tr>";

      for(i = 0; i < this.numRiders(); i++) {
         if(!this.riders[i].sledID) {
            if(this.riders[i].rweight <= limit) {
               rows += '<tr><td><button onclick="res.seatRider(' + i + ')" type="button">&lt;-Seat ' + this.riders[i].rname + '</button></td>';
            } else {
               rows += '<tr><td>&nbsp;</td>';
            }
            rows += "<th>" + this.riders[i].rname + "</th><td>" + this.riders[i].rweight + "</td><td>" + this.riders[i].rheightText + "</td><td>" + this.riders[i].rageText + "</td></tr>";
         }
      }

      if(!rows) {
         output = "<h1>All riders have been seated</h1>";
         output += '<p>Click "Continue" above to move to the next section</p>';
      } else {
         output += rows + "</tbody></table>";
      }
   }

   var x = document.getElementById("matchRidersDIV");
   x.innerHTML = output;
}

function allRidersSeated()
{
   var i = 0, result = true;

   if(this.numRiders() > 0) {
      for(var i = 0; i < this.numRiders(); i++) {
         if(!this.riders[i].sledID) {
            result = false;
         }
      }
   } else {
      result = false;
   }

   return result;
}

function seatRider(riderIndex)
{
   var rider = null, sled = null, seatIndex = 0, sledIndex = 0;

   if(res.selectedSeat) {
      rider = this.riders[riderIndex];

      // Extract hidden info from checked radio buttons value
      seatIndex = res.selectedSeat.substr(0,1);
      sledIndex = res.selectedSeat.substr(1);
      sled = this.getSledByIndex(sledIndex);

      sled.seats[seatIndex] = rider.id;
      rider.sledID = sled.id;

      sled.weight += rider.rweight;
      sled.updateSledCost(this.affCode, sledIndex);
		this.sortSeats(sledIndex);

      this.drawMatchSledsTable();
      this.showMatchRiders();
      this.showDescription('resDescription');
   } else {
      alert('You must select a sled seat before seating a rider.');
   }
}

function unSeatRider(riderID)
{
   var
		j = {}, sled = {}, k = 0,
		i = this.findRiderIndex(riderID),
		rider = this.getRiderByIndex(i);

   if(rider.sledID) {
      j = this.findSledIndex(rider.sledID);
      sled = this.getSledByIndex(j);

      k = sled.seats[0] == rider.id ? 0 : (sled.seats[1] == rider.id ? 1 : 2);
      sled.seats.splice(k,1);
      sled.seats[2] = '';
      sled.weight -= rider.rweight;
      sled.updateSledCost(this.affCode, j);      
		this.sortSeats(j);
   }

   rider.sledID = '';

   this.drawMatchSledsTable();
   this.showMatchRiders();
   this.showDescription('resDescription');
}

function loadProgress()
{
   this.progress.push(new infoObj('newOrUsed',    'New/existing Reservation',   'newOrUsed', false, 'If this is your first time visiting the site, choose new reservation.  If you have already made a reservation and just want to see the details, select existing reservation.'));

   this.progress.push(new infoObj('service',    'Service',   'service', false, 'Pick one of our services.  We offer winter sled rides when snow is on the ground, cart rides when the ground is dry, and kenel tours most of the year.'));

   this.progress.push(new infoObj('resName',    'Reservation Name',   'contact', false, 'The name associated with the reservation.  This could be the name of the organizor, or something like "The Martin Family"'));
   this.progress.push(new infoObj('mobilePhone','Mobile Phone',       'contact', false, 'Your mobile telephone number.  Please include your area code.  We can not accept international numbers.'));
   this.progress.push(new infoObj('lodging',    'Lodging',            'contact', false, 'Where you are staying during your visit to Winter Park.'));
   this.progress.push(new infoObj('localPhone', 'Local Phone',        'contact', false, 'The phone number where you are staying locally.  Use your mobile phone number if you are coming up for the day or do not know your local number.  The local area code is (970)'));
   this.progress.push(new infoObj('travelDay',  'Travel Day',         'contact', true,  'If you are traveling to us from Denver or similar locations, you will travel over Berthoud Pass.  The pass is sometimes closed, so we want to know whether to fill your spot with wait-list customers when the pass is closed.'));
   this.progress.push(new infoObj('comment',    'Special Notes',      'contact', true,  'Any special instructions you may have for us, like if you are pregnant or if anyone has disabilities requiring special care.'));
   this.progress.push(new infoObj('affCode',    'Referral Code',      'contact', true,  'Optional.  If you do not have or do not know what a referral code is, leave this field empty.'));
   this.progress.push(new infoObj('emailAddr',  'Email Address',      'contact', false, 'It is important that our system be able to commincate with you via email.  Please enter your email address.'));
   
   this.progress.push(new infoObj('mBeginDate,dBeginDate,yBeginDate','Begin Date','date', false, 'Enter the date you want to begin looking for availability.  This is usually your arrival date into Grand County.  Please use the month/day/year date format.'));
   this.progress.push(new infoObj('mEndDate,dEndDate,yEndDate',      'End Date',  'date', false, 'Enter the date you want to see availability through.  This is usually your departure date from Grand County.  Please use the month/day/year date format.'));
   this.progress.push(new infoObj('checkAvButt',      'Check Availability',  'date', false, 'Press the "Check Availability" button to see sleds available during your stay.  The two dates you enetered are sent to the server, and it returns a list of days and sleds.'));
   this.progress.push(new infoObj('pickAvailable',      'Pick Sleds',  'date', false, 'Click on available sleds to add them to your reservation.  A sled is available if it is green and says "Available".  Once selected it is orange and says "Selected".  Most sleds can hold two people, so initially pick one sled for every two people in your group.'));
   this.progress.push(new infoObj('ktAdult', 'Number of adults',                  'date', false, 'Enter the number of people in your party who are 13 years old or older. (For kennel tours only.)'));
   this.progress.push(new infoObj('ktChild', 'Number of children',                'date', false, 'Enter the number of children in your party who are between the ages of 4 and 12.  (For kennel tours only.)'));
   this.progress.push(new infoObj('ktFree',  'Number of toddlers',                'date', false, 'Enter the number of children in your party who are 3 years old or younger.  (For kennel tours only.)'));

   this.progress.push(new infoObj('reviewButt', 'Review reservation', 'review', false, 'Click the button to see a summary of your reservation.  You do not have a reservation yet.'));

   this.progress.push(new infoObj('pay', 'Payment', 'pay', false, 'Fill in the form to make your payment.'));

   this.progress.push(new infoObj('riderName',   'Rider Name',   'riders', false, 'We are pretty casual around here, so just enter the first name for each rider.'));
   this.progress.push(new infoObj('riderWeight', 'Rider Weight', 'riders', false, 'Weigh yourself at home in your winter gear, or add 5 to 15 pounds to your bathroom weight to get your winter sled riding weight.'));
   this.progress.push(new infoObj('weightUnits', 'Weight Units', 'riders', true, 'Choose the units for the weight you entered.  We will convert your weight to pounds.'));
   this.progress.push(new infoObj('riderHeight', 'Rider Height', 'riders', true, 'Choose either taller than or shorter than 48 inches.'));
   this.progress.push(new infoObj('riderAge',    'Rider Age',    'riders', true, 'Choose the appropriate age for each rider.  The cost of the sled is determined by the ages of the riders.'));

   this.progress.push(new infoObj('sledSeat', 'Seat Riders', 'match', true, 'Each sled is represented by a table with three empty seats. When you click one of the empty seats, all of the riders that can fit in that seat will have a seating button.  Click the button of the rider you want to put in that seat. Continue until all sled have at least one person, and all riders have been seated.'));

   this.progress.push(new infoObj('resID',    'Reservation ID', 'login', false, 'This is the reservation ID that was generated when you made your reservation.  Check the email we sent to confirm your reservation.'));
   this.progress.push(new infoObj('resEmail', 'Email Address',  'login', false, 'Enter the email address you entered when you made your reservation.  This is kind of like your password for accessing your reservation details.'));

   this.progress.push(new infoObj('resDump', 'Help! I\'m Stuck!',  'all', false, 'If you are having trouble with your reservation, and already have some information entered, <button type="button" onclick="resDump()">click here</button> to submit your partial reservation to one of our experts.  We will try to complete your reservation for if.  If we have any questions, we will call the number listed in the contact info view.  If everything looks OK, and we are able to complete the reservation, you will receive a confirmation via email.'));
}

function showProgress(group)
{
   var o = '<dl class="progress">';
   var l = this.progress.length;

   if(l > 0)
   {
      for(var i=0; i<l; i++)
      {
         if(this.progress[i].group == group)
         {
            o += '<dt><button type="button" onclick="showDD(\''+this.progress[i].id+'PDD\')">?</button>'+this.progress[i].name+'</dt>';
            o += '<dd id="'+this.progress[i].id+'PDD">'+this.progress[i].helpText+'</dt>';
         }
      }
   
      o += '<dt><button type="button" onclick="showDD(\''+this.progress[l-1].id+'PDD\')">?</button>'+this.progress[l-1].name+'</dt>';
      o += '<dd id="'+this.progress[l-1].id+'PDD">'+this.progress[l-1].helpText+'</dt>';
   }

   o += '</dl>';
   var x = document.getElementById('progress');
   if(x) { x.innerHTML = o; }
}

//
// Function:   toggleProgress(id, state)
// Usage:      Called when an input field is changed.  Changes label text class to complete or incomplete
//    Also checks to see if all other input fields in this group are complete.  If so, changes label of group.
//
function toggleProgress(id, state)
{
   var x;
   var groupName = '';
   var groupComplete = true;
   var len = this.progress.length;

   // find the infoObj with the provided id and change the label.  also remember what group it is in
   for(var i = 0; i < len; i++)
   {
      if(this.progress[i].id == id)
      {
         this.progress[i].complete = state;
         x = document.getElementById(id+'Label');
         if(x) { x.className = state ? "complete" : "incomplete"; }
         groupName = this.progress[i].group;
         break;
      }
   }

   // Check to see if the group is complete
   for(i = 0; i < len; i++)
   {
      if(this.progress[i].group == groupName)
      {
         if(!this.progress[i].complete)
         {
            groupComplete = false;
            break;
         }
      }
   }

   if(groupName == 'contact')
   {
      // If the group is complete show it's next button
      x = document.getElementById('contactNextDIV');
      if(x)
      {
         x.style.display = groupComplete ? "block" : "none";
         x = document.getElementById(groupName+'NextButt');
         if(x && groupComplete) { x.focus(); }
      }
   }
}

function presetVals()
{
	var sledDate = '';
	
   loadValues();

   if(res.affCode) {
      document.getElementById('affCode').value = res.affCode;
   } else {
      res.affCode = document.getElementById('affCode').value;
   }

	if(res.newOrUsed > 0) {
		setSelectValue('newOrUsedSEL', res.newOrUsed);
		changeView(1);
	}
	
	if(res.type !== '') {
		setSelectValue('serviceSEL', res.type);
		serviceSelected();
	}

	if(res.numSleds() > 0 || res.day != '') {
		if(res.day != '') {
			sledDate = res.day;
		} else {
			sledDate = res.sleds[0].id;
		}
		setSelectValue('mBeginDate', sledDate.substr(5,2) * 1 + '');
		setSelectValue('mEndDate', sledDate.substr(5,2) * 1 + '');
		setSelectValue('dBeginDate', sledDate.substr(8,2) * 1 + '');
		setSelectValue('dEndDate', sledDate.substr(8,2) * 1 + '');
		setSelectValue('yBeginDate', sledDate.substr(0,4));
		setSelectValue('yEndDate', sledDate.substr(0,4));
		showAvailability();
		if(res.numSleds() > 0) {
			changeView(1);
		}
	}
	
   document.getElementById('resName').value = res.name;
   document.getElementById('emailAddr').value = res.email;
   document.getElementById('mobilePhone').value = res.mobilePhone;
   document.getElementById('localPhone').value = res.localPhone;
   setSelectValue("lodging", res.lodging + ";" + res.localPhone);
   document.getElementById('comment').value = res.comment;
   document.getElementById('travelDay').checked = res.travelDay;
   
   // Special Groupon processing
   if(res.affCode.substr(0, 7) == "GROUPON") {
		if(res.comment == '') {
			document.getElementById('comment').value = "Enter your Groupon code here.";
		}
	}
	res.drawMatchSledsTable();
	res.showMatchRiders();
}

//****************************************************************
//                Kennel Tour object
//****************************************************************

function ktObj(id, day, time, a, c, f)
{
   this.id = id;
   this.day = day;
   this.time = time;
   this.adult = a;
   this.child = c;
   this.free = f;
   this.cost = 15*a + 8*c;

   this.displayText = displayText;
}

function displayText()
{
   var out = this.day+' at '+this.time+' for ';
   out += this.adult+' adults, '+this.child+' children and '+this.free+' toddlers.  ';
   out += 'Total cost is $'+this.cost+'</p>';

   return out;
}


//
//    Rider object
//
function riderObj(rname, rweight, rheightID, rheightText, rageID, rageText)
{
   this.id = rageID + rheightID + rname;
   this.rname = rname;
   this.rweight = rweight;
   this.rheightID = rheightID;
   this.rheightText = rheightText;
   this.rageID = rageID;
   this.rageText = rageText;
   this.sledID = '';
}

//
// Info object
//
function infoObj(id, name, group, state, help)
{
   this.id = id;
   this.name = name;
   this.complete = state;
   this.group = group;
   this.helpText = help;
}

//****************************************************
//                         Functions
//****************************************************

// This function sends all the data from the res object via email
function resDump()
{
   var args = 'q=rd&o=html';

   args += makeResArgs();

   asProcess(wroot + '/reservations/dispatch.php', args, 'Fetching reservation...', handleDump, "sugarBum");
}

function handleDump()
{
   if(xmlHttp.readyState == 4)

   {
      alert("You do not have a reservation.  Your incomplete information was sent to us, but you need to call during business hours to complete your reservation.");
   }
}

function changeView(direction)
{
   var x, newOrUsed, msg = {};

   if(direction < 0) {
      if(navButtons.currentView == 'review') {
			resetReview();
		}
      navButtons.goBack();
   } else {
      switch(navButtons.currentView) {
         case 'newOrUsed' :
            newOrUsed = getSelectValue('newOrUsedSEL') * 1;
            res.reset();
				res.newOrUsed = newOrUsed;
            switch (newOrUsed) {
               case 0:     // No selection made
                  alert('Please choose new or existing reservation');
                  break;
               case 1:     // New selected
                  navButtons.goForward('service');
						res.showProgress('service');
                  break;
               case 2:     // Existing selected
						if (typeof(localStorage) != undefined) {
							document.getElementById('resID').value = localStorage.getItem('resID');
							document.getElementById('resEmail').value = localStorage.getItem('resEmail');
						}
                  // Try to find some stored info then go to login
                  navButtons.goForward('login');
						res.showProgress('login');
                  break;
            }
            break;
         case 'service' :
            // Change the picture on the left to match the service
            res.setResType(getSelectValue('serviceSEL'));
            if (res.type === '') {
               alert('Please choose a service.');
            } else {
					if(res.type == 'cart') {
						res.maxWeight = maxCartWeight;
                  G.hide("sledRiderTypes");
                  G.show("cartRiderTypes");
					} else if(res.type == 'scooter') {
                  G.hide("sledRiderTypes");
                  G.show("cartRiderTypes");
						res.maxWeight = maxScooterWeight;
					} else {
                  G.show("sledRiderTypes");
                  G.hide("cartRiderTypes");
						res.maxWeight = maxSledWeight;
					}
					document.getElementById('avCalendar').innerHTML = '';
					navButtons.goForward('date');
					res.showProgress('date');
            }
            break;
			case 'date' :
				if (res.numKTs() + res.numSleds() == 0) {
               alert('Please choose a ' + res.type + '.  Enter your vacation dates, press check availability, click an available time.');
            } else {
               navButtons.goForward('contact');
					res.showProgress('contact');
            }
				break;
			case 'contact' :
				validateContactView(msg);
            if(msg.msg === '') {
					navButtons.goForward('riders');
					res.showProgress('riders');
				} else {
					alert(msg.msg);
				}
				break;
			case 'riders' :
				if(res.numRiders() < res.numSleds()) {
					alert("You have more " + res.type + "s on hold than riders entered.  Go back to remove a " + res.type + ", or add more riders.");
				} else if(res.numRiders() > 3 * res.numSleds()) {
					alert("You have too many riders entered.  Go back to add a " + res.type + ", or remove riders.");
				} else {
					navButtons.goForward('match');
					res.showProgress('match');
				}
				break;
			case 'match' :
				if(!res.allRidersSeated()) {
					alert("NOT all of the riders have been seated.  Place the unseated riders in seats, or go back to add a " + res.type + " if you do not have enough seats available.");
				} else if(!res.allSledsFull()) {
					alert("NOT all " + res.type + "s have at least one rider.  Spread out your riders so that at least one rider is in each " + res.type + ", or go back to add more riders or remove " + res.type + "s.");
				} else {
					navButtons.goForward('review');
					res.showProgress('review');
				}
				break;
			case 'review' :
				if(res.resID) {
					navButtons.goForward('pay');
					res.showProgress('pay');
				} else {
					alert("You do not have a reservation yet.  Click the 'make reservation' button to send your data to the server.");
				}
				break;
         case 'login':
				if(res.resID) {
					navButtons.goForward('loginReview');
				} else {
					alert('You must login to review your reservation');
				}
            break;
         case 'loginReview':
				navButtons.goForward('pay');
            break;
         default:
            break;
      }
   }

   // Update the description of the reservation
   res.showDescription('resDescription');
}

function setEndDate(obj)
{
   var id2 = obj.id.substring(0,1) + 'EndDate';
   var val = getSelectValue(obj.id);

   setSelectValue(id2, val);
}

function setTheYear(obj)
{
   var val = getSelectValue(obj.id);

   if(val < (today.getMonth() + 1))
   {
      setSelectValue('yBeginDate', today.getFullYear() + 1);
      setSelectValue('yEndDate',   today.getFullYear() + 1);
   }
   else
   {
      setSelectValue('yBeginDate', today.getFullYear());
      setSelectValue('yEndDate',   today.getFullYear());
   }
}

function validateContactView(msg) {
	msg.msg = '';
	
	if(res.name === '') {
		msg.msg += '* A reservation name is required.\n\n';
	}
	if(res.mobilePhone === '' ) {
		msg.msg += '* A mobile phone is required.  Use your home phone if you do not have a mobile phone.\n\n';
   }
   if(res.lodging == '') {
		msg.msg += '* A lodging option is required.\n\n';
	}
   if(res.localPhone === '') {
		msg.msg += '* A local phone is required. Use your mobile phone if you do not know your local phone.\n\n';
	}
	if(res.email === '') {
		msg.msg += '* An email address is required.  Use an email address of someone else in the group if you do not have one.\n\n';
   }

	return false;
}

function validateEntry(x)
{
   var val = x.value;
   var allowed = '';

   switch(x.id)
   {
      case 'resName' :
      case 'riderName' :
         allowed = "abcdefghijklmnopqrstuvwxyz 0123456789";
         val = validateInput(x.id, val, allowed);
         break;
      case 'comment' :
         allowed = "abcdefghijklmnopqrstuvwxyz 0123456789.,-_()[]*@!";
         val = validateInput(x.id, val, allowed);
         break;
      case 'affCode' :
         allowed = "abcdefghijklmnopqrstuvwxyz0123456789";
         val = validateInput(x.id, val.toUpperCase(), allowed);
         break;
      case 'emailAddr' :
      case 'resEmail' :
         allowed = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
         val = validateInput(x.id, val, allowed);
         break;
      case 'mobilePhone' :
      case 'localPhone' :
         val = makePhoneNumber(val);
         x.value = val;
         if(val.length != 14) { alert('Phone number does not appear valid'); }
         break;
      case 'riderWeight' :
         allowed = "0123456789.";
         val = validateInput(x.id, val, allowed);
         break;
		case 'travelDay' :
			val = x.checked ? 1 : 0;
			break;
      default:
         break;
   }

   // toggle the progress of this input and possibly the group
   var state = val ? true : false;
   res.toggleProgress(x.id, state);

   // Save the new value to the res object
   switch(x.id)
   {
      case 'resName' :
         res.name = val;
         break;
      case 'mobilePhone' :
         res.mobilePhone = val;
         break;
      case 'localPhone' :
         res.localPhone = val;
         break;
      case 'comment' :
         res.comment = val;
         break;
      case 'affCode' :
         res.affCode = val;
         break;
      case 'travelDay' :
         res.travelDay = val;
         break;
      case 'emailAddr' :
			res.email = val;
			break;
      default:
         break;
   }

   res.showDescription('resDescription');
   // Reservation info has changed, so reset the review button
//   resetReview();
}

function formatResID(x)
{
   var nums = '0123456789';
   var val = x.value;
   var new_val = '';
   var c = '';
   var l = Math.min(val.length, 12);
   
   // Step through each character of the input value
   // 012345678901
   // 9999-99-9999
   for(var i = 0; i < l; i++)
   {
      c = val.charAt(i)+'';
      // Check to see if the character is in the allowed string
      if((i == 4) || (i == 7))
      {
         if(c == '-') { new_val += c; }
      }
      else
      {
         if(nums.indexOf(c) >= 0)
         {
            new_val += c;     // Append char to the end of the new value if legal
         }
      }
   }

   if((new_val.length == 4) || (new_val.length == 7))
   {
      new_val += '-';
   }

   // Put the new value in the input field
   x.value = new_val;
}

function showWeightAlert()
{
   if(!res.weightInstructions)
   {
      if(res.type == 'sled')
      {
         alert('Be sure to provide an accurate weight.  Add 5 to 15 pounds to your "bathroom weight" to account for winter clothing.\n\nIf you show up over the weight limit ('+res.maxWeight+' pounds per sled), one of the following will apply:\n   1. We will be unable to take you for your ride (Please see our cancellation policy)\n   2. One or more persons in your party will not be able to ride.\n   3. If we feel it is safe to accommodate your weight, you will be charged $1 per pound that you are over our current weight limit.');
      }
      else if(res.type == 'cart')
      {
         alert('Be sure to provide an accurate weight.\n\nIf you show up over the weight limit ('+res.maxWeight+' pounds per cart), one of the following will apply:\n   1. We will be unable to take you for your ride (Please see our cancellation policy)\n   2. One or more persons in your party will not be able to ride.\n   3. If we feel it is safe to accommodate your weight, you will be charged $1 per pound that you are over our current weight limit.');
      }
      else
      {
         alert('Be sure to provide an accurate weight.\n\nIf you show up over the weight limit ('+res.maxWeight+' pounds per scooter), one of the following will apply:\n   1. We will be unable to take you for your ride (Please see our cancellation policy)\n   2. If we feel it is safe to accommodate your weight, you will be charged $1 per pound that you are over our current weight limit.');
      }

      res.weightInstructions = true;

      // This is not working.  Why not?
      document.getElementById('riderWeight').focus();
   }
}

//******************************************************
//             Availability Functions
//******************************************************
function showAvailability()
{
   var beginDate = getSelectValue('mBeginDate')+'/'+getSelectValue('dBeginDate')+'/'+getSelectValue('yBeginDate');
   var endDate = getSelectValue('mEndDate')+'/'+getSelectValue('dEndDate')+'/'+getSelectValue('yEndDate');
   var args = "q=av"+res.type+"&o=html&bd="+beginDate+"&ed="+endDate;
   var msg = 'Fetching ' + res.type + 's .....';

   asProcess(wroot + '/reservations/dispatch.php', args, msg, handleAvailability, "avCalendar");
}

function handleAvailability()
{
   if(xmlHttp.readyState == 4)
   {
      document.getElementById("avCalendar").innerHTML = xmlHttp.responseText;
      switch(res.type)
      {
         case 'kt' :
            res.resetSelectedKT();
            break;
         case 'cart' :
         case 'scooter' :
         case 'sled' :
            res.checkStoredSleds();
            break;
         default:
            break;
      }
   }
}

//******************************************************
//             Kennel Tour Functions
//******************************************************

function tourSelect(x)
{
   var ktID = x.id.substring(7);

   // Get number of each type of guest; cost
   var adult = getSelectValue('ktAdult'+ktID) * 1;
   var child = getSelectValue('ktChild'+ktID) * 1;
   var free  = getSelectValue('ktFreee'+ktID) * 1;
   var day = document.getElementById("ktDay"+ktID).innerHTML;
   var time = document.getElementById("ktTime"+ktID).innerHTML;

   res.addKT(ktID, day, time, adult, child, free);
   res.showSelectedKT();
   resetReview();
}

function removeKTour(i)
{
   var ktID = res.kts[i].id;

   setSelectValue('ktAdult'+ktID, 0);
   setSelectValue('ktChild'+ktID, 0);
   setSelectValue('ktFreee'+ktID, 0);

   res.removeKT(i);
   res.showSelectedKT();
}

//******************************************************
//             Sled Functions
//******************************************************

function toggleSled(ent, entType)
{
   // entType is either a checkbox id, or an array index
   var sled;
   var state;

   switch(entType)
   {
      case "id":
         // We have a checkbox id
         var x = document.getElementById(ent);
         sled = new Sled(ent);
         if(x) {
				state = x.className == 'sledStatus0';
			} else {
				state = true;
			}
         break;
      case "index":
         // We have an index into the sledArray
         sled = res.getSledByIndex(ent);
         // Since we have an index into the sled array, the sled necessarily exists, so we are toggling it false
         state = false;
         break;
      default:
         break;
   }

   sled.toggle(state);

   res.showDescription('resDescription');
   res.drawMatchSledsTable();
}

function changeLodge(xs)   // x is the select DOM object
{
   // The value of the lodging options is lodgingID;lodgingPhoneNumber
   // Extract these values and save them to appropriate places.

   var xo = xs.options[xs.selectedIndex];

   if(xo.value != 'noselection') {
      res.toggleProgress("lodging", true);
      res.lodgingText = xo.text;
      var a = xo.value.split(";");
      res.lodging = a[0];

      if(a[1] === '') {
         a[1] = document.getElementById("mobilePhone").value;
      }

      document.getElementById("localPhone").value = a[1];
      res.localPhone = a[1];

      res.toggleProgress("localPhone", a[1]);
   } else {
      res.toggleProgress('lodging', false);
      res.toggleProgress('localPhone', false);
      document.getElementById("localPhone").value = '';
      res.localPhone = '';
      res.lodging = '';
      res.lodgingText = '';
   }
}


function calculateWeightLimit(sledIndex)
{
   var limit = 0, x = null, sled = null;

	x = document.getElementById('seat1' + sledIndex);
   if(x) {
      sled = res.getSledByIndex(sledIndex);
      limit = res.maxWeight - sled.weight;
   }

   return limit;
}

//******************************************************
//             Login Tab Functions
//******************************************************

function login()
{
   var args = 'q=l&o=xml';
   args += '&r=' + document.getElementById('resID').value;
   args += '&e=' + document.getElementById('resEmail').value;

   asProcess(wroot + '/reservations/dispatch.php', args,'Fetching reservation...', handleLogin, "loginResultsDIV");
}

function handleLogin()
{
   if(xmlHttp.readyState == 4) {
      var 
			errorCount = 1, errorMessage = '',
			message = '', xmlDoc = xmlHttp.responseXML;

		if(xmlDoc) {
			errorCount = xmlDoc.getElementsByTagName("errorCount")[0].childNodes[0].nodeValue * 1;
			if(errorCount > 0) {
				errorMessage = xmlDoc.getElementsByTagName("errorText")[0].childNodes[0].nodeValue;
			}
		} else {
			errorMessage = 'Server did not return valid xml';
		}

      if(errorCount > 0) {
			document.getElementById("loginResultsDIV").innerHTML = '<h1>' + errorMessage + '</h1>';
      } else {
         res.resID = xmlDoc.getElementsByTagName("resID")[0].childNodes[0].nodeValue;
         res.email = xmlDoc.getElementsByTagName("email")[0].childNodes[0].nodeValue;
         res.totCost = xmlDoc.getElementsByTagName("balance")[0].childNodes[0].nodeValue * 1;
			message += "<p>Unpaid balance: $ " + res.totCost + "</p>";
			if(res.totCost > 0) {
				message += "<p>Click continue above to go to the payment view.</p>";
			}
			message += "<h2>I know there is not much info.  I'll fix this in an upcoming release.</h2>";
			updatePaymentForm();
         document.getElementById("item_number").value = res.resID;
			res.showDescription('loginReviewResultsDIV');
         document.getElementById("loginReviewResultsDIV").innerHTML += message;
			document.getElementById("loginResultsDIV").innerHTML = '<h1>Reservation located</h1><h2>Click continue to see your reservation details.</h2>';
			changeView(1);
      }

//      document.getElementById("loginReviewDIV").innerHTML = '<h1>'+message+'</h1>';
   }
}

//******************************************************
//             Review Tab Functions
//******************************************************

function resetReview()
{
   document.getElementById("resReviewDIV").innerHTML = '<button onclick="showResReview()" type="button" id="reviewButt">Click to review your reservation details</button>';
}

function showResReview()
{
   switch(res.type)
   {
      case 'kt' :
         res.showKTReview();
         break;
      case 'cart' :
      case 'scooter' :
      case 'sled' :
         res.showSledReview();
         break;
      default:
         break;
   }
}

function doResHold()
{
   var args = 'q=hold'+res.type+'&o=xml';

   args += makeResArgs();

   asProcess(wroot + '/reservations/dispatch.php', args,'Recording reservation...', handleReservation, "resReviewDIV");
}

function makeResArgs()
{
   var args;

   args  = '&t='    + res.type;
   args += '&rt='  + res.restakerID;
   args += '&rid=' + res.resID;
   args += '&tc='  + res.totCost;
   args += '&rn='  + res.name;
   args += '&e='   + res.email;
   args += '&td='  + res.travelDay;
   args += '&m='   + res.mobilePhone;
   args += '&l='   + res.localPhone;
   args += '&lo='  + res.lodging;
   args += '&ac='  + res.affCode;
   args += '&c='   + res.comment;

   switch(res.type)
   {
      case 'kt' :
         args += getKTArgs();
         break;
      case 'cart' :
      case 'scooter' :
      case 'sled' :
         args += getSledArgs();
         break;
      default:
         break;
   }

   return args;
}

function getKTArgs()
{
   var args = '';

   // Put rider info in args
   var ids = '';
   var a = '';
   var c = '';
   var f = '';
   var p = '';

   for(var i=0; i<res.kts.length; i++)
   {
      ids += res.kts[i].id + ';';
      a += res.kts[i].adult + ';';
      c += res.kts[i].child + ';';
      f += res.kts[i].free + ';';
      p += res.kts[i].cost + ';';
   }

   args += '&kti=' + ids;
   args += '&kta=' + a;
   args += '&ktc=' + c;
   args += '&ktf=' + f;
   args += '&ktp=' + p;

   return args;
}

function getSledArgs()
{
   var i = 0, args = '', rds = '', rws = '', rss = '', sds = '', scs = '';

   // Put rider info in args
   for(i = 0; i < res.numRiders(); i++) {
      rds += res.riders[i].id + ';';
      rws += res.riders[i].rweight + ';';
      rss += res.riders[i].sledID + ';';
   }

   args += '&rd=' + rds;
   args += '&rw=' + rws;
   args += '&rs=' + rss;

   // Put sled info in args
   for(i = 0; i < res.numSleds(); i++) {
      sds += res.sleds[i].id + ';';
      scs += res.sleds[i].cost + ';';
   }

   args += '&sd=' + sds;
   args += '&sc=' + scs;

   return args;
}

function handleReservation()
{
   if(xmlHttp.readyState == 4)
   {
      var
			x = null, r = null, errorCount = 1,
			message = '', errorMessage = '',
			xmlDoc = xmlHttp.responseXML;

		if(xmlDoc) {
			r = xmlDoc.getElementsByTagName("result");
			if(r && r.length > 0) {
				errorCount = r[0].getAttribute("error") * 1 + 0;
				if (errorCount > 0) {
					errorMessage = r[0].getAttribute("errorText");
				}
			} else {
				errorMessage = 'Valid xml returned by the server, but result tag was missing';
			}
		} else {
			errorMessage = 'An invalid xml response was returned by the server';
		}

      if(errorCount > 0)
      {
         x = document.getElementById('reviewH1');
         if(x) { x.innerHTML = 'Error Making Reservation'; }
         else  { message = '<h1>Error Making Reservation</h1>'; }

         message += '<p>The following error was encountered when we tried to make your reservation:</p>';
         message += '<p class="incomplete">' + errorMessage + '</p>';
         message += '<p>You may try to fix the problem yourself, or let us help.  Click on the "Help! I\'m stuck!\" link on the left, then click on the "click here" text.  Someone will call or email to help fix your error.</p>';
      }
      else
      {
         res.resID = r[0].getAttribute("resID");
			if (typeof(localStorage) != 'undefined' ) {
				localStorage.setItem('resID', res.resID);
				localStorage.setItem('resEmail', res.email);
			}
			// Test if this will work document.getElementById("quantity").value = res.numSleds();

         message = "<h1>Your Reservation has been recorded</h1>";
         message += "<h2>Your reservation ID is: '"+res.resID+"'<br />Your recorded email address is '"+res.email+"'</h2>";
         message += "<p>If you call us to ask about your reservation, we will ask you for this information to confirm your identity.  You may also use your reservation ID and email address to log in and <a href=\"http://www.dogsledrides.com/reservations/check_status.php\">check the status</a> of your reservation.</p>";
         message += "<p>Your reservation is currently pending.  Once we receive payment for your reservation it will be confirmed.  If we do not receive a payment notification within two hours, your reservation will be cancelled and completely removed from the system.</p>";
         message += "<p><button type=\"button\" onclick=\"changeView(1)\">Move to Payment section</button></p>";

         updatePaymentForm();
         document.getElementById("item_number").value = res.resID;
      }

      document.getElementById("resReviewDIV").innerHTML = message;
   }
}

//
// Add a rider to the rider array
//
function doAddRider()
{
   var riderName = document.getElementById("riderName").value;
   var riderWeight = document.getElementById("riderWeight").value;

   if((riderName === '') || (riderWeight === ''))
   {
      alert("A rider must have both a name and a weight.");
   }
   else
   {
      var riderHeightID = 0;
      var riderHeightText = '';
      var riderAgeID;
      var riderAgeText;

      if(res.type == 'sled')
      {
         riderHeightID = getSelectValue("riderHeight");
         riderHeightText = getSelectText("riderHeight");
         riderAgeID = getSelectValue("riderAge");
         riderAgeText = getSelectText("riderAge");
      }
      else if(res.type == 'cart')
      {
         riderAgeID = getSelectValue("cartRiderAge");
         riderAgeText = getSelectText("cartRiderAge");
      }
      else
      {
         riderAgeID = getSelectValue("scooterRiderAge");
         riderAgeText = getSelectText("scooterRiderAge");
      }

      x = document.getElementById("weightUnits");
      var weightUnits = x.options[x.selectedIndex].value;
      if(weightUnits == 2)
      {
         riderWeight = Math.round(riderWeight * 2.2);
      }
      else if(weightUnits == 3)
      {
         riderWeight = Math.round(riderWeight * 14);
      }
      else
      {
         riderWeight = Math.round(riderWeight * 1);
      }
   
      rider = new riderObj(riderName, riderWeight, riderHeightID, riderHeightText, riderAgeID, riderAgeText);
      res.addRider(rider);

      res.showRiders();
      res.showMatchRiders();
		res.showDescription('resDescription');
		
      // Clear name and weight entries and move back to the name field
      document.getElementById("riderWeightLabel").className = 'incomplete';
      document.getElementById("riderNameLabel").className = 'incomplete';
      document.getElementById("riderWeight").value = '';
      document.getElementById("riderName").value = '';
      document.getElementById("riderName").focus();
      resetReview();
   }
}

function doRemoveRider(i)
{
   res.removeRider(i);
   res.showRiders();
   res.showMatchRiders();
   res.showDescription('resDescription');
   resetReview();
}


function drawPaymentForm()
{
   var txt = '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="payPalForm">';
   txt += '<input type="hidden" id="item_number" name="item_number" value="noIDwha" />';
   txt += '<input type="hidden" name="cmd" value="_xclick" />';
   txt += '<input type="hidden" name="no_note" value="1" />';
   txt += '<input type="hidden" name="business" value="winterpark@dogsledrides.com" />';
   txt += '<input type="hidden" name="return" value="http://www.dogsledrides.com/' + wroot + '" />';
   txt += '<input type="hidden" name="cancel_ return" value="http://' + theDomain + wroot + '/reservations/paypal_cancel.php" />';
   txt += '<input type="hidden" name="cbt" value="View further instructions" />';
   txt += '<input type="hidden" name="no_shipping" value="1" />';
   txt += '<input type="hidden" name="rm" value="2" />';
   txt += '<input type="hidden" name="notify_url" value="http://' + theDomain + wroot + '/reservations/paypal_notify.php" />';
   txt += '<input name="item_name" type="hidden" id="item_name"  value="Dog Sled Ride Reservation"><br />';
   txt += '<input id="fullRadio" type="radio" name="amount" value="0" /><label id="fullRadioLabel" for="fullRadio">Pay full amount (0)</label><br />';
   txt += '<input id="halfRadio" type="radio" name="amount" value="0" /><label id="halfRadioLabel" for="halfRadio">Pay 50% deposit (0)</label><br /><br />';
   txt += '<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="">';
   txt += '</form>';

   document.getElementById("payDIV").innerHTML = txt;
}


function updatePaymentForm()
{
   drawPaymentForm();

//   var tot = document.getElementById("totResCost").value * 1;
//   var bal = document.getElementById("balance").value * 1;

   var tot = res.totCost;
   var bal = tot;

//   document.getElementById("item_number").value = document.getElementById("resID").value;
   document.getElementById("item_number").value = res.resID;

   if(bal == tot) {
      document.getElementById("fullRadio").value = tot;
      document.getElementById("fullRadio").selected = 'selected';
      document.getElementById("fullRadioLabel").innerHTML = 'Pay full amount ($'+tot+')';
      document.getElementById("halfRadio").value = Math.ceil(tot/2);
      document.getElementById("halfRadioLabel").innerHTML = 'Pay 50% deposit ($'+Math.ceil(tot/2)+')';
   } else if(bal === 0) {
      document.getElementById("paymentDiv").innerHTML = '<h1>You have a $0 balance, no payment is necessary.</h1>';
   } else {
      document.getElementById("fullRadio").value = bal;
      document.getElementById("fullRadio").selected = 'selected';
      document.getElementById("fullRadioLabel").innerHTML = 'Pay balance ($'+bal+')';
      document.getElementById("halfRadio").style.display = 'none';
      document.getElementById("halfRadioLabel").style.display = 'none';
   }
}

