// $Id: slider.js 2203 2009-11-11 00:57:19Z dhh $
//
	var scale = 18; // pixels per day
	var show_days = 36;
	var sl_scroll = 7; // days

// business rules
	var max_days = 14;
	var max_days_normal = 14;
	var too_young_days = 56;
	var not_tomorrow = 7;
	var min_gap = 2;
	var min_my_gap = 7;


	var spacer = "<img class='sl_spacer' src='/skin/std/images/hline.png' alt=''>";


	// no more constants below ;-)

	var baseDate;
	var mode; 
	var coSlider;
	var ciSlider;
	var ci;
	var co;
	var startDate;
	var endDate;
	var age_at_start;
	var cost_msg;

	var final_days;
	var final_dollars;
	var final_year;
	var final_ab_credits;
	var final_sab_days;

	var is_auto = 'N';
	var wishlist_ref;

	var add_day_price;

	var current_occupancy_idx;

	var warnings = 0;
	var ci_start = 0;
	var co_start = 0;

function findMode (theDate) {
		if (CC.object_id || CO.object_id){return 'sab30'};
		
		var diff = Math.round((theDate-now_at_location)/1000/60/60/24);
		var mm;
		if (CM.object_id){
			mm = CM.plan.sab_window;
		} else {
			mm = 90;
		}
		if (diff > mm){
			return 'ab';
		} else if (diff > 60) {
			return 'sab90';
		} else if (diff > 30){
			return 'sab60';
		} else {
			return 'sab30';
		}
}


function paint_it () {
		for (var i = 0; i<=show_days-1; i++){
			var tmp_date  = addDays2Date(baseDate, i);
			var td = ge(dateFormatted(tmp_date));
			if (i<ci || i>=co){
				td.style.backgroundColor = '';
			} else {
				td.style.backgroundColor = 'white';
			}
		}
}

function dateFormatted(d){
		return printf('%4d%02d%02d', d.getUTCFullYear(), d.getUTCMonth()+1, d.getUTCDate());
}

function dateFormatted2(d){
		return printf('%4d/%02d/%02d', d.getUTCFullYear(), d.getUTCMonth()+1, d.getUTCDate());
}

function gen_wishlist_ref(){
	var i = 0;
	var empty;
	while (!empty){
		var tmp_date  = addDays2Date(startDate, i++);
		var td = ge(dateFormatted(tmp_date));
		empty =  td.getAttribute('wishlist_ref');
	}
	wishlist_ref = empty;
	max_waiting = td.getAttribute('waiting');
}
	
function mark_holiday(cell, h){
		cell.title=h;
		cell.className='holiday_sl_cell';
		cell.setAttribute('holiday',h);
}




function generate_calendar(){
		zap_if(ge("calendar_table"));
		var tab = ce('TABLE');
		tab.id = "calendar_table";
		ge("calendar_container").appendChild(tab);

		tab.cellPadding=0;
		tab.cellSpacing=0;
		tab.border=0;
		var tr = tab.insertRow(0);
		for (var i = 0; i<=show_days-1; i++){
			var td = tr.insertCell(i);
			td.className = "sl_cell";

			var tmp_date = addDays2Date(baseDate,i);

			
			td.id = dateFormatted(tmp_date);
			td.innerHTML = tmp_date.getUTCDate() + spacer;
			if (tmp_date.getUTCDay() == 0){
				td.className='sun_sl_cell';
			}
			if (tmp_date.getUTCDay() == 6){
				td.className='sat_sl_cell';
			}
			for (var j=0; j<Holidays.length; j++){
				if (dateFormatted(tmp_date) == Holidays[j].when){
					mark_holiday(td,Holidays[j].what);
				}
			}
		}
		var tr0 = tab.insertRow(1);
		var old_month = 'NADA';
		var j = 0;
		for (var i = 0; i<=show_days-1; i++){

			var tmp_date = addDays2Date(baseDate,i);

			if (tmp_date.getUTCMonth() != old_month){
				var td0 = tr0.insertCell(j);
				var month_name = Months[tmp_date.getUTCMonth()] + ' ' + tmp_date.getUTCFullYear();
				var start_days = 0;
				var end_days = 0;
				if (j == 0){
					start_days = baseDate.getUTCDate()-1;
				}
				var d_month = days_in_month(tmp_date.getUTCFullYear(), tmp_date.getUTCMonth());
				if (d_month > show_days-i){
					end_days = d_month - (show_days-i);
				}
				var colspan = d_month - start_days - end_days;
				if (colspan <= 1){
					month_name = "";
				} else if (colspan == 2){
					month_name = Months_short[tmp_date.getUTCMonth()];
				} else if (colspan <=4){
					month_name = Months[tmp_date.getUTCMonth()];
				}
				td0.colSpan = colspan;
				td0.className = "sl_month_cell";
				if (j != 0){
					td0.style.borderLeft="dotted 1px rgb(215, 211, 182)";
				}
				td0.innerHTML = month_name;
				old_month = tmp_date.getUTCMonth();
				j++;
			}
		}
}
	
function printDate(d){
		return Days[d.getUTCDay()] + ', ' + d.getUTCDate() + '/' + (d.getUTCMonth()+1) + '/' + d.getUTCFullYear();
}

function cWarning(){
	 the_warning('');

}

function the_warning (msg){
		if (msg && msg != ''){
			ge('warningDiv').innerHTML = "warning: " + msg;
			setTimeout("cWarning()", 1700);
		} else {
			ge('warningDiv').innerHTML = "&nbsp;";
		}
		warnings = 0;
}
	

function postinit_dates(){
	var b_id = getCookie('edit');
	if (b_id){
			var tmp_date = new Date(startDate);
			var td = ge(dateFormatted(tmp_date));
			while(td.getAttribute('wishlist_ref') == b_id){
				tmp_date = addDays2Date(tmp_date,1);
				td = ge(dateFormatted(tmp_date));
			}
			endDate = addDays2Date(tmp_date, 0);
			co_start = Math.round((endDate-baseDate)/1000/60/60/24);
			coSlider.setValue(co_start*scale);
	}

}


function preinit_dates(){

	var bstart = getCookie('b_start');
	if (bstart){
		SetCookie('b_start','',-1);
		var yyyy = bstart.substr(0,4);
		var mm = bstart.substr(4,2);
		var dd =  bstart.substr(6,2);
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));

		baseDate = addDays2Date(b_start, -4);
		startDate = new Date(b_start);
		endDate = new Date(startDate);

	} else { 
		startDate = new Date(baseDate);
	}

	mode = findMode(baseDate);
	if (bstart){
		startDate = new Date(b_start);
		endDate = new Date(startDate);
		
	} else {
		if (mode == 'ab' || mode == 'sab90' || mode == 'sab60'){
			// find first available Sunday
			while (startDate.getUTCDay() != 0){
				startDate.setUTCDate(startDate.getUTCDate()+1);
			}
			endDate = addDays2Date(startDate, 7); // default one week for AB
		} else if (mode == 'sab30'){
				
			endDate = new Date(startDate);

		} else {
			alert('unknown booking mode ' + mode);
		}
	}

	ci_start = Math.round((startDate-baseDate)/1000/60/60/24);
	co_start = Math.round((endDate-baseDate)/1000/60/60/24);

}





function ch_o (oc_idx){
	var oc = CFO.enhanced.occupancies[oc_idx];
	var td = ge(oc.object_id);
	var tr = td.parentNode;
	for (var i=0; i<tr.childNodes.length; i++){
		var bg = '';
		var sel = false;
		if (tr.childNodes[i].id == oc.object_id){
			bg = '#e0e0e0';
			sel = true;
		}
		tr.childNodes[i].style.backgroundColor=bg;
		if (ge('i_'+tr.childNodes[i].id)){
			ge('i_'+tr.childNodes[i].id).checked = sel;
		}
	}
	current_occupancy_idx = oc_idx;
	paint_bookings(oc_idx);
	if (!CC.object_id && !CO.object_id){
		paint_discounts(oc_idx);
	}
	redisplay();
	return false;
}

function oc_quick_info (many){
	var d = ge('oc_quick_info');
	if (many){
		var oc = CFO.enhanced.occupancies;
		var h = '<table align=\"center\" cellspacing=\"0\" cellpadding=\"0\"><tr>';
		h += '<td class=\"oc_qih"\>';
		h += '<b>Residence:</b></td>';
		for (var i=0; i<oc.length;i++){
			h += '<td class=\"oc_qi"\ id=\"'+oc[i].object_id+'\" onclick=\"ch_o('+i+');\">';
			h += '<input type=radio name=ocz id=\"i_'+oc[i].object_id+'\">&nbsp;&nbsp;';
			h += oc[i].info.curlang ;
			h += ".&nbsp;&nbsp;<b>Occupancy limit: " + oc[i].capacity;
			h += " guests</b></td>";
		}
		h += "</tr></table>";
		d.innerHTML = h;
	} else {
		var oc = CFO.enhanced.occupancies[0];
		var h = '<table align=\"center\" cellspacing=\"0\" cellpadding=\"0\"><tr>';
		h += '<td class=\"oc_qih"\>';
		h += '<b>Destination:</b></td>';
		h += '<td class=\"oc_qi"\ id=\"'+oc.object_id+'\" style=\"cursor:default;\">';
		h += oc.info.curlang;
		h += ".&nbsp;&nbsp; <b>Occupancy limit: " + oc.capacity;
		h += " guests</b></td>";
		h += "</tr></table>";
		d.innerHTML = h;
	}
}


