/* 
 * Archers/Cosmos Tourama Website, Product Code Selectah
 * Author: Andy Gale
 *
 */

// Date a month in advance.
var now  = new Date();
now.setMonth(now.getMonth() + 1);

var selected_type       = 'normal'; 
var selected_duration   = null;
var selected_accomm     = null;
var selected_ext        = null; 
var selected_ext_accomm = null; 
var selected_day        = now.getDate();
var selected_month      = now.getMonth() + 1; 
var selected_year       = now.getFullYear();
var search_availability = false;
var code_selectah_version = null;

// Prefetch/Precache image
ikd = new Image();
ikd.src = '/content-styles/images/clock_anim.gif';

// Store whether a difference in core product duration effects
// the product code. It does not for some resort holidays.
var duration_difference = false;

function init_code_selectah(version)
{
		code_selectah_version = version;
    if (Ajax.getTransport()) {
        //supports ajax
    } else {
        cs = document.getElementById('codeselectah');
        cs.style.display = 'none';
        na = document.getElementById('noajaxmovealong');
        na.style.display = 'block';
        return;
    }

    tt = document.getElementsByName('tour_type');
    if (tt) { 
        for (i = 0; i < tt.length; i++) { 
            tt[i].onclick = check_selectah;
        }
    }

    durs = document.getElementsByName('duration');
    if (durs) {
        for (i = 0; i < durs.length; i++) { 
            durs[i].onclick = check_selectah;
        }
    }
    
    a = document.getElementById('accommodation');
    if (a) { 
        a.options.length = 0;
        a.options[0] = new Option('Please Select', 0);
        a.onchange = check_selectah;
    }

    ext = document.getElementsByName('extension');
    if (!ext) { 
        alert('init_product_details: tags with name extension not found');
        return;
    }

    for (i = 0; i < ext.length; i++) { 
        ext[i].onclick = check_selectah;

    }

    ea = document.getElementById('extension_accommodation');
    if (ea) { 
        ea.onchange = check_selectah;
    }
    
    ga2 = document.getElementById('get_availability2');
    if (ga2) { 
        ga2.onclick = submit_availability_form;
    }

    gd = document.getElementById('get_debugging');
    if (gd) { 
		gd.onclick = debug_availability;
    }

    duration_difference = false;
    
    // Work out if duration effects the product codes
    for (i = 0; i < product_codes.length; i++) { 
        p = product_codes[i];
        if (p[2] != null && p[4] == null) { 
            duration_difference = true;
            break;
        }
    }

    if (related_accomm_id > 0) { 
        selected_accomm = related_accomm_id;
    }

    fill_selectah();
	
	if (search_availability) { 
		offset_fetch(selected_month, selected_year);
	}
}

/* get_selectah_values
 *
 * Get selected values from selectah and fill global vars defined at top.
 *
 */ 

function get_selectah_values()
{
    // Type: (radios) 'normal', 'platinum' or 'costcutter'
    selected_type = 'normal';

    tt = document.getElementsByName('tour_type');
    if (tt) { 
        for (i = 0; i < tt.length; i++) { 
            if (tt[i].checked) {
                selected_type = tt[i].value;
                break;
            }
        }
    }
    
    // Duration: (radios) only if explicitly selected
    selected_duration = null;

    durs = document.getElementsByName('duration');
    if (durs) {
        for (i = 0; i < durs.length; i++) { 
            if (durs[i].checked) { 
                selected_duration = durs[i].value;
            }
        }
    }

    // Accommodation: (select) again, only if selected
    acc = document.getElementById('accommodation');
    if (acc) { 
        selected_accomm = acc.options[acc.options.selectedIndex].value;
        if (selected_accomm == 0) { 
            selected_accomm = null;
        }
    } else {
        selected_accomm = null;
    }
	
    if (related_accomm_id > 0) { 
        selected_accomm = related_accomm_id;
    }

	if (!this_linked_product) { 
	
		// Extension: (radios)
		selected_ext = null;

		exts = document.getElementsByName('extension');
		if (exts){ 
			for (i = 0; i < exts.length; i++) { 
				ext = exts[i].id.substr(10);
            
				if (exts[i].checked) { 
					selected_ext = ext;
					break;
				}
			}
		}

		if (selected_ext == 'no') { 
			selected_ext = null;
		}
 
		// Extension Accommodation: (select)
		selected_ext_accomm = null;
    
		exa = document.getElementById('extension_accommodation');
		product_type_obj = document.getElementById('product_type');
		if (product_type_obj) {
			product_type = product_type_obj.value;
		} else {
			product_type = 'none';
		}
		if (exa && !exa.disabled && (product_type != 'resort')) { 
			selected_ext_accomm = exa.options[exa.options.selectedIndex].value;
		}
	} else { 
		selected_ext = null;
		
		exa = document.getElementById('extension_accommodation');
		if (exa && !exa.disabled) { 
			selected_ext_accomm = exa.options[exa.options.selectedIndex].value;
		}
	}
	
	//alert("fill_selectah: got following values...\n\n" + 
	//	  "selected_type       = '" + selected_type + "'\n" +
	//        "selected_duration   = '" + selected_duration + "'\n" +
	//	  "selected_accomm     = '" + selected_accomm + "'\n" +
	//	  "selected_ext        = '" + selected_ext + "'\n" +
	//	  "selected_ext_accomm = '" + selected_ext_accomm + "'\n" +
	//       "selected_day        = '" + selected_day + "'\n" +
	//	  "selected_month      = '" + selected_month + "'\n" +
	//	  "selected_year       = '" + selected_year + "'\n");
}

