/* Shows the room info lines with titles and inputs for num adults and num children */
function showRooms(roomPrefix) {
    roomsSelected = new Number(numRoomsSelected())-1;//make zero-based
    for (row = 0; row < totalPossibleRooms; row++) {
        if (row <= roomsSelected && !isGroup()) {
            eval("document.getElementById('" + roomPrefix + row + "').style.display = ''");
        } else {
            eval("document.getElementById('" + roomPrefix + row + "').style.display = 'none'");
        }
    }
}

/*
    Control the display of the room information. Display the correct title on the row for the specified room.
    Display the child count dropdown. Display the column titles and the room rows in the child age section.
    When I say "display" here, I mean display or don't display depending on varioius conditions.

    @param roomId identifies the room the children belong to (e.g. 1, 2, 3)
    @param ageRowName the age row id/name that for the room (e.g. room1ages, room2ages, etc)
    @param ageItemPrefix the prefix name for each room/age combination (e.g. room1age1 - room1age is the prefix)

*/
function showRoomInfo(roomId, ageRowName, ageItemPrefix) {
    var childBoxPrefix = 'childroom';
    //var ageTitlePrefix = 'ageTitle';
    var childSelected = document.getElementById(childBoxPrefix + roomId).value;
    displayElementForRoomType("unitTitle" + roomId);
    eval("document.getElementById('" + childBoxPrefix + roomId + "').style.display = ''");
    if (childSelected > 0 && numRoomsSelected() > roomId && !isGroup() && roomType == "hotel") {
        eval("document.getElementById('" + ageRowName + "').style.display = ''");
        showAges(roomId, childBoxPrefix+roomId, ageItemPrefix);
    } else {
        eval("document.getElementById('" + ageRowName + "').style.display = 'none'");
        showAges(roomId, childBoxPrefix+roomId, ageItemPrefix);
    }
}

/*
    Displays/hides the age selection for each child in each room

    @param childBoxName the name of the selection box for the number of children for a room (e.g. childRoom1, childRoom2, etc)
    @param ageItemPrefix the prefix name for each room/age combination (e.g. room1age1 - room1age is the prefix)
*/
function showAges(roomId, childBoxName, ageItemPrefix) {
    var childSelected = document.getElementById(childBoxName).value;
    childSelected = new Number(childSelected) - 1; //make zero-based
    for (row = 0; row < totalPossibleChildren; row++) {
        var elem = document.getElementById(ageItemPrefix + row);
        if (elem) {
            var ageFormElement = "OIdx["+roomId+"].CAIdx["+row+"]";
            if (row <= childSelected && roomType == "hotel") {
                //eval("document.getElementById('" + ageItemPrefix + row + "').style.display = ''");
                elem.style.display = "";
                document.getElementById(ageFormElement).disabled = false;
            } else {
                //eval("document.getElementById('" + ageItemPrefix + row + "').style.display = 'none'");
                elem.style.display = "none";
                document.getElementById(ageFormElement).disabled = true;
            }
        }
    }
}

/*
    Shows the titles above the ages (e.g. child 1, child 2, etc) depending of how many children there
    are in the row with the most children for which we need ages.

    @param childBoxPrefix the prefix name for the number of children per room (e.g. childRoom)
    @param ageItemPrefix the prefix name for each room/age combination (e.g. room1age1 - room1age is the prefix)
*/
function showAgeTitles() {
    var childBoxPrefix = 'childroom';
    var ageTitlePrefix = 'ageTitle';
    showAgeMessage();
    var maxChildren = 0;
    
    if (!isGroup() && roomType == "hotel") {
        for (room = 0; room < numRoomsSelected(); room++) {
            childCnt = document.getElementById(childBoxPrefix + room).value;
            if (childCnt > maxChildren) {
                maxChildren = childCnt;
            }
        }
    }
    if (maxChildren > 0) {
        document.getElementById("ageTitles").style.display = '';
    } else {
        document.getElementById("ageTitles").style.display = 'none';
    }
    for (title = 0; title < maxChildren; title++) {
        var elem = document.getElementById(ageTitlePrefix + title);
        if (elem) {
            elem.style.display = '';
        }
    }
    for (title = maxChildren; title < totalPossibleChildren; title++) {
        var elem = document.getElementById(ageTitlePrefix + title);
        if (elem) {
            elem.style.display = 'none';
        }
    }
}