function paint_discounts (oc_idx){

		var deals = CFO.enhanced.deals;
		for (var i = 0; i<=show_days-1; i++){
			var tmp_date  = addDays2Date(baseDate, i);
			var td = ge(dateFormatted(tmp_date));
			td.setAttribute('price', 1);
			td.setAttribute('discount', '');
			td.style.borderBottom = '';
			for (var j=0; j<deals.length; j++){
				var discount_start = date_perl2js(deals[j].start_date);
				var discount_end = date_perl2js(deals[j].end_date);
				var days_price = deals[j].discount.val;
				if (tmp_date > discount_end || tmp_date < discount_start){
					//
				} else {
					td.setAttribute('price', days_price);
					td.style.borderBottom = 'solid 1px #a0ffa0';
					td.setAttribute('discount', deals[j].to_string);
				}
			}
		}

}


function clear_all_bookings(){
		for (var i = 0; i<=show_days-1; i++){
			var tmp_date  = addDays2Date(baseDate, i);
			var td = ge(dateFormatted(tmp_date));
			td.style.color = '';
			td.style.textDecoration = '';
			td.style.backgroundColor = '';
			td.style.background = '';
			td.setAttribute('booked',0);
			td.setAttribute('booking_id', '');
		}
}


function test_date_booked(oc_idx,test_date, my_only){
	var oc = CFO.enhanced.occupancies[oc_idx];
	for (var b=0; b<CFO.enhanced.bookings.length; b++){
		var my_b = CFO.enhanced.bookings[b];
		if (my_b.occupancy.object_id != oc.object_id){continue;}
		if (my_only == 1 && my_b.b_member.object_id != CM.object_id){ continue; }
		var dd = my_b.start_date.local_c.day;
		var mm = my_b.start_date.local_c.month;
		var yyyy = my_b.start_date.local_c.year;
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));
		dd = my_b.end_date.local_c.day;
		mm = my_b.end_date.local_c.month;
		yyyy = my_b.end_date.local_c.year;
		var b_end = new Date(Date.UTC(yyyy,mm-1,dd));

		var tmp_date  = addDays2Date(test_date, 0);
		if (b_start <= tmp_date && tmp_date <= b_end){
				return true;
		}
	}	
	return false;
}

function paint_bookings(oc_idx){
	clear_all_bookings();
	var oc = CFO.enhanced.occupancies[oc_idx];
	var scale_start = addDays2Date(baseDate, 0);
	var scale_end = addDays2Date(baseDate, show_days-1);
	var bos = new Array;
	if (CFO.enhanced.bookings.length != 0){
		for (var i=0; i<CFO.enhanced.bookings.length; i++){
			if (CFO.enhanced.bookings[i].is_canceled.yn == 'N'){
				bos.push(CFO.enhanced.bookings[i]);
			}
		}
	}
	if (CFO.is_mobile.yn == 'Y' && !CC.object_id){
		for (var i = 0; i<CFO.schedule.length; i++){
			CFO.schedule[i].is_mobile = 1;
			if (CFO.schedule[i].is_available.yn == 'N'){
					CFO.schedule[i].is_not_bookable = 1;
			}
			bos.push(CFO.schedule[i]);
		}
	}
	for (var b=0; b<bos.length; b++){
		var my_b = bos[b];
		if (my_b.is_mobile){
		} else {
			if (my_b.occupancy.object_id != oc.object_id){continue;}
		}
		var dd = my_b.start_date.local_c.day;
		var mm = my_b.start_date.local_c.month;
		var yyyy = my_b.start_date.local_c.year;
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));
		dd = my_b.end_date.local_c.day;
		mm = my_b.end_date.local_c.month;
		yyyy = my_b.end_date.local_c.year;
		var b_end = new Date(Date.UTC(yyyy,mm-1,dd));

		if (b_start > scale_end || b_end < scale_start) {continue;}
		for (var i = 0; i<=show_days-1; i++){
			var tmp_date  = addDays2Date(baseDate, i);
			var td = ge(dateFormatted(tmp_date));
			td.title = '';
			if (b_start <= tmp_date && tmp_date <= b_end){
				if (my_b.is_mobile){
					td.setAttribute('location', my_b.object_id);
					if (my_b.is_not_bookable){
						td.setAttribute('is_not_bookable', my_b.object_id);
					}
					if (my_b.is_transit.yn == 'Y'){
						td.setAttribute('mobile_transit', my_b.object_id);
					}
				} else {
					td.setAttribute('booked',1);
					if (my_b.is_wishlist.yn == 'Y' && my_b.position != 0){
						var waiting = td.getAttribute('waiting');
						if (waiting){
							waiting++;
						} else {
							waiting = 1;
						}
						td.setAttribute('waiting', waiting);
					} else {
						if (my_b.is_maintenance.yn == 'N'){
							td.setAttribute('wishlist_ref', my_b.object_id);
						} else {
							td.setAttribute('is_maintenance', my_b.object_id);
						}
					}
				
					if (my_b.b_member.object_id == CM.object_id){
						td.setAttribute('my_booking',1);
						if (my_b.is_wishlist.yn == 'Y'){
							td.setAttribute('my_wishlist',1);
						}
					}
				}
	
				if (td.getAttribute('booked') == 1 || (td.getAttribute('is_not_bookable') && td.getAttribute('is_not_bookable') != '')){
					if (td.className == 'sl_cell'){
						td.style.color = 'gray';
					} else {
						td.style.color = 'tomato';
					}
					td.style.textDecoration = 'line-through';
					td.style.background='url(/skin/std/images/select.png) no-repeat center';
				} else if (td.getAttribute('mobile_transit') && td.getAttribute('mobile_transit') != ''){
						td.style.background='url(/skin/std/images/todo_blue.gif) no-repeat bottom';
				}
				if (CC.object_id || CO.object_id){
					td.setAttribute('booking_id',my_b.object_id);
					if (CC_mode == 'browse'){
						td.style.cursor = 'pointer';
						if (my_b.is_maintenance.yn == 'N'){
							td.onclick = loadBook2;
							td.title = 'Click to load booking details';
						} else {
							td.onclick = loadMaintain;
							td.title = 'Click to load maintenance details';
						}
					}
				}
			}
		}
	}
}


var sum_on = 0;

function sw_bm_summary(){
	if (sum_on == 0){
		build_summary('bmc_c');
		sum_on = 1;
	} else {
		init_bm_summary();
		sum_on = 0;
	}
}

var sab_no = 0;
function recalc_sab() {
	if (CC.object_id || CO.object_id){
		return;
	}
	sab_no = 0;
	for (var i=0;i<myBookings.length;i++){
		if (myBookings[i].booking_type == 'ab'){ continue; }
		if (myBookings[i].deleted == 1){ continue; }
		if (myBookings[i].past == 1){ continue; }
		if (myBookings[i].is_wishlist == 'Y'){ continue; }
		sab_no ++;
	}
}

var CC_mode = 'browse';

var cc_bm_inited = 0;

function bm_switch_title(){
	var t = 'Click to switch to ';
	if (CC_mode != 'browse'){
		t += 'bookings mode';
	} else {
		t += 'property maintenance mode';
	}
	return t;
}

function init_bm_summary(){
	var c = ge('bm_summary');
	if (!c){return};
	if (!CC.object_id && !CM.object_id && !CO.object_id){
		zap(c);
	}
	if (!CC.object_id && !CO.object_id){
		c.innerHTML = '<span style="text-decoration:underline"> Days left</span><span id="bmc_c"></span>';
		c.onclick = sw_bm_summary;
	} else {
//		if (!cc_bm_inited && CFO.is_mobile.yn == 'N'){
		if (!cc_bm_inited){
			var tt = ' browse bookings';
			if (CO.object_id){
				tt = ' property maintenance';
				CC_mode = 'maintenance';
			} 
			c.innerHTML = '<span style=text-decoration:underline"> Mode:</span><span id="m_c">'+tt+'</span>';
			c.onclick = sw_cc_mode;
			c.title = bm_switch_title();
			cc_bm_inited = 1;
		}
	}
}


function killSlider(){

	ge('coBGDiv').setAttribute('x2:role','');
	ge('ciBGDiv').setAttribute('x2:role','');
	ge('coBGDiv').title='';
	ge('ciBGDiv').title='';
	ciSlider.onSlideEnd = function(){void(0)};
	coSlider.onSlideEnd = function(){void(0)};
	ciSlider = null;
	coSlider = null;
	ci = null;
	co = null;
	ci_start = 0;
	co_start = 0;
	ge('coHandleDiv').style.display='none';
	ge('ciHandleDiv').style.display='none';
	redisplay();
}

function rebornSlider(){
		ge('coHandleDiv').style.display='';
		ge('ciHandleDiv').style.display='';
		init_slider(null, 1);		
}


function init_slider (start, from_self){
		current_occupancy_idx = 0;
		recalc_sab();
		init_bm_summary();
		init_one_slider(start, from_self);
		if (!CFO || !CFO.enhanced || !CFO.enhanced.occupancies || CFO.enhanced.occupancies.length == 0){
			alert('DEVELOPEMENT: This destination has no single occupancy loaded. Please load it at your leisure.');
		} else if (CFO.enhanced.occupancies.length == 1){
			oc_quick_info(0);
			ch_o(current_occupancy_idx);
			oc_availability(current_occupancy_idx);
		} else {
			oc_quick_info(1);
			ch_o(current_occupancy_idx);
			oc_availability(current_occupancy_idx);
		}

		postinit_dates();

}