function fill_selectah()
{
    // Select type
    tt = document.getElementsByName('tour_type');
    if (tt) { 
        for (i = 0; i < tt.length; i++) { 
            if (tt[i].value == selected_type) {
                tt[i].checked = true;
                break;
            }
        }
    }

    // Select duration
    durs = document.getElementsByName('duration');
    if (durs) {
        found_a_duration = false;
        
        for (i = 0; i < durs.length; i++) { 
            if (durs[i].value == selected_duration) { 
                durs[i].checked = true;
                found_a_duration = true;
                break;
            }
        }
         
        // If the user has not selected a duration, select the first, by default.
        if (!found_a_duration && durs[0]) { 
            durs[0].checked = true;
        }
    }
	
    // Work out possible accommodation for selected duration and type
    possible_accommodation = new Array();

    for (i = 0; i < product_codes.length; i++) { 
        p = product_codes[i];
		
        if ((selected_duration == null || duration_difference == false || p[2] == selected_duration || p[2] == null) && 
            (selected_type == 'normal' || (selected_type == 'platinum' && p[1]))) 
        { 
            if (accomm_choice_a[p[3]]) { 
                possible_accommodation[p[3]] = true;
            }
        }
    }
		
	// Get selected accommodation to maintain selected accommodation if
    // possible after duration update
    acc = document.getElementById('accommodation');
    if (acc) { 
        // Rebuild accommodation list
        opt = acc.options[0];
        acc.options.length = 0;
        j = 0;
        
        acc.options[j++] = opt;
        
        for (i in possible_accommodation) { 
            // Stop Prototype ruining our array
            if (isNaN(parseInt(i))) {
                continue;
            }
                  
            acc.options[j] = new Option(accomm_choice_a[i], i);
            
            if (i == selected_accomm || (!selected_accomm && related_accomm_id == i)) { 
                acc.options[j].selected = true;
            } 
            
            j++;
        }
    }

	//alert('fill_selectah: after: ' + acc.selectedIndex + ', selected_accomm: ' + selected_accomm);
	
	possible_extensions = new Array();
	possible_extensions_accommodation = new Array();
	
	if (!this_linked_product) { 
	
		// Work out which extensions are possible with the selections made so far...
    
		for (i = 0; i < product_codes.length; i++) { 
			p = product_codes[i];
        
			if ((p[3] == selected_accomm || selected_accomm == null) && p[4] && 
				(selected_type == 'normal' || (selected_type == 'platinum' && p[1]))) 
			{ 
				possible_extensions[p[4]] = true;
			}
		}

		// Hide extensions that are not possible with the selections made so far...
		eul = document.getElementById('extensionsul');
		if (eul) { 
			for (i in extensions) { 
				// Stop Prototype ruining our array
				if (isNaN(parseInt(i))) {
					continue;
				}
   
				obj = document.getElementById('linked' + i);
				if (!obj) { 
					alert('fill_selectah: linked >' + i + '< not found');
					return;
				}
            
				if (possible_extensions[i]) { 
					obj.style.display = 'block';
				} else {
					obj.style.display = 'none';
				}
			}
		}
		
		// Unchecked extension radio button if it has been hidden
		exts = document.getElementsByName('extension');
		if (exts){ 
			no = false;
        
			for (i = 0; i < exts.length; i++) { 
				ext = exts[i].id.substr(10);
        
				if (ext == 'no') { 
					no = exts[i];
					continue;
				}	
            
				if (!possible_extensions[ext] && exts[i].checked) { 
					no.click();
					break;
				}
			}
		}
    
		// Select extension (or No thanks)
		exts = document.getElementsByName('extension');
		if (exts){ 
			no = false;
        
			for (i = 0; i < exts.length; i++) { 
				ext = exts[i].id.substr(10);
            
				if ((ext == 'no' && selected_ext == null) || (possible_extensions[ext] && ext == selected_ext)) { 
					exts[i].checked = true;
				}
			}
		}
    
		// Work out which extension accommodations are possible with the
		// selections made so far...

		for (i = 0; i < product_codes.length; i++) { 
			p = product_codes[i];
        
			if ((selected_accomm == null || p[3] == selected_accomm) && p[4] == selected_ext) { 
				possible_extensions_accommodation[p[5]] = true;
			}
		}
		
	} else { 
		// This is a linked product - work out which extensions are possible

		for (i = 0; i < product_codes.length; i++) { 
			p = product_codes[i];
        
			if ((selected_accomm == null && possible_accommodation.length == 0) || p[3] == selected_accomm) { 
				possible_extensions_accommodation[p[5]] = true;
			}
		}	
	}
	
	// Populate extension accommodation drop down
	exa = document.getElementById('extension_accommodation');
	product_type_obj = document.getElementById('product_type');
	if (product_type_obj) {
		product_type = product_type_obj.value;
	} else {
		product_type = 'none';
	}
	if (exa && (product_type != 'resort')) { 
		exalabel = getLabelById('extension_accommodation');
		if (!exalabel) { 
			alert('check_selectah: extension_accommodation label not found');
			return;
		}
        
		exa.options.length = 0;
        
		j = 0;
		if (possible_extensions_accommodation.length) { 
			exa.disabled = false;
			exalabel.className = '';
			for (i in possible_extensions_accommodation) { 
				// Stop Prototype ruining our array
				if (isNaN(parseInt(i))) {
					continue;
				}
   
				if (!this_linked_product) { 
					exa.options[j++] = new Option(extension_accommodations[selected_ext][i], i);        
				} else {
					exa.options[j++] = new Option(extension_accommodations[i], i);  
				}
			}
		} else {
			exa.disabled = true;
			exalabel.className = 'disabled';
		}

		if (!selected_ext_accomm && exa.options.selectedIndex == 0) { 
			selected_ext_accomm = exa.options[0].value;
		}
	}
		
    // Select selected extension accommodation
    if (exa && !exa.disabled && selected_ext_accomm) { 
        for (i = 0; i < exa.options.length; i++) { 
            if (exa.options[i].value == selected_ext_accomm) { 
                exa.options[i].selected = true;
            }
        }
    }
	
    get_selectah_values();

    c = document.getElementById('calendar');

    if (!c) { 
		/*alert('required element "calendar" not found');*/
		return;
	}

	// Do not complain about lack of an element as it will not exist on the 
    // version Cosmos are styling.
        
    code = lookup_product_code();
    if (code) { 
         c.disabled = false;
         c.onclick = fetch_calendar;
    } else {
         c.onclick = calendar_alert;
    }
}