/*
    Shows the instructional message for selecting the individual ages.  The message should not be
    shown if not needed.

    @param childBoxPrefix the prefix name for the number of children per room (e.g. childRoom)
*/
function showAgeMessage() {
    var childBoxPrefix = 'childroom';
    var maxChildren = 0;
    var childCnt = 0;
    if (!isGroup() && roomType == "hotel") {
        for (room = 0; room < numRoomsSelected(); room++) {
            childCnt = eval("document.getElementById('" + childBoxPrefix + room + "').value");
            if (childCnt > 0) {
                break;
            }
        }
    }
    if (childCnt > 0) {
        document.getElementById('ageMessage').style.display = '';
    } else {
        document.getElementById('ageMessage').style.display = 'none';
    }
}

function numRoomsSelected(){
    var roomsSelected = document.getElementById("rooms").value;
    return roomsSelected;
}

function isGroup() {
    var roomsSelected = document.getElementById("rooms").value;
    return (roomsSelected > totalPossibleRooms);
}

function selectRoomType() {
    roomType = "hotel";
    roomMaxGuests = 4;
    roomMinAdults = 1;
    roomMaxChildren = 8;
    var typeStop = false;
    //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
    if (document.forms[0].name == "myform") {
        var box = document.forms[0].allPropertyTypesSelected;
        var isPropertyPage = document.forms[0].isPropertyPage;
        var isCondo = document.forms[0].isCondo;
    } else {
        var box = document.forms[1].allPropertyTypesSelected;
        var isPropertyPage = document.forms[1].isPropertyPage;
        var isCondo = document.forms[1].isCondo;
    }
    
    if (isPropertyPage != null && isPropertyPage.value == "true") {
        if (isCondo != null && isCondo.value == "true") {
            roomMaxGuests = 4;
            roomType = "condo";
            roomMaxChildren = 8;
        } else {
            roomMaxGuests = 8;
            roomType = "hotel";
            roomMaxChildren = 8;
        }
    } else {
    
    
    
    if (box) {
        if (box.type == "hidden") {
            val = "false" != box.value;
        }
        else {
            val = box.checked;
        }
        if (val) {
            for (i=0 ; i < checkBoxId.length ; ++i) {
                if ("text.property.hotelPropertyType" == checkBoxId[i] || "text.property.resortPropertyType" == checkBoxId[i]) {
                    roomType = "hotel";
                    roomMaxGuests = checkBoxMaxGuests[i];
                    roomMinAdults = checkBoxMinAdults[i];
                    roomMaxChildren = 8;
                    break;
                }
            }
        }
        else {
            for (i=0 ; i < checkBoxId.length ; ++i) {
                //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
                if (document.forms[0].name == "myform") {
                    box = document.forms[0][checkBoxFormField[i]];
                } else {
                    box = document.forms[1][checkBoxFormField[i]];
                }
                if (box) {
                    if (box.type == "hidden") {
                        val = "false" != box.value;
                    }
                    else {
                        val = box.checked;
                    }
                    if (val) {
                        if (checkBoxType[i] == "condo") {
                            roomMaxChildren = 8;
                        } else {
                                roomMinAdults = checkBoxMinAdults[i];
                                roomMaxChildren = 8;
                        }
                        
                        if (!typeStop) {
                            roomType = checkBoxType[i];
                            if (roomType == "hotel") {
                                typeStop = true;
                            }
                        }
                        
                        if (roomMaxGuests < checkBoxMaxGuests[i]) {
                            roomMaxGuests = checkBoxMaxGuests[i];
                        }
                        if (checkBoxType[i] == "hotel" && roomMinAdults < checkBoxMinAdults[i]) {
                            roomMinAdults = checkBoxMinAdults[i];
                        }
                    }
                }
            }
        }
      }
    }
    //roomMaxChildren = roomMaxGuests - roomMinAdults;
    
    //property page override
    //For the property page the search type (blended, hotel/condo only) is overridden to be property specific
    //instead of search type specific to ensure a condo that is viewed from a blended search path shows the correct labels. 
    if (document.forms[0].isPropertyPage != null && document.forms[0].isPropertyPage.value == "true") {
        if(document.forms[0].isCondo != null &&  document.forms[0].isCondo.value == "true") {
            roomType = "condo";
        } else {
            roomType = "hotel";
        }
    }
    
}

/*
    This function will display one of two elements by id. It takes the supplied
    title and appends .condo and .hotel and displays the one that matches the
    room type and hides the other one.
*/
function displayElementForRoomType(title) {
    
    eval("document.getElementById('" + title + ".condo" + "').style.display = 'none'");
    eval("document.getElementById('" + title + ".hotel" + "').style.display = 'none'");
    eval("document.getElementById('" + title + "." + roomType + "').style.display = ''");
}