function init_one_slider(start, from_self) {
		if (start){
			var yyyy = start.substr(0,4);
			var mm = start.substr(4,2);
			mm--;
		} else {
			var yyyy = now_at_location.getUTCFullYear();
			var mm = now_at_location.getUTCMonth();
		}
		baseDate = new Date(Date.UTC(yyyy,mm,1));
		if ( mm   == now_at_location.getUTCMonth() &&
			yyyy == now_at_location.getUTCFullYear()){
			baseDate.setUTCDate(now_at_location.getUTCDate());
		} else {
			baseDate = addDays2Date(baseDate, -4);
		}

		preinit_dates();
		JustInitSlider(from_self);
		if ((CC.object_id || CO.object_id) && CC_mode == 'browse'){
			killSlider();
		}

}

function JustInitSlider(from_self){
		
		ge('cWrapper').style.width=scale*show_days+'px';
		generate_calendar();
	if (!CM.object_id && !CC.object_id && !CO.object_id){return;}
	if (!from_self) {

		ciSlider = YAHOO.widget.Slider.getHorizSlider("ciBGDiv", "ciHandleDiv", 0, (show_days-1)*scale, scale);
		coSlider = YAHOO.widget.Slider.getHorizSlider("coBGDiv", "coHandleDiv", 0, (show_days-1)*scale, scale);
	} else {
		if (!ciSlider){
			ciSlider = YAHOO.widget.Slider.getHorizSlider("ciBGDiv", "ciHandleDiv", 0, (show_days-1)*scale, scale);
		}
		if (!coSlider){
			coSlider = YAHOO.widget.Slider.getHorizSlider("coBGDiv", "coHandleDiv", 0, (show_days-1)*scale, scale);
		}
	}

		ciSlider.tickPause = 30;
		coSlider.tickPause = 30;
		

		ciSlider.onChange = function(offset) {
		};

		ciSlider.onSlideEnd = function (){
			var tmp_date = addDays2Date(baseDate, ciSlider.getValue()/scale);
			var tmp_mode = findMode(tmp_date);
			mode = tmp_mode;
			the_warning();
			ci = ciSlider.getValue()/scale;
			startDate = addDays2Date(baseDate,ci);
			check_overlap();
			check_max_days();
			redisplay();
		}
		
		coSlider.onChange = function(offset) {
		//
		};
		

		coSlider.onSlideEnd = function (){
			check_overlap();
			check_max_days();
			co = coSlider.getValue()/scale;
			endDate = addDays2Date(baseDate,co);
			redisplay();
		}
		ciSlider.setValue(ci_start*scale);
		coSlider.setValue(co_start*scale);

}
	
function get_o_idx (id){
	for (var i=0; i<CFO.enhanced.occupancies.length;i++){
		if (CFO.enhanced.occupancies[i].object_id == id){
			return i;
		}
	}
	return -1;
}

function check_other_occupancies(){
	var Other = new Array;
	var scale_start = addDays2Date(baseDate, 0);
	var scale_end = addDays2Date(baseDate, show_days-1);
	var oc = CFO.enhanced.occupancies[current_occupancy_idx];
oc_loop:
	for (var o_idx=0; o_idx<CFO.enhanced.occupancies.length; o_idx++){
		var o = CFO.enhanced.occupancies[o_idx];
		if (o.object_id == oc.object_id){ continue; }
	booking_loop:
  	for (var b=0; b<CFO.enhanced.bookings.length; b++){
   	 var my_b = CFO.enhanced.bookings[b];
   	 if (my_b.occupancy.object_id == oc.object_id){continue;}
			var dd = my_b.start_date.local_c.day;
			var mm = my_b.start_date.local_c.month;
			var yyyy = my_b.start_date.local_c.year;
			var b_start = new Date(Date.UTC(yyyy,mm-1,dd));
 			dd = my_b.end_date.local_c.day;
			mm = my_b.end_date.local_c.month;
			yyyy = my_b.end_date.local_c.year;
			var b_end = new Date(Date.UTC(yyyy,mm-1,dd));
			if (b_start > scale_end || b_end < scale_start) {continue;}
			for (var i=ci; i<co; i++){
				var tmp_date = addDays2Date(baseDate,i);
				if (b_start <= tmp_date && tmp_date <= b_end){
					continue booking_loop;
				}
			}
			continue oc_loop;
		}
		Other.push(o_idx);
	}
	return Other;
}

function check_overlap(){
		if (ciSlider.getValue() > coSlider.getValue()){
			coSlider.setValue(ciSlider.getValue());
		}
}

function check_max_days(){
	if (CC.object_id || CO.object_id){
		return;
	}
	if (CM.plan && CM.plan.name.indexOf('Trial') != -1){
		if (CM.plan.code == 'Trial 3'){
			max_days_trial = 3;
		} else if (CM.plan.code == 'Trial 4' ){
			max_days_trial = 4;
		}
		max_days = max_days_trial;
	} else {
		max_days = max_days_normal;
		if (mode == 'ab'){
			max_days += 7;
		}
	}
	if (coSlider.getValue()/scale > ci + max_days){
		coSlider.setValue((ci+max_days)*scale);
		the_warning('No more than ' + max_days + ' days can be booked.');
	}
}
	

function getAgeAtStart(){
		var diff = Math.round((theDate-now_at_location)/1000/60/60/24);

}

var enough = 0;
var b_errors = new Array;

function bep (txt){
	if (!enough){
		b_errors.push(txt);
	}
}