function calendar_alert(){
    alert("Please select your accommodation");
}

function check_selectah()
{
    get_selectah_values();
    fill_selectah();
}

function lookup_product_code()
{
    found_code = false;

    for (i = 0; i < product_codes.length; i++) { 
        p = product_codes[i];
        
        if ((selected_duration == p[2] || single_duration && single_duration == p[2] || !duration_difference ||
             (selected_ext && extension_durations[selected_ext] && extension_durations[selected_ext] == p[2]))
            && selected_accomm == p[3] && p[4] == selected_ext
            && p[5] == selected_ext_accomm) 
        { 
            if (selected_type == 'normal') { 
                found_code = p[0];
                break;
            } else if (selected_type == 'platinum') { 
                found_code = p[1];
                break;
            } else {
                alert('unknown handled type =>' + selected_type + '<=');
                return;
            }
        }
    }

    return found_code;
}

function submit_availability_form(day, month, year, debug)
{
    get_selectah_values();

    if (!selected_duration && !single_duration)  {
        alert('Please select a duration');
        return;
    }

    acc = document.getElementById('accommodation');
    if (acc) { 
        if (!selected_accomm && acc.options.length > 1) { 
            alert('Please select some accommodation');
            return;
        }
    }
    
    found_code = lookup_product_code();

    if (!found_code) { 
        alert('Unable to determine product code');
        return;
    }

    script = 'content/search-availability.php';
    if (debug == true) { 
        script = 'content/debug-availability.php';
    }

    // Fill in availability form
    at = document.getElementById('avail_type');
    if (!at) { 
        alert('submit_availability_form: avail_type not found');
        return;
    }

    at.value = selected_type;
    
    at = document.getElementById('avail_duration');
    if (!at) { 
        alert('submit_availability_form: avail_duration not found');
        return;
    }

    if (selected_duration) { 
        at.value = selected_duration;
    } else if (selected_ext && extension_durations[selected_ext]) { 
        at.value = extension_durations[selected_ext];
    } else if (single_duration) { 
        at.value = single_duration;
    }
	
    at = document.getElementById('avail_accomm');
    if (!at) { 
        alert('submit_availability_form: avail_accomm not found');
        return;
    }

    if (selected_accomm) {
        at.value = selected_accomm;
    } else {
        at.value = '';
    }
    
    at = document.getElementById('avail_ext');
    if (!at) { 
        alert('submit_availability_form: avail_ext not found');
        return;
    }

    if (selected_ext) { 
        at.value = selected_ext;
    } else {
        at.value = '';
    }
    
    at = document.getElementById('avail_ext_accomm');
    if (!at) { 
        alert('submit_availability_form: avail_ext_accomm not found');
        return;
    }
    
    if (selected_ext_accomm) { 
        at.value = selected_ext_accomm;
    } else {
        at.value = '';
    }

    ad = document.getElementById('avail_day');
    if (!ad) { 
        alert('submit_availability_form: avail_day not found');
        return;
    }

    ad.value = day;

    ad = document.getElementById('avail_month');
    if (!ad) { 
        alert('submit_availability_form: avail_month not found');
        return;
    }
    
    ad.value = month;

    ad = document.getElementById('avail_year');
    if (!ad) { 
        alert('submit_availability_form: avail_year not found');
        return;
    }

    ad.value = year;

    at = document.getElementById('avail_product_code');
    if (!at) { 
        alert('submit_availability_form: avail_product_code not found');
        return;
    }

    at.value = found_code;

    f = document.getElementById('avail_form');
    if (!f) { 
        alert('submit_availability_form: avail_form not found');
        return;
    }

    f.action = '/'  + script;
    
    //leigh added 10/August/07 to show "waiting for avail" popup.
    popup = document.getElementById("processing");
    if(popup){
        selects = document.getElementsByTagName('select');
        
        for (i = 0; i < selects.length; i++) { 
            selects[i].style.display = 'none';
        }
         
        popup.style.display = 'block';	
    }
    
    f.submit();
}