/*    update the numbers in the dropdowns for number of adults and number of children */
function updateAdultChildDropdowns() {
    var adults;
    var children;
    //roomMaxChildren = 14;
    roomsSelected = new Number(numRoomsSelected())-1;//make zero-based
    //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
    if (document.forms[0].name == "myform") {
        adults = document.forms[0].numadults; // handle the NS4 form
    } else {
        adults = document.forms[1].numadults; // handle the NS4 form
    }
    updateAdultDropdown(adults, roomsSelected + 1, roomMaxGuests * (roomsSelected + 1));
    //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
    if (document.forms[0].name == "myform") {
        children = document.forms[0].numchildren;
    } else {
        children = document.forms[1].numchildren;
    }
    updateChildDropdown(children, roomMaxChildren * (roomsSelected + 1));
    if (children) {
        children.disabled = (roomType != "hotel");
    }

    adults = document.getElementById("adultroom0");
    if (adults) {   // handle the non NS4 form 
        for (j = 0 ; j < totalPossibleRooms ; ++j) {
            adults = document.getElementById("adultroom" + j);
            updateAdultDropdown(adults, 1, roomMaxGuests);
            
            children = document.getElementById("childroom" + j);
            updateChildDropdown(children, roomMaxChildren);

            if (j <= roomsSelected && !isGroup()) {
                adults.disabled=false;
                children.disabled=false;
            } else {
                adults.disabled=true;
                children.disabled=true;
            }
        }
    }
}

/* update one dropdown for the adult count for one room 
   @param adults the select box form field for which we are changing the options 
   @param limit the highest number allowed in the dropdown (1 is lowest)
*/
function updateAdultDropdown(adults, minimum, limit) {
    if (adults && adults.options.length != limit) {
        var selectedAdult = adults.value;
        if (selectedAdult > limit || selectedAdult < minimum) {
            selectedAdult = minimum * 2;
        }
        var newSelectedIndex = 1;
        adults.options.length = limit-minimum;
        for (i = minimum ; i <= limit; ++i) {
            adults.options[i-minimum] = new Option(i, i);
            if (i == selectedAdult) {
                newSelectedIndex = i-minimum;
            }
        }
        adults.selectedIndex = newSelectedIndex;
    }
}

/* update one dropdown for the children count for one room 
   @param children the select box form field for which we are changing the options 
   @param limit the highest number allowed in the dropdown (0 is lowest)
*/
function updateChildDropdown(children, limit) {
    if (children && children.options.length != limit + 1) {
        var selectedChild = children.selectedIndex;
        if (selectedChild > limit) {
            selectedChild = 0;
        }
        children.options.length = limit + 1;
        for (i = 0 ; i <= limit; ++i) {
            children.options[i] = new Option(i, i);
        }
        children.selectedIndex = selectedChild;
    }
}

function getRefToDiv(divID,oDoc) {
	if( document.getElementById ) { return document.getElementById(divID); }
	if( document.all ) { return document.all[divID]; }
	if( !oDoc ) { oDoc = document; }
	if( document.layers ) {
		if( oDoc.layers[divID] ) {
			return oDoc.layers[divID];
		} else {
			for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
				y = getRefToDiv(divID,oDoc.layers[x].document);
			}
			return y;
		}
	}
	return false;
}

function showDiv(divID_as_a_string) {
	var myReference = getRefToDiv(divID_as_a_string);
	document.getElementById(divID_as_a_string).style.display = '';
	if( !myReference ) { return; }
	if( myReference.style ) { myReference.style.visibility = 'visible'; } else {
		if( myReference.visibility ) { myReference.visibility = 'show'; } else {
			return; } }
}

function hideDiv(divID_as_a_string) {
	var myReference = getRefToDiv(divID_as_a_string);
	document.getElementById(divID_as_a_string).style.display = 'none';
	if( !myReference ) { return; }
	if( myReference.style ) { myReference.style.visibility = 'hidden'; } else {
		if( myReference.visibility ) { myReference.visibility = 'hide'; } else {
			return; } }
}

function checkRates() {
	//hack to get myform - as in rooms and Rates tile there are more than one myform
	var allForms = document.getElementsByName("myform");
	var form;
	//hack for IE as getElementsByName returns all html elements with name starting with "myform". 
	//firefox returns exact match only
	for(var i = 0; i < allForms.length ; i++) {
		if(allForms[i].name == "myform") {
			form = allForms[i];
			break;
		}
	}
	if(form != null) {
	    if (form.CIMonth.value == "-1" || form.COMonth.value == "-1") { 
	        showDiv('propertyForm1');
       	} else {
			form.changeDates.value = 'true';	    
	        form.submit();
	        }
	}
}