function getBookingCost(){

		add_day_price = CM.plan.extra_days_cost;
		var ent_days = 0;
		var sab_days = 0;
		var dollars = 0;
		var balance;
		var comments = new Array;
		b_errors = new Array;
		var ab = '';
		var holiday_paid = 0;
		var max_waiting = 0;
		var booked_overlap = 0;
		var bop = 0;
		var my_booking = 0;
		var my_wishlist = 0;
		var book_allowed = 1;
		var ab_c = 0;
		var too_young = 0;
		var is_tomorrow = 0;
		var out_sab = 0;
		var total_sab = 0;
		var ret = '';
		enough = 0;
		if (CM.is_active == 'N'){
			bep('Your account is not active. You can not make any bookings until the Club will receive your payment.');
			book_allowed = 0;
			enough = 1;
		}

		if (CM.nomore_bookings == 1){
			bep('Trial Membership Plan does not allow to have more than one booking.');
			book_allowed = 0;
			enough = 1;
		}

		if (CM.plan.name.indexOf('Trial') != -1){
			var dam = CM.plan.sab_window;
			if ((startDate - now_at_location) / (1000*60*60*24) > dam){
				bep('Your holiday can not start later than '+ dam  +' days from current date.');
				book_allowed = 0;
				enough = 1;
			}

		}
		if (CM.plan.name.indexOf('Trial') != -1 && !CM.exceptions.allowMobile){
			if (CFO.is_mobile.yn == 'Y'){
				bep('Your membership plan does not allow you to book mobile destinations');
				book_allowed = 0;
				enough = 1;
			}
		}

		age_at_start = (startDate - CM.membership.commencement_date)/(1000*60*60*24);
		if (CM.plan.name.indexOf('Trial')  == -1 && !CM.exceptions.ignore8WeeksRule && age_at_start < too_young_days){
			bep('Your first holiday can not start earlier than 8 weeks from membership commencement date.');
//			bep('TODO: add \"click to go there\" link.');
			book_allowed = 0;
			too_young = 1;
		} else {
			if ((startDate - now_at_location) / (1000*60*60*24) < not_tomorrow-1){
				bep('Your holiday can not start earlier than '+ not_tomorrow  +' days from current date.');
//				bep('TODO: add \"click to go there\" link.');
				book_allowed = 0;
				is_tomorrow = 1;
			
			}

			if 	(startDate > addYears2Date(now_at_location,CM.plan.ab_window_years)) {
				bep('Your holiday can not start later than two years from current date.');
				book_allowed = 0;
			}

			if (startDate < launch_date){
				bep('This property is not available for bookings before '+launch_date);
				book_allowed = 0;
			}

			if (endDate >= closure_date && closure_date.getFullYear() > 2000){
				var foc = getCookie ('foc');
				if (!foc){
					bep('This property is not available for bookings after '+closure_date);
					book_allowed = 0;
				}
			}

			if (somewhere_else(startDate, endDate) > 1 && book_allowed){
				bep('You can not have more than two destinations booked at the same time.');
				book_allowed = 0;

			}
			if (seen_same_time(startDate, endDate, CFO)){
				bep('You can not book the same destination at the same time within two subsequent years.');
				book_allowed = 0;

			}

			if (mode != 'ab' && sab_no > 1){
				bep('You can have no more than 2 Space Available Bookings at the time');
				book_allowed=0;
			}

			if (mode != 'ab' && (startDate - now_at_location) / (1000*60*60*24) > CM.plan.sab_window){
				bep('Your membership plan does not allow you to make a Space Available Booking later than '+ CM.plan.sab_window  +' days prior arrival.');
//				bep('TODO: add \"click to go there\" link.');
				book_allowed = 0;
				out_sab = 1;
				
			}
			var cur;
			if (mode != 'ab'){
				cur = getCurBal(now_at_location);
			} else { 
				cur = getCurBal(startDate);
			}
			var curbal = cur.balance;
			var curyear = cur.year;
			final_year = curyear;


			var hacked = 0;			
			var disc_price_msg = 0;
			var sundays = 0;
			var start_on_sunday = 0;
			var booked_same_week = 0;
			var is_not_bookable = 0;
			var mobile_transit = 0;
			var where;
			var cal_days = 0;
			var unpaid_days = 0;
			for (var i=ci; i<co; i++){
				var tmp_date = addDays2Date(baseDate,i);
				var td_date = ge(dateFormatted(tmp_date));
				if (i == ci && td_date.getAttribute('location')){
					where = get_location_descript(td_date.getAttribute('location'));
				}
				if (i == ci || i == co-1){
					if (td_date.getAttribute('mobile_transit') && td_date.getAttribute('mobile_transit') != ''){
						mobile_transit = 1;
					}
				}
				var booked  = td_date.getAttribute('booked');
				var holiday = td_date.getAttribute('holiday');
				var price   = td_date.getAttribute('price');
				if (ci == i && tmp_date.getUTCDay() == 0){
					start_on_sunday = 1;
				} else { // check if someone has booking during same week
					var t_tmp_date = addDays2Date (baseDate,i);
					while (t_tmp_date.getUTCDay() != 0 && booked_same_week == 0 && t_tmp_date-baseDate >= 0){
						//freezing syndrome
						var t_booked = ge(dateFormatted(t_tmp_date)).getAttribute('booked');
						if (!t_booked || t_booked == 0){
							 t_tmp_date = addDays2Date(t_tmp_date,-1);
						} else {
							  booked_same_week = 1;
						}
					}
				}

				if (tmp_date.getUTCDay() == 0 && i != ci){
					sundays++;
				}

					var mt = td_date.getAttribute('is_not_bookable');
					if (mt && mt != 0){
						is_not_bookable = 1;
					}
				if (booked && booked != 0){
					booked_overlap = 1;
					var myb = td_date.getAttribute('my_booking');
					if (myb && myb == 1){
						my_booking = 1;
						book_allowed = 0;
						if (td_date.getAttribute('my_wishlist') && td_date.getAttribute('my_wishlist') == 1){
							my_wishlist = 1;
						}
					}
					var waiting = td_date.getAttribute('waiting');
					if (waiting && waiting>max_waiting){
						max_waiting = waiting;
					}
					if (td_date.getAttribute('is_maintenance') && td_date.getAttribute('is_maintenance') != ''){
						is_not_bookable = 1;
					}
				} else {
					bop = 1;
				}

				if (booked == 0 && price != 1 && disc_price_msg == 0){
					comments.push('Special deal discount has been applied to this time period.');
					disc_price_msg = 1;
				}
				ent_days += price*1*CFO.discount_class.val;
				cal_days++;
				var all_days = curbal.days;
				if (mode != 'ab'){
					all_days += curbal.sab_days;
				}
				if (ent_days > all_days){
						unpaid_days +=  price*1*CFO.discount_class.val;
					}

				if (mode == 'ab'){
					if (holiday){
						ab_c++;
						comments.push('additional AB credit taken because of booking the holiday (' + holiday + ')');
						holiday_paid++;
					}

				}
			} // end foreach day

			unpaid_days = Math.round(unpaid_days);

			if (is_not_bookable){
				bep('The destination is not available for bookings for this period of time.');
				book_allowed = 0;
				enough = 1;
			}


			if (mobile_transit){
				bep('Arrival and departure dates can not be inside of "in transit" period of time for this mobile destination');
				enough = 1;
				book_allowed = 0;
			}

			var t;
			if (booked_overlap && !my_booking && !is_not_bookable){
					t = getOrigDays();
					sundays = t.sundays;
					ent_days = t.ent_days;
					booked_same_week = t.booked_same_week;
					ab_c = t.ab_c;
					if (t.comments.length > 0){
						for (var j=0; j<t.comments; j++){
							comments.push(t.comments[j]);
						}
					}
					comments.push('Should you wish to add yourself to the waiting list, your arrival and departure dates will be exactly same as of existing booking: '+t.to_string);

			}

			if (cal_days < 2){
				bep('The minimum stay at the destination is 2 nights.');
				book_allowed = 0;
				enough = 1;
			}

///removed as per Nick's request
///			if (CFO.is_mobile.yn == 'Y' && CFO.discount_class.val != 1 && mode != 'sab30'){
///					if (startDate.getUTCDay() == 0) { //Sun
///					} else {
///						bep('Arrival Day must be on Sundays only.');
///						book_allowed = 0;
///					}
///					if (endDate.getUTCDay() == 0) { //Sun
///					} else {
///						bep('Departure Day must be on Sundays only.');
///						book_allowed = 0;
///					}
///			}

//			ent_days = Math.round(ent_days*CFO.discount_class.val);
			ent_days = Math.round(ent_days);
			if (ent_days == 0){
				ent_days = 1;
			}

			if (mode == 'ab'){
				ab_c += (sundays+1)*CFO.ab_value;
				if (sundays > 2){
					bep('Booking must be made within no more than two consecutive Sunday to Sunday time periods.');
					book_allowed = 0;
				}

				if (ab_c != 1){
					ab_c -= booked_same_week;
				}
				
				if (ent_days > curbal.days){
					if (CM.plan.name.indexOf('Trial') != -1){
						dollars = (ent_days - curbal.days)*add_day_price;
						final_sab_days = 0;
						ent_days = 0;
					} else if (CFO.is_mobile.yn == 'Y' ){
 // 2009 04 reverting Lady K rule
//						if (CM.plan.name.indexOf('2007') == -1){
//							dollars = 4*(ent_days - curbal.days)*add_day_price;
								dollars = (ent_days - curbal.days)*1500;
//						} else {
//							dollars = (ent_days - curbal.days)*add_day_price;
//						}
						ent_days = curbal.days;
						final_sab_days = 0;
						hacked = 1;
					} else {
						bep('You do not have enough Entitlement Days to make this booking.');
						book_allowed = 0;
					}
				}

			} else {

				if (mode == 'sab60'){
					if (startDate.getUTCDay() == 0) { //Sun
					} else if (startDate.getUTCDay() == 4){ //Thu
					} else {
// as requested by Nick
//						bep('Arrival Day must be on Sundays or Thursdays only.');
//						book_allowed = 0;
					}
					if (endDate.getUTCDay() == 0) { //Sun
					} else if (endDate.getUTCDay() == 4){ //Thu
					} else {
//						bep('Departure Day must be on Sundays or Thursdays only.');
//						book_allowed = 0;
					}
				} else if (mode == 'sab90'){
					if (startDate.getUTCDay() == 0) { //Sun
					} else {
						bep('Arrival Day must be on Sundays only.');
						book_allowed = 0;
					}
					if (endDate.getUTCDay() == 0) { //Sun
					} else {
						bep('Departure Day must be on Sundays only.');
						book_allowed = 0;
					}

				} else if (mode == 'sab30'){
					if (book_allowed){
						var closestEnd = getClosestEnd();
						if (startDate <= closestEnd || startDate >= addDays2Date(closestEnd, min_gap)){ // fine
	
						} else {
							bep('Arrival Day must be either on Departure Day of previous existing booking or more than ' + min_gap + ' days after it.');
							book_allowed = 0;
						}
					}
					if (book_allowed){
						var closestStart = getClosestStart();
						if (endDate >= closestStart || endDate <= addDays2Date(closestStart, -min_gap)){ // fine
	
						} else {
							bep('Departure Day must be either on Arrival Day of next existing booking or less than ' + min_gap + ' days before it.');
							book_allowed = 0;
						}
					}

				}
				if (book_allowed){
						var closestEnd = getMyClosestEnd();
						if (startDate <= closestEnd || startDate >= addDays2Date(closestEnd, min_my_gap)){ // fine
	
						} else {
							bep('Arrival Day must be more than ' + min_my_gap + ' days after your previous existing booking.');
							book_allowed = 0;
						}
				}
				if (book_allowed){
						var closestStart = getMyClosestStart();
						if (endDate >= closestStart || endDate <= addDays2Date(closestStart, -min_my_gap)){ // fine
	
						} else {
							bep('Departure Day must be less than ' + min_my_gap + ' days before your next existing booking.');
							book_allowed = 0;
						}
				}

				if (ent_days <= curbal.sab_days){
					// enough SAB days
					final_sab_days = ent_days;
					ent_days = 0;
				} else {
					final_sab_days = curbal.sab_days;
					ent_days = ent_days - final_sab_days;	
					if (ent_days > curbal.days){
						if (CM.plan.is_prepaid == 0){
							bep('You do not have enough Entitlement Days to make this booking.');
							book_allowed = 0;
						} else {
							dollars = (unpaid_days)*add_day_price;
							ent_days = curbal.days;

						}
					}
					if (ent_days != 0){
						comments.push(ent_days + ' of your Entitlement Days will be converted to SAB Days for immediate use');
					}									
				}
			}



			if (mode == 'ab'){
				ab = ab_c + ' AB credit';
				final_ab_credits = ab_c;
				if (ab_c != 1){
					ab += 's';
				}

				// check AB credits
				if (ab_c > CM.balance1.ab_credits){// current year always
					bep('You do not have enough AB credits to make this booking!');
					book_allowed = 0;
				}
				if (CM.plan && CM.plan.name.indexOf('Trial') == -1 && !hacked){

///					final_sab_days = (sundays + 1) * 7 - Math.round(ent_days/CFO.discount_class.val);

///					ent_days = Math.round((sundays + 1) *7*CFO.discount_class.val);

//					ent_days = Math.round(ent_days*CFO.discount_class.val);

					if (book_allowed){
///						if (final_sab_days != 0){// && ab_c == CM.balance1.ab_credits){
///							comments.push(final_sab_days + ' of your Entitlement Days will be converted to SAB Days for future use');
///							final_sab_days = -final_sab_days; //credit actually
///						}
						if (ab_c == CM.balance1.ab_credits){
							final_sab_days = CM.balance1.days - ent_days;
							if (final_sab_days < 0){
								final_sab_days = 0;
							} else {
								comments.push(final_sab_days + ' of your Entitlement Days will be converted to SAB Days for future use');
								final_sab_days = -final_sab_days; //credit actually
							}
						}
					}
				} 
			}

			var days_w;
			if (final_sab_days > 0){
				days_w = (final_sab_days + ent_days);
			} else {
				days_w = ent_days;
			}
			days_w += ' day';
// HACK
			if (days_w == '0 day'){
				days_w = '';
			}
			if (final_sab_days + ent_days > 1){
				days_w += 's';
			}

			final_days = ent_days;

			if (booked_overlap){
				var fw = 'Requested';
				if (bop == 1){
					fw = 'Part of requested';
				}
				if (my_booking){
					if (!my_wishlist){
						bep(fw + ' time period has been already booked out by yourself! Please use the booking page to extend dates of this booking if you wish.');
						book_allowed = 0;
					} else {
						var ttt = '<br/>Click <a href="javascript:void(0);" onclick="make_member_waiting_list();">here</a> to go to your waiting list.';

						bep(fw + ' time period already has a waiting list entry made out by yourself!'+ttt);
						book_allowed = 0;
					}
				} else {

					bep(fw + ' time period has been already booked out.');
					if (max_waiting != 0){
						var ws = 's';
						if (max_waiting == 1){ws = '';}
						bep('Also, there is a waiting list of ' + max_waiting + ' other Club Member ' + ws);
					}
					if (CFO.enhanced.occupancies.length > 1){
						var other_avail = check_other_occupancies();
						if (other_avail.length > 0){
							var res = 'other residences';
							var links=new Array;
							if (other_avail.length == 1){res = 'another residence';}
							for (var j=0; j<other_avail.length; j++){
								var l = "<a href=\"javascript:void(0);\" onclick=\"return ch_o("+other_avail[j]+");\">";
								l += CFO.enhanced.occupancies[other_avail[j]].info.curlang;
								l += "</a>";
								links.push(l);
							}
							bep('However, for the same time period you can book '+res+' ('+links.join(',') + ') at the destination.');
						} else {
							bep('All other residences at the destination have been booked out as well for this time period.');
						}
					}
				}
			}
		}
		var my_ret = new Object;


		if (co == ci) {
			final_days = 0;
			final_sab_days = 0;
			final_dollars = 0;
			final_ab_credits = 0;
			final_year = 0;
			ret = '';
			my_ret.html = ret;
			my_ret.errors = b_errors;
			my_ret.book_allowed = 0;

		} else {
			ret = '';
			if (!is_tomorrow && !too_young && book_allowed){
				ret = "<b>Booking Cost:</b> " + days_w;
				if (ab != ''){
					if (days_w != ''){
						ret += ' + ';
					}
					ret += ab;
				}
				if (dollars != 0){
					if (ret != ''){
						ret += ' +';
					}
					ret += ' USD $'+dollars;
//					comments.push('USD $' + dollars + ' payable for ' + (co-ci - (curbal.days+curbal.sab_days)) + ' additional SAB days.');
					comments.push('USD $' + dollars + ' payable for additional SAB days.');
				}
				cost_msg = ret;
				final_dollars = dollars;
			}
			if (comments.length != 0 && !enough){
				ret += '<br/><b>Comments:</b> ';
				for (var i=0; i<comments.length; i++){
					ret += '<br/>'+comments[i]+'';
				}
			}

			if (b_errors.length != 0){
				if (!book_allowed){
					bep('<span class=\"hde\">No booking can be made for selected days.</span>');
				}
				if (ret != ''){ ret += '<br/>';}
				ret += '<span class=\"hde\">IMPORTANT:</span>';
				for (var i=0; i<b_errors.length; i++){
					ret += '<br/>'+b_errors[i]+'';
				}
			}
			if (where){
				if (ret != ''){ ret += '<br/>';}
				ret += '<br/><b>Location:</b> ' + where+'<br/>';
			}
			my_ret.html = ret;
			my_ret.errors = b_errors;
			my_ret.book_allowed = book_allowed;

		}

		return my_ret;
}