/*
function calendar_popupwin()
{
    product_code = lookup_product_code();
    
    url = '/content/calendar-availability.php?product_code=' + product_code;

    day = new Date();
    id  = day.getTime();

    window.open(url, id, 'width=300,height=300,left=340,top=362');
}
*/

var daystr = new Array('BAD Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

var monthstr = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 
                         'August', 'September', 'October', 'November', 'December');

var this_month_index = -1;
var no_results = false;
var no_results_for_version = false;

/* PLEASE NOTE: 
 * 
 * All the month functions below EXPECT MONTHS 1-12 (i.e. January is 1 NOT 0) 
 *
 */

function getMonthFirstDay(m_month, m_year)
{
    d = new Date(m_year, m_month - 1, 1);
    a = d.getDay();
    if (a == 0) { 
        return 7;
    } else {
        return a;
    }
}

function getMonthLen(m_month, m_year)
{
    nextMonth = new Date(m_year, m_month, 1);
    nextMonth.setHours(nextMonth.getHours() - 3);
    return nextMonth.getDate();
}

function getMonthName(m_month)
{
    return monthstr[m_month - 1];     
}

/* PLEASE NOTE::: Ends here */

// This is written for a purpose... it will not work with everything.
function myParseInt(number)
{
    if (number[0] == '0') { 
        number = number[1];
    }
    
    return number;
}

function fetch_calendar()
{
    offset_fetch(0, 0);
}

function offset_fetch(m_month, m_year)
{
    m_month = myParseInt(m_month);
    m_year  = myParseInt(m_year);
    pc      = lookup_product_code();

		getting_dates();
		
    //alert('/content/availability-calendar.php?product_code=' + pc + '&version=' + code_selectah_version + '&month=' + m_month + '&year=' + m_year);
		no_results = false;
		no_results_for_version = false;

    new Ajax.Request('/content/availability-calendar.php?product_code=' + pc + '&version=' + code_selectah_version + '&month=' + m_month + '&year=' + m_year,
    {
        method: 'get',
        onSuccess: display_calendar,
        onFailure: function(){ alert('Something went wrong...') }    
     } );
}

var backup_codeselectah_top = null;

function getting_dates()
{
    backup_codeselectah_top = $('codeselectah_top').innerHTML;
    $('codeselectah_top').innerHTML = '<img src="/content-styles/images/clock_anim.gif" />';
}