function checkPage() {
    //IE doesn't populate radio buttons like all other browsers so we have to hack in a hidden var that is set
    var ie4=document.all;
    if (ie4) {
        if (document.myform.iehack.selectedIndex == 1 || document.myform.vrChoice[1].checked) {
            showDiv("vrConfirmForm");
        }
    } else {
        //back button fix
        if (!document.myform.vrChoice[0].checked & !document.myform.vrChoice[1].checked) {
            hideDiv("vrConfirmForm");
        }
        if (document.myform.vrChoice[0].checked) {
            hideDiv("vrConfirmForm");
        }
        if (document.myform.vrChoice[1].checked) {
            showDiv("vrConfirmForm");
        }
    }
}


/*
    This function handles all the view updates.  Element events should call into this function (e.g. onClick, onChange, etc)
*/
function updateView(){
    selectRoomType();

    var adults = document.getElementById("adultroom0");
    if (adults) {
        // This is the non-NS4 part
        displayElementForRoomType("roomTitle");
        displayElementForRoomType("guestTitle");
        
        if (!isGroup()){        
            document.getElementById('adultLabel').style.display = '';
        } else {        
            document.getElementById('adultLabel').style.display = 'none';
        }
        if (!isGroup()){     
            document.getElementById('childLabel').style.display = '';
        } else {        
            document.getElementById('childLabel').style.display = 'none';
        }
        
        showRooms('room');
        
        for (var i = 0 ; i < totalPossibleRooms ; ++i) {
            showRoomInfo(i, 'room' + i + 'ages', 'room' + i + 'age');
        }
        showAgeTitles();
    }
    
    updateAdultChildDropdowns();
}

/* When the user selects the number of adults this sets the hidden adults/room fields */
function updateHiddenAdultCounts() {
    var rooms = numRoomsSelected();
    //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
    if (document.forms[0].name == "myform") {
        var count = new Number(document.forms[0].numadults.value);
    } else {
        var count = new Number(document.forms[1].numadults.value);
    }
    
    // this divides them up among the rooms roughly evenly
    for (var i = 0; i < totalPossibleRooms ; ++i) {
        //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
        if (document.forms[0].name == "myform") {
            document.forms[0]["adults[" + i + "]"].value = 0;
        } else {
            document.forms[1]["adults[" + i + "]"].value = 0;
        }
    }
    while (count > 0) {
        for (var i = 0; 
        count > 0 && i < rooms ; 
        ++i) {
            //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
            if (document.forms[0].name == "myform") {
                document.forms[0]["adults[" + i + "]"].value++;
            } else {
                document.forms[1]["adults[" + i + "]"].value++;
            }
            count--;
        }
    }
}

/* When the user selects the number of children this sets the hidden children/room fields */
function updateHiddenChildCounts() {
    var rooms = numRoomsSelected();
    //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
    if (document.forms[0].name == "myform") {
        var count = new Number(document.forms[0].numchildren.value);
    } else {
        var count = new Number(document.forms[1].numchildren.value);
    }
    /* this divides them up among the rooms roughly evenly */
    for (var i = 0; i < totalPossibleRooms ; ++i) {
        //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
        if (document.forms[0].name == "myform") {
            document.forms[0]["child[" + i + "]"].value = 0;
        } else {
            document.forms[1]["child[" + i + "]"].value = 0;
        }
    }
    while (count > 0) {
        for (var i = rooms-1; 
        count > 0 && i >= 0 ; 
        --i) {
            //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
            if (document.forms[0].name == "myform") {
                document.forms[0]["child[" + i + "]"].value++;
            } else {
                document.forms[1]["child[" + i + "]"].value++;
            }
            count--;
        }
    }
}

/* Enable only some of the hidden fields on the NS4 form based on the number of rooms selected */
function enableDisableCounts() {
    var count = numRoomsSelected();
    for (var i = 0 ; i < totalPossibleRooms ; ++i) {
        //forms hack for IE, property page has 2 forms now and requires a lot of tinkering
        if (document.forms[0].name == "myform") {
            document.forms[0]["child[" + i + "]"].disabled = !(i < count);
        } else {
            document.forms[1]["child[" + i + "]"].disabled = !(i < count);
        }
    }    
    updateAdultChildDropdowns();
    updateHiddenAdultCounts();
    updateHiddenChildCounts();
}

function groupsUpdateAdults(rooms){
	var numRooms = rooms.value;
	numRooms = (numRooms*2)-1;
	document.forms[0].numadults.selectedIndex = numRooms; 

}