function the_button (ob) {
			var book_allowed = ob.book_allowed;
			var b_errors = ob.errors;
			var ret = '';

			if (book_allowed){
				if (b_errors.length != 0){
					ret += '<br/><center><span class=\"button-group\"><button style=\"font-size: 8pt;\" onclick=\"return book(\'wait\');\">Add me to the waiting list</button></span>';
					var link = "<a class=\"l_help\" href=\"javascript:void(0);\" onclick=\"return l_help(\'waiting\');\">";
//					ret += '<br/>'+link+'what is waiting list?</a>';
				} else {
					ret += '<br/><center><span class=\"button-group\"><button style=\"font-size: 8pt;\" onclick=\"return book(\'book\');\">Book now!</button></span>';
				}
			}
		return ret;
}

function the_cons_button (){
	var ret='';
	ret += '<br/><br/><center><span class="button-group"><button style="font-size: 8pt;" onclick="return book(\'close\');">Close the destination for these dates</button></span>';
	return ret;
}

function l_help (what){
	alert('explanation of ' + what);
	return false;
}






function setAuto(el){
	if (el.checked){
		is_auto = 'Y';
	} else {
		is_auto = 'N';
	}

}

function book(how){

	var msg = '<div id="confirm_booking">Please read this carefully!<br/>';
	if (how == 'book'){
		msg += "You are about to book a holiday.<br/>";
		msg += cost_msg;
		msg += "<br/>";
		msg += "<b>Cancellation Rules:</b>&nbsp;";
		msg += get_crules();
		msg += "<br/><br/>";
		var handleOK = function() {
				if (check_pwd()){
					do_book('book');
				} else {
					pwd_warn();
				}
		};
	} else if (how == 'wait'){
		gen_wishlist_ref();
		msg += "You are about to add yourself to a watinig list...<br/><br/>";
		if (max_waiting > 0){
			var s = ' ENTRIES';
			var w = max_waiting;
			if (max_waiting == 1){
				s = ' ENTRY';
				w = 'ONE';
			}
			msg += '<b>PLEASE NOTE THAT THIS BOOKING ALREADY HAS ' + w + s + ' IN THE WAITING LIST</b><br/>';
		}
		msg += '<input type="checkbox" onclick="setAuto(this);"> Automatically convert my waiting list entry to a booking once the destination becomes available<br/><br/>';
		msg += get_crules() +'<br/><br/>';
		var handleOK = function() {
				if (check_pwd()){
					do_book('wish');
				} else {
					pwd_warn();
				}
		};
	} else if (how == 'close'){
		msg += "<br/>You are about to close the destination for maintenance.<br/>";
		msg += "<br/>";
		if (!CO.object_id){
			msg += "Please provide a brief explanation below why are you closing the destination.<br/>";
			msg += '<textarea id="close_explain"></textarea>';
			msg += "<br/><br/>";
		} else {
			msg += '<input type="hidden" value="Closed by property owner" id="close_explain">';
		}
		var handleOK = function() {
			if (!CO.object_id){
				if (tmp_check_pwd()){
						do_book('close');
				} else {
						pwd_warn();
				}
			} else {
				if (check_pwd()){
						do_book('close');
				} else {
						pwd_warn();
				}
			}
		};
	} else if (how == 'open'){
		msg += "<br/>You are about to open the destination for bookings.<br/>";
		msg += "<br/>";
		msg += "<br/><br/>";
		var handleOK = function() {
					do_cancel('open');
		};

	}

	if (CM.under_focus == 0 || CC.object_id || CO.object_id){
		if (CC.object_id){ msg += 'Club Administrators ';}
		msg += 'Password:  <input type="password" id="c_pwd"><br/>';
	}
	msg += "Click OK to proceed, otherwise click Cancel</div>";

	YB(); // Show yahoo submit and cancel buttons, if hidden

	l_confirm(msg, handleOK);
	return false;
}