function display_calendar(transport)
{
    var response = transport.responseText || '';
    eval(response);

    // Delete any old rows
    tbody = $('tablebody');
    while (tbody.rows.length > 0) { 
        tbody.deleteRow(0);
    }

	if (no_results) { 
		// There are no results.
		$('codeselectah_top').innerHTML = 'CHECK PRICES<br /><span>&amp; AVAILABILITY</span>';
		$('noresultscont').style.display = 'block';
		$('noresultsversion').style.display = 'none';
		$('ajaxcalendar').style.display = 'none';  
	} else if (no_results_for_version) {
		// There are no results for this version, but there are results for another version.
		$('codeselectah_top').innerHTML = 'CHECK PRICES<br /><span>&amp; AVAILABILITY</span>';
		$('noresultscont').style.display = 'none';
		$('noresultsversion').style.display = 'block';
		$('ajaxcalendar').style.display = 'none';  
	} else {
		$('noresultscont').style.display = 'none';
		$('noresultsversion').style.display = 'none';
	}
	    
    var done       = false;
    var firstday   = getMonthFirstDay(current_month, current_year);
    var howmany    = getMonthLen(current_month, current_year);
    var daycounter = 1;

	//alert('The first day of ' + monthstr[current_month - 1] + ' is ' + daystr[firstday]);
	
    while (!done) { 
        // Create new row (at end)
        newr = tbody.insertRow(tbody.rows.length);
        if (newr) { 
            for (var i = 1; i <= 7 ; i++) { 
                // Create new cell (at end)
                newc = newr.insertCell(newr.cells.length);

                if (tbody.rows.length == 1 && i < firstday) { 
                    // empty boxes before first day
                    newc.innerHTML = '&nbsp;';
                    continue;
                }
                
                if (daycounter == howmany) { 
                    // No more rows after this one
                    done = true;
                }

                if (daycounter <= howmany) { 
                    newc.innerHTML = daycounter;

                    if (dates[daycounter]) { 
					  /* if (dates[daycounter].length>1 || dates[daycounter][0] != '') { */
                        newc.className   = 'avail';
                        newc.onclick     = calendar_click;
					  /*}*/
                    }

                    daycounter++;
                } else {
                    newc.innerHTML = '&nbsp';
                }
            }
        } else {
            done = true;
        }
    }

    // Populate drop down
    var am = $('avail_months');
    
    am.options.length = 0;
    this_month_index = -1;

    for (var i = 0; i < avail_months.length; i++) {
        var mm = avail_months[i].split('/');

        im = myParseInt(mm[0]);
        iy = myParseInt(mm[1]);

        am.options[i] = new Option(monthstr[im - 1] + ' ' + iy, avail_months[i]);
        
        if (im == current_month && iy == current_year) { 
            this_month_index = i;
        }
    }
    
    //alert(this_month_index);

    am.selectedIndex = this_month_index;

    am.onchange = load_selected_month;

    nm = $('next_month');
    pm = $('previous_month');

    if (this_month_index == 0) { 
        // Hide previous available month button
        pm.style.visibility = 'hidden';
        pm.onclick = null;
    } else {
        pm.style.visibility = 'visible';
        pm.onclick = load_previous_month;
    }
    
    if (this_month_index == avail_months.length - 1) { 
        // Hide next available month button
        nm.style.visibility = 'hidden';
        nm.onclick = null;
    } else {
        nm.style.visibility = 'visible';
        nm.onclick = load_next_month;
    }

    if (!no_results && !no_results_for_version) {
			$('ajaxcalendar').style.display = 'block';    
		}
    $('codeselectah_top').innerHTML = 'CHECK PRICES<br /><span>&amp; AVAILABILITY</span>';
}

function load_previous_month()
{
    mm = avail_months[this_month_index - 1].split('/');
    offset_fetch(mm[0], mm[1])
} 

function load_next_month()
{
    mm = avail_months[this_month_index + 1].split('/');
    offset_fetch(mm[0], mm[1]);
}

function load_selected_month()
{
    mm = this.options[this.selectedIndex].value.split('/');
    offset_fetch(mm[0], mm[1]);
}

function calendar_click()
{
    day = this.innerHTML;

    submit_availability_form(day, current_month, current_year, false);
}

function debug_availability()
{
	if (!search_availability) { 
		alert('please click a date first');
	} else {
		submit_availability_form(selected_day, selected_month, selected_year, true);
	}
}

function pad(number, length) {
    var str = '' + number;
    while (str.length < length)
        str = '0' + str;
    return str;
}