function do_book (how){

	var expl;
	if (how == 'close'){
		expl = ge('close_explain').value ;
		if (expl == ''){
			alert('The explanation can not be empty!');
			return false;
		}
	}

	ge('confirm_booking').innerHTML = 'Communicating with the server. Please wait...';

	hideYAHOOButtons();

	var r = new Object;
	r.typ = 'post';
	r.clas = 'fake';

	r.params = 'w=boo';
	r.params += '&de='+CFO.object_id;
	r.params += '&oc='+CFO.enhanced.occupancies[current_occupancy_idx].object_id;
	r.params += '&s_date='+dateFormatted2(startDate);
	r.params += '&e_date='+dateFormatted2(addDays2Date(endDate,-1));

	if (how == 'book'){
		r.params += '&is_wish=N';
	} else if (how == 'wish'){
		r.params += '&is_wish=Y';
	} else if (how == 'close'){
		if (!CO.object_id){
			r.params += '&is_wish=C';
		} else {
			r.params += '&is_wish=O';
		}
	}
	if (how != 'close'){
		r.params += '&days='+final_days;
		r.params += '&sab_days='+final_sab_days;
		r.params += '&year='+final_year;
		r.params += '&ab='+final_ab_credits;
		r.params += '&dollars='+final_dollars;
		r.params += '&mod='+mode;
		r.params += '&wishlist_ref='+wishlist_ref;
		r.params += '&is_auto='+is_auto;
		r.params += '&cm_tostring=' + escape(CM.to_string);
	} else {
		if (CC.object_id){
			r.params += '&cons_tostring=' + escape(CC.to_string);
		} else {
			r.params += '&cons_tostring=' + escape(CO.to_string);
		}
		r.params += '&explain='+escape(expl);
	}

  if(typeof(active_action_request) == 'object'){
    if(active_action_request.typ == 'post') {
      alert('Please wait while submiting form');
      return false;
    }
    active_action_request.aborted = true;
    active_action_request.req.abort();
  }
  action_requests = new Array();
  action_requests.push(r);
	return false;
}

function show_start_end(){
	if (CC_mode && CC_mode == 'browse'){
		return;
	}
	var start_w = 'Arrival';
	var end_w = 'Departure';
	if (CC.object_id || CO.object_id){
		start_w = 'Closing';
		end_w = 'Opening';
	}
		if (startDate.valueOf() != endDate.valueOf() ){
			ge("bValueDiv").innerHTML = "<b>"+start_w+":</b> " + printDate(startDate) + "; ";
			var diff = Math.round((endDate - startDate)/(1000*24*60*60));
			var ss = "s";
			if (diff == 1){
				ss = "";
			}
			ge("bValueDiv").innerHTML += "<b>"+end_w+":</b> " + printDate(endDate) + " (total " + diff + " night" + ss + ")";
			ge("bValueDiv").className='bvd';
			if (CC.object_id || CO.object_id){
				ge("bValueDiv").innerHTML += the_cons_button();
			}
		} else {
			ge("bValueDiv").className='bvdEmpty';
			ge("bValueDiv").innerHTML = '';
		}

}

function redisplay(){
	paint_it();
	show_start_end();
	if (!CC.object_id && !CM.object_id && !CO.object_id){ return;}
	if (CC.object_id || CO.object_id){
		return;
	} else {
		var booking_obj = getBookingCost();
		var booking_cost = booking_obj.html;
		var butt = the_button(booking_obj);

		show_mode();
		ge("bookingCostDiv").innerHTML = booking_cost;
		ge("bookingCostDiv").innerHTML += show_cancel(booking_obj);
		ge("bookingCostDiv").innerHTML += butt;
	}
}


function slRight() {
	var tmp_date = addDays2Date(baseDate, sl_scroll);
	var max_date = addDays2Date(addYears2Date(now_at_location,2), max_days-show_days) ;
	if (tmp_date > max_date){
		tmp_date = max_date;
	} 
	baseDate = tmp_date;
	startDate = addDays2Date(startDate, sl_scroll);
	endDate = addDays2Date(endDate, sl_scroll);
	generate_calendar();
	paint_bookings(current_occupancy_idx);
	paint_discounts(current_occupancy_idx);
	if (ciSlider){
		ciSlider.onSlideEnd();
	}
	if (coSlider){
		coSlider.onSlideEnd();
	}
}

function slLeft() {
	var tmp_date = addDays2Date(baseDate, -sl_scroll);
	if (tmp_date < now_at_location){
		tmp_date = now_at_location;
	} 
	baseDate = tmp_date;
	startDate = addDays2Date(startDate, -sl_scroll);
	endDate = addDays2Date(endDate, -sl_scroll);
	generate_calendar();
	paint_bookings(current_occupancy_idx);
	paint_discounts(current_occupancy_idx);
	if (ciSlider){
		ciSlider.onSlideEnd();
	}
	if (coSlider){
		coSlider.onSlideEnd();
	}
}

function show_mode (){
	ge("modeValueDiv").innerHTML = "<span class=\"hd\">Booking Type:</span> " + Modes[mode].name;
	ge("modeValueDiv").innerHTML += "<br/><span class=\"hd\">Booking Rules:</span> " + Modes[mode].brules;
}

function show_cancel (obj){
	var ret = '';
	if (obj.book_allowed){
		ret = "<br/><span class=\"hd\">Cancellation Rules:</span> " + get_crules();
	}
	return ret;
}


function get_crules(opt){

	var dtcancel;
	if(!opt) {
		dtcancel = (startDate-now_at_location)/(1000*60*60*24);
	} else {
		var dd = T['booking'].booking.start_date.local_c.day;
		var mm = T['booking'].booking.start_date.local_c.month;
		var yyyy = T['booking'].booking.start_date.local_c.year;
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));
		mode = T['booking'].booking.booking_type.code;
		dtcancel = (b_start-now_at_location)/(1000*60*60*24);
	}

	var crules;
	if (mode == 'ab'){
		if (dtcancel >= 100){
			crules = 'If you cancel this Advance Booking more than 100 Days before the Arrival Date, then the AB Credit(s) and Entitlement Days used to make this Booking will be restored to you, and any Entitlement Days that were converted to Space Available Days will be reconverted to Entitlement Days.';
		} else if (dtcancel >= 60){
			crules = 'If you cancel this Advance Booking between 100 and 60 Days before the Arrival Date, then the AB Credit(s) used to make this Booking will not be restored to you and the Entitlement Days that were used to make the Booking will be converted to Space Available Days. Any Entitlement Days that were converted to Space Available Days upon the making of this Booking shall remain as Space Available Days.';
		} else {
			crules = ' If you cancel this Booking 59 or less Days before the Arrival Date, then the AB Credit(s) and Entitlement Days used for the Booking will remain as fully charged, except that for each cancelled booked Day that is later booked by another Member at the same Destination, the Club will credit you with one Space Available Day.';
		}

	} else {
		if (dtcancel >= 60){
			crules = 'If you cancel this Space Available Booking not later than 61 days before the Arrival Date, then the Club will restore to you all Space Available Days or Entitlement Days used to make this Booking.';
		} else {
			crules = 'If you cancel this Space Available Booking before the Arrival Date, then the Entitlement Days and/or Space Available Days used for the Booking will remain as fully charged, except that for each cancelled booked Day that is later booked by another Member at the same Destination, the Club will credit you with one Space Available Day.';
		}

		
	}

	return crules;
}


function oc_availability(oc_idx){
	ge('oc_avail').innerHTML = CFO.availability_html;

}


function displayYAHOOButtons() {

	if (dlg) {
		dlg.hide();
		setTimeout("YB();",1000); //otherwise not looking pretty
	}

}

function YB() {
	var y_c = ge('y_control');
	if (y_c) {
		y_c.style.display = '';
			
	}
}
function hideYAHOOButtons() {

	var rows = getElementsByClass(ge('dlg'), 'ft', 'div' )
	if(rows.length > 0) {
		rows[0].id = 'y_control';
		rows[0].style.display = 'none';
	}

}



function booking_done(bo){
	var bt;
	if (bo.is_maintenance.yn == 'Y'){
		bt =  'The property has been marked as unavailable for the dates requested.<br/><br/>';
		bt += 'Click <a href="javascript:void(0);" onclick="displayYAHOOButtons();">here</a> to hide this message';
		ge("confirm_booking").innerHTML = bt;
	} else {
		if (bo.is_wishlist.yn == 'Y'){
			bt =  'You have been added to the waiting list for this destination.<br/><br/>';
			bt += 'You can cancel or amend this entry by clicking on "Waiting List" menu section.<br/><br/>';
			bt += 'Click <a href = "javascript:void(0)" onclick="make_member_waiting_list(1); displayYAHOOButtons(); return false;">here</a> to go to this page.<br>';
			ge("confirm_booking").innerHTML = bt;

		} else if (bo.is_wishlist.yn == 'N'){
			bt =  'New booking has been created.<br/><br/>';
			bt += 'The booking page has been created and corresponding menu item added under "Bookings" section.<br/><br/>';
			bt += 'Click <a href = "javascript:void(0)" onclick="return make_booking_page(\''+bo.object_id+'\');">here</a> to go to this page.<br>';

			var shared = 0;
			if (CM.plan.code == 'Shared'){
				shared = 1;
			} else if (CM.plan.code.indexOf('Trial') != -1){
				CM.nomore_bookings = 1;
			}

			ge("confirm_booking").innerHTML = bt;
			if (final_year == 1){
				CM.balance1.days = CM.balance1.days - final_days;
				CM.balance1.sab_days = CM.balance1.sab_days - final_sab_days;
				if (shared){
					CM.balance_ubm1.days = CM.balance_ubm1.days + final_days;
					CM.balance_ubm1.sab_days = CM.balance_ubm1.sab_days + final_sab_days;
				}
				if (mode == 'ab'){
					CM.balance1.sab_days_acquired = CM.balance1.sab_days_acquired - final_sab_days;
				}
			} else if (final_year == 2){
				CM.balance2.days = CM.balance2.days - final_days;
				CM.balance2.sab_days = CM.balance2.sab_days - final_sab_days;
				if (shared){
					CM.balance_ubm2.days = CM.balance_ubm2.days + final_days;
					CM.balance_ubm2.sab_days = CM.balance_ubm2.sab_days + final_sab_days;
				}
				if (mode == 'ab'){
					CM.balance2.sab_days_acquired = CM.balance2.sab_days_acquired - final_sab_days;
				}
			} else {
				CM.balance3.days = CM.balance3.days - final_days;
				CM.balance3.sab_days = CM.balance3.sab_days - final_sab_days;
				if (shared){
					CM.balance_ubm3.days = CM.balance_ubm3.days + final_days;
					CM.balance_ubm3.sab_days = CM.balance_ubm3.sab_days + final_sab_days;
				}
				if (mode == 'ab'){
					CM.balance3.sab_days_acquired = CM.balance3.sab_days_acquired - final_sab_days;
				}
			}
			CM.balance1.ab_credits = CM.balance1.ab_credits - final_ab_credits;
			if (shared){
				CM.balance_ubm1.ab_credits = CM.balance_ubm1.ab_credits + final_ab_credits;
			}
		}
	}

	CFO.enhanced.bookings.push(bo);

	paint_bookings(current_occupancy_idx);
	ge('oc_avail').innerHTML = bo.occupancy.destination.availability_html;

	if (!CC.object_id && !CO.object_id){
		var b = new Object;
		b['id'] = bo.object_id;
		b['name'] = bo.to_string;
		b['is_wishlist'] = bo.is_wishlist.yn;
		b['is_auto'] = bo.is_auto.yn;
		b['past'] = 0;
		b['deleted'] = 0;
		b['booking_type'] = bo.booking_type.code;
		b['destination_id'] = bo.occupancy.destination.object_id;
		var dd = bo.start_date.local_c.day;
		var mm = bo.start_date.local_c.month;
		var yyyy = bo.start_date.local_c.year;
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));	
		b['start_date'] = b_start;
		dd = bo.end_date.local_c.day;
		mm = bo.end_date.local_c.month;
		yyyy = bo.end_date.local_c.year;
		var b_end = new Date(Date.UTC(yyyy,mm-1,dd));	
		b['end_date'] = b_end;
	
		myBookings.push(b);
		refreshBookings();
		recalc_sab();
		search_is_dirty = true;

	} else {
		var c = 0;
		if (CC_mode != 'browse'){
			c = 1;
		}

		ge('d_left_pane').innerHTML='';
		ge('d_right_pane').innerHTML='';
		ge('d_left_pane').appendChild(make_bookings_list(c));
		ge('d_right_pane').appendChild(booking_details_templ(c));
	}
}

function conversion_done(bo){

	var bt;
	bt =  'New booking has been created.<br/><br/>';
	bt += 'The booking page has been created and corresponding menu item added under "Bookings" section.<br/><br/>';
	bt += 'Click <a href = "javascript:void(0)" onclick="return make_booking_page(\''+bo.object_id+'\');">here</a> to go to this page.<br>';
	ge("confirm_booking").innerHTML = bt;

	for (var i=0; i<myBookings.length; i++){
		if (myBookings[i].id == bo.object_id){
			myBookings[i].is_wishlist = 'N';
			myBookings[i].name = myBookings[i].name.split(",")[0];
		}
	}

	refreshBookings();
  make_member_waiting_list(1);
	search_is_dirty = true;
}

function booking_failed(bo){
	var bt='';
	CFO.enhanced.bookings.push(bo);
	paint_bookings(current_occupancy_idx);
	search_is_dirty = true;
	redisplay();
	bt =  'Sorry, but it appeared that somebody else has just booked these days out.<br/><br/>';
	bt += '<a href="javascript:closem();">Close</a>';
	ge("confirm_booking").innerHTML = bt;


}

function closem(){
	dlg.hide();
}

function oc_avail_onclick(){
               var when = getCookie('booking');
                if (when){
                        SetCookie('booking','',-1);
                } else {
                
                }

                init_slider(when,1);
}


// this will go to hacks.

function cancel_booking(){

        var msg = '<div id="confirm_booking">Please read this carefully!<br/>';
        msg += "You are about to cancel a booking...<br/><br/>";
        msg += get_crules(1) +'<br/><br/>';
        var handleOK = function() {
				if (check_pwd()){
					do_cancel();
				} else {
					pwd_warn();
				}
			};
	if (CM.under_focus == 0){
		msg += 'Password:  <input type="password" id="c_pwd"><br/>';
	}
       msg += "Click OK to proceed, otherwise click Cancel";
       l_confirm(msg, handleOK);  

	return false;
}

function cancel_wishlist(id){

	 T['cancel_wishlist_id'] = id;
        var msg = '<div id="confirm_booking">Please read this carefully!<br/>';
        msg += "You are about to cancel a wishlist item.<br/><br/>";
        var handleOK = function() {
				if (check_pwd()){
					ge('confirm_booking').innerHTML = 'Communicating with the server. Please wait...';
					hideYAHOOButtons();
					remove_wish();
				} else {
					pwd_warn();
				}
			};
	if (CM.under_focus == 0){

		msg += 'Password: <input type="password" id="c_pwd"><br/>';
	}
  msg += "Click OK to proceed, otherwise click Cancel";
	l_confirm(msg, handleOK);  
	return false;
}

function convert_wishlist(id){

	T['convert_wishlist_id'] = id;
  var msg = '<div id="confirm_booking">Please read this carefully!<br/>';
	msg += "You are about to convert a wishlist item to a booking.<br/><br/>";
	msg += "<b>Cancellation Rules:</b>&nbsp;";
	msg += "todo: add rules here.";
//	msg += get_crules();
	msg += "<br/>";
        var handleOK = function() {
				if (check_pwd()){
					ge('confirm_booking').innerHTML = 'Communicating with the server. Please wait...';
					hideYAHOOButtons();
					convert_wish();
				} else {
					pwd_warn();
				}
			};
	if (CM.under_focus == 0){
		msg += 'Password: <input type="password" id="c_pwd"><br/>';
	}
  msg += "Click OK to proceed, otherwise click Cancel";
 l_confirm(msg, handleOK);  
	return false;
}




function do_cancel(op){
	ge('confirm_booking').innerHTML = 'Communicating with the server. Please wait...';
	hideYAHOOButtons();

	var r = new Object;
	r.typ = 'post';
	r.clas = 'fake';
	r.params = 'w=booc';
	r.params += '&bid='+CB.object_id;
	if (T.concierge && T.concierge.obj){
		r.params += '&cid=' + T['concierge']['obj'].webauth.object_id;
	}
	if (op){
		r.params += '&op=1';
	}

  if(typeof(active_action_request) == 'object'){

    if(active_action_request.typ == 'post') {
      alert('Please wait while submiting form');
      return false;
    }
    active_action_request.aborted = true;
    active_action_request.req.abort();

  }
  action_requests = new Array();
  action_requests.push(r);
	return false;
}



function cancel_done (b){

	for (var i in myBookings){
		if (myBookings[i].id == b.object_id){
			myBookings[i]['deleted'] = 1;
		}
	}
	if (b.is_maintenance.yn == 'N'){
		refreshBookings();
		ge("confirm_booking").innerHTML  = 'Your booking was canceled and you will be redirected to the home page.<br/><br/>' + 
			'Click <a href = "javascript:void(0)" onclick="make_member_home(); return false;">here</a> to go to home page.<br>';
		search_is_dirty = true;
		CM.nomore_bookings = 0;
	} else {
		bt =  'The property has been marked as available for the dates requested.<br/><br/>';
		bt += 'Click <a href="javascript:void(0);" onclick="displayYAHOOButtons();">here</a> to hide this message';
		ge("confirm_booking").innerHTML = bt;
		for (var i=0; i<CFO.enhanced.bookings.length; i++){
			if (CFO.enhanced.bookings[i].object_id == b.object_id){
				CFO.enhanced.bookings[i].is_canceled.yn = 'Y';
			}
		}
		ge("bValueDiv").innerHTML = '';
		CB=null;
		var c = 0;
		if (CC_mode != 'browse'){
			c = 1;
		}
		paint_bookings(current_occupancy_idx);
		ge('oc_avail').innerHTML = b.occupancy.destination.availability_html;
		ge('d_left_pane').innerHTML='';
		ge('d_right_pane').innerHTML='';
		ge('d_left_pane').appendChild(make_bookings_list(c));
		ge('d_right_pane').appendChild(booking_details_templ(c));
	}

	return false;
}


function somewhere_else (sdate, edate){
	var cnt = 0;
	for (var i=0; i<myBookings.length; i++){
		if (myBookings[i].start_date >= edate || myBookings[i].end_date < sdate){
			continue;
		}
		if (myBookings[i].deleted == 1){continue};
//		if (myBookings[i].is_wishlist == 'Y'){continue};
		if (myBookings[i].destination_id == CFO.object_id){continue;}
		cnt++;
	}

	return cnt;
}


function seen_same_time (sdate,edate, destin){
	if (mode != 'ab'){
		return false;
	}
	for (var i=0; i<myBookings.length; i++){
		if (myBookings[i].destination_id != destin.object_id){continue;}
		if (myBookings[i].is_wishlist == 'Y'){continue;}
		if (myBookings[i].deleted == 1){continue;}
		//HERE
		var XXdays = 2;
		
		if (myBookings[i].start_date.getUTCFullYear() + 1 == sdate.getUTCFullYear()){
			var t_sdate = new Date(myBookings[i].start_date);		
			t_sdate.setUTCFullYear(sdate.getUTCFullYear());
			var t_edate = new Date(myBookings[i].end_date);

// BUG HERE!!! FIXME ASAP
			t_edate.setUTCFullYear(edate.getUTCFullYear());
			if (sdate >= addDays2Date(t_sdate,-XXdays) && edate <= addDays2Date(t_edate,XXdays)){
				return true;
			}
		}
	}
	return false;
	
}


function getClosestEnd(){
	for (var i = 0; i<=min_gap; i++){
      var tmp_d  = addDays2Date(startDate, -1-i);
			if (tmp_d <= baseDate){
				if (test_date_booked(current_occupancy_idx,tmp_d, 0)){
					return tmp_d;
				} else {
					continue;
				}
			}
      var td = ge(dateFormatted(tmp_d));
			if (td.getAttribute('booked') == 1){
				return addDays2Date(tmp_d, 1);
			}
    }
	
	return startDate;
}

function getClosestStart(){
	for (var i = 0; i<=min_gap; i++){
      var tmp_d  = addDays2Date(endDate, i);
			if (tmp_d >= addDays2Date(baseDate, show_days-1)){
				if (test_date_booked(current_occupancy_idx,tmp_d, 0)){
					return tmp_d;
				} else {
					continue;
				}
			}
      var td = ge(dateFormatted(tmp_d));
			if (td.getAttribute('booked') == 1){
				return addDays2Date(tmp_d,0);
			}
    }
	
	return startDate;
}


function getMyClosestEnd(){
	for (var i = 0; i<=min_my_gap; i++){
      var tmp_d  = addDays2Date(startDate, -1-i);
			if (tmp_d <= baseDate){
				if (test_date_booked(current_occupancy_idx,tmp_d, 1)){
					return tmp_d;
				} else {
					continue;
				}
			}
      var td = ge(dateFormatted(tmp_d));
			if (td.getAttribute('booked') == 1 && td.getAttribute('my_booking') == 1){
				return addDays2Date(tmp_d, 1);
			}
    }
	
	return startDate;
}

function getMyClosestStart(){
	for (var i = 0; i<=min_my_gap; i++){
      var tmp_d  = addDays2Date(endDate, i);
			if (tmp_d >= addDays2Date(baseDate, show_days)){
				if (test_date_booked(current_occupancy_idx,tmp_d, 0)){
					return tmp_d;
				} else {
					continue;
				}
			}
      var td = ge(dateFormatted(tmp_d));
			if (td.getAttribute('booked') == 1 && td.getAttribute('my_booking') == 1){
				return addDays2Date(tmp_d,0);
			}
    }
	
	return startDate;
}


function getOrigDays(){
	var t_date = new Date(startDate);
	var td = ge(dateFormatted(t_date));
	var bid = td.getAttribute('wishlist_ref');
	while (!bid){
		t_date = addDays2Date(t_date,1);
		td = ge(dateFormatted(t_date));
		bid = td.getAttribute('wishlist_ref');
	}
	var bo;
	for (var i=0; i<CFO.enhanced.bookings.length; i++){
		if (CFO.enhanced.bookings[i].object_id == bid){
			bo = CFO.enhanced.bookings[i];
			break;
		}
	}
		var dd = bo.start_date.local_c.day;
		var mm = bo.start_date.local_c.month;
		var yyyy = bo.start_date.local_c.year;
		var b_start = new Date(Date.UTC(yyyy,mm-1,dd));
		dd = bo.end_date.local_c.day;
		mm = bo.end_date.local_c.month;
		yyyy = bo.end_date.local_c.year;
		var b_end = new Date(Date.UTC(yyyy,mm-1,dd));
	
	var diff = (b_end - b_start)/(3600*24*1000);
			var sundays = 0;
			var start_on_sunday = 0;
			var booked_same_week = 0;
			var comments = new Array;
			var holiday_paid = 0;
			var ent_days = 0;
			var ab_c =0;
			for (var i=0; i<=diff; i++){
				var tmp_date = addDays2Date(b_start,i);
				var td_date = ge(dateFormatted(tmp_date));
				if (td_date){
					var booked  = td_date.getAttribute('booked');
					var holiday = td_date.getAttribute('holiday');
					var price   = td_date.getAttribute('price');
				} else {
					var booked  = 1;
					var holiday = 0;
					var price   = 1;

				}
				if (0 == i && tmp_date.getUTCDay() == 0){
					start_on_sunday = 1;
				} else { // check if someone has booking during same week
					var t_tmp_date = addDays2Date (baseDate,i);
					while (t_tmp_date.getUTCDay() != 0 && booked_same_week == 0 && t_tmp_date-baseDate >= 0){
						//freezing syndrome
						var t_booked = ge(dateFormatted(t_tmp_date)).getAttribute('booked');
						if (!t_booked || t_booked == 0){
							 t_tmp_date = addDays2Date(t_tmp_date,-1);
						} else {
							  booked_same_week = 1;
						}
					}
				}

				if (tmp_date.getUTCDay() == 0 && i != 0){
					sundays++;
				}

				if (booked==0 && price != 1 && disc_price_msg == 0){
					comments.push('Last minute booking discount has been applied to this time period.');
					disc_price_msg = 1;
				}
				ent_days++;

				if (mode == 'ab'){
					if (holiday && !holiday_paid){
						ab_c++;
						comments.push('additional AB credit taken because of booking the holiday (' + holiday + ')');
						holiday_paid++;
					}

				}
			} // end foreach day

			var t = new Object;
			t.ent_days = ent_days;
			t.ab_c = ab_c;
			t.sundays = sundays;
			t.comments = comments;
			t.booked_same_week = booked_same_week;
			t.to_string = bo.to_string;
	return t;
}


function getCurBal(sDate){
	// find out what year of membership we will be taking SAB days out from
	var cd =  CM.membership.commencement_date;
	var commencement_anniversary = new Date(Date.UTC(now_at_server.getUTCFullYear(), cd.getUTCMonth(), cd.getUTCDate()));
	while (commencement_anniversary <= now_at_server){
		commencement_anniversary.setUTCFullYear(commencement_anniversary.getUTCFullYear()+1);
	}

	// gotcha. commencement_anniversary is the end of first balance year.
			
	var curbal;
	var curyear = 1;
	var max_days;
	var max_ab;
	if (sDate < commencement_anniversary || CM.is_prepaid == 1){
		curbal = CM.balance1;
		max_days = CM.max_days_current;
		max_ab = CM.max_ab_current;
	} else {
		var tmp = new Date(commencement_anniversary);
		tmp.setUTCFullYear(tmp.getUTCFullYear()+1);
		if (sDate < tmp){
			curbal = CM.balance2;
			curyear = 2;
		} else {
			curyear = 3;
			curbal = CM.balance3;
		}
		max_days = CM.max_days_future;
		max_ab = CM.max_ab_future;
	}
	if (CM.is_primary == 'N'){
		if (max_days != ''){
			if (curbal.days > max_days){
				curbal.days = max_days;
			}
		}
		if (max_ab != ''){
			if (curbal.ab_credits > max_ab){
				curbal.ab_credits = max_ab;
			}
		}
	}
	var c = new Object;
	c.balance = curbal;
	c.year = curyear;
	return c;
}


function get_location_descript (id){
	var t = 'N/A';
	for (var i=0; i<CFO.schedule.length; i++){
		if (CFO.schedule[i].object_id == id){
			var z = CFO.schedule[i];
			return z.short_description.curlang + ' ('+date_formatted(z.start_date) + ' - ' + date_formatted(z.end_date) + ')';
		}
	}
	return t;
}


// Move this out of here please


var Modes = new Array;
var tmp = new Object;
tmp.name = 'Space Available Booking (30 days or less before the arrival)';
tmp.brules = 'Bookings may be for any combination of days up to 14 consecutive days';
Modes['sab30'] = tmp;
delete tmp;
var tmp = new Object;
tmp.name = 'Space Available Booking (31 to 60 days before the arrival)';
tmp.brules = 'Bookings may be made for up to a maximum of 14 consecutive days having both Depature and Arrival days on Sundays or Thursdays';
Modes['sab60'] = tmp;
delete tmp;

var tmp = new Object;
tmp.name = 'Space Available Booking (61 to 90 days before the arrival)';
tmp.brules = 'Bookings must be made for 7 or 14 days from Sunday to Sunday.';
Modes['sab90'] = tmp;
delete tmp;

var tmp = new Object;
tmp.name = 'Advanced Booking';
//tmp.brules = 'Bookings must be made for 7 or 14 consecutive Days commencing on Sunday and ending on Sunday.';
tmp.brules = 'Bookings must be for 7 or 14 consecutive Days, commencing on a Sunday and ending on  Sunday. A booking that includes a Special Holiday Date will use, in addition to the number of Days, 2 AB Credits. Bookings may be made for a period of less than 7 Days if the period booked is within one Sunday to Sunday time period. Any of the days in this 7 or 14 day period not booked, will be converted from Entitlement Days to Space Available Days for future use.';

Modes['ab'] = tmp;
delete tmp;


