
$(document).ready(function() {

    /*
    var stepNumber = 1;
    $('.reservationStep').each( function() {
    $(this).append('<div class="stepNumber">' + stepNumber + '</div>');
    });
    */

    // This is to handle the room selection process, whereby its border turns blue onClick
    $('#content .rates .ratechoice a').click(function() {
        var roomId = $(this).parents('.stepChoiceRoom').parent('div').attr('id');
        var clickedRate = $(this)
        cancelError();

        // Get occupant counts
        var occupantCountsArray = $(".occupantCounts").val().split(",");
        var maxOccupancy = $(this).parents('.roomChoice').find('input.maxOccupants').val();
        var occupantCount;

        if ($(this).parents('.roomChoice').hasClass('room1')) {
            $('input.roomType1').val(roomId);
            occupantCount = occupantCountsArray[0];
            $(this).parents('.reservationStep').next('.reservationStep').find('.stepContinueDyn, .stepContinue').fadeIn(700);
        }
        if ($(this).parents('.roomChoice').hasClass('room2')) {
            $('input.roomType2').val(roomId);
            occupantCount = occupantCountsArray[1];
            $(this).parents('.reservationStep').next('.reservationStep').find('.stepContinueDyn, .stepContinue').fadeIn(700);
        }
        if ($(this).parents('.roomChoice').hasClass('room3')) {
            $('input.roomType3').val(roomId);
            occupantCount = occupantCountsArray[2];
            $(this).parents('.reservationStep').next('.reservationStep').find('.stepContinueDyn, .stepContinue').fadeIn(700);
        }

        // Check that room's max occupancy has not been exceeded
        if (occupantCount > maxOccupancy) {
            //alert("Oops! occupants: " + occupantCount + " max: " + maxOccupancy);

            $(this).parents('.stepChoiceRoom').prepend('<div class="error">You have ' + occupantCount + ' guests assigned to this room, but only ' + maxOccupancy + ' are allowed for this room type. If you do not cancel this selection you will have to reassign some guests to another room.<a href="#" class="errorCancel">cancel</a><a href="#" class="errorContinue">continue</a></div>');
            // WHEN CANCEL IS CLICKED:
            $('.error .errorCancel').click(function() {
                cancelError();
                return false;
            });
            // WHEN CONTINUE IS CLICKED:
            $('.error .errorContinue').click(function() {
                cancelError();
                return false;
            });
        }

        // Find any previous rates that have been checked.
        // Then determin if the rate being clicked is the same type as previous rates.
        // If not display message.this must be placed before the script that sets the checkbox to be checked.
        var currentRateType = $(this).parent('.ratechoice').hasClass('bookitnow') ? "bookitnow" : "bestrate";
        var lastRateType = $('.ratechoice input:checked').parent('.ratechoice').hasClass('bookitnow') ? "bookitnow" : "bestrate";
        var selectedRoomCount = $('.ratechoice input:checked').length;

        // Checks to see if the rate that you clicked matches the rates of previously selected rates.
        if ((selectedRoomCount > 0) && (currentRateType != lastRateType) && ($('.room2').length > 0)) {

            // CREATE ERROR POPUP
            $(this).parents('.stepChoiceRoom').prepend('<div class="error">You can only choose one room rate type for all rooms. By choosing to continue, all previously selected rooms will reflect this room type. If you cancel nothing will happen.<a href="#" class="errorCancel">cancel</a><a href="#" class="errorContinue">continue</a></div>');
            // WHEN CANCEL IS CLICKED:
            $('.error .errorCancel').click(function() {
                cancelError();
                return false;
            });
            // WHEN CONTINUE IS CLICKED:
            $('.error .errorContinue').click(function() {
                $('.ratechoice input:checked').each(function() {
                    $(this).parents('.roomChoice').find('.ratechoice').removeClass('SelectedRateChoice');
                    $(this).parents('.rates').find('input').not('input:checked').parents('.ratechoice').addClass('SelectedRateChoice');
                    $(this).parents('.rates').find('input').not('input:checked').attr('checked', true);
                    $(this).attr('checked', false);
                    cancelError();
                });
                if (!$(this).parent().parent('.stepChoiceRoom').hasClass('SelectedRoomChoice')) {
                    selectRoom(clickedRate);
                    cancelError();
                }
                return false;
            });
            return false;

        } else {

            selectRoom(this);
            setPlanLink();
            return false;

        }

    });

    // This code handles when the visitor clicks "Continue" in any pane
    $("#userInfo .stepContinue").click(function() {
        editStep("#" + $(this).parent().attr('id'));
    });

    // ...and likewise, this code handles when the visitor clicks "Edit" on a previously completed pane	
    $(".stepPrevious").click(function() {
        if ($(this).attr('id') == "editItinerary") { editStep("#itinerary"); }
        else if ($(this).attr('id') == "editRoom") { editStep("#roomPreference"); }
        else if ($(this).attr('id') == "editUserInfo") { editStep("#userInfo"); }
    });

    // Finally, whenever this script loads, it begins editing the Itinerary step

    /*if ($("#roomPreference .stepContinue").css('display') != null) { editStep("#itinerary"); }
    else { editStep("#roomPreference"); }*/

    // This is the logic that fetches data (if it exists) from the hidden room type fields at the top of the page.
    if ($('.roomType1').attr('value') != '') {
        var roomType = '#' + $('.roomType1').val();
        // $(roomType).find('input[type=checkbox]').attr('checked', true);

        $(roomType).find('input[type=checkbox]').each(function() {
            if ($(this).attr('checked') != '') {
                $(this).parents().filter('.ratechoice').addClass('SelectedRateChoice');
            }
        })

        $(roomType).find('.stepChoiceRoom').addClass('SelectedRoomChoice');
    }

    if ($('.roomType2').attr('value') != '') {
        var roomType = '#' + $('.roomType2').val();
        // $(roomType).find('input[type=checkbox]').attr('checked', true);

        $(roomType).find('input[type=checkbox]').each(function() {
            if ($(this).attr('checked') != '') {
                $(this).parents().filter('.ratechoice').addClass('SelectedRateChoice');
            }
        })

        $(roomType).find('.stepChoiceRoom').addClass('SelectedRoomChoice');
    }

    if ($('.roomType3').attr('value') != '') {
        var roomType = '#' + $('.roomType3').val();
        // $(roomType).find('input[type=checkbox]').attr('checked', true);

        $(roomType).find('input[type=checkbox]').each(function() {
            if ($(this).attr('checked') != '') {
                $(this).parents().filter('.ratechoice').addClass('SelectedRateChoice');
            }
        })

        $(roomType).find('.stepChoiceRoom').addClass('SelectedRoomChoice');
    }

    /* Debug on pageload: Alert us as to what the values are of the three fields.
    alert('Room type 1: ' + $('.roomType1').val());
    alert('Room type 2: ' + $('.roomType2').val());
    alert('Room type 3: ' + $('.roomType3').val());
    */
    editStep("#" + $('.selectedPanel').val());

    // Set rate plan link
    setPlanLink();

    // Shows captcha when Forgot Password is clicked.
    $('.ForgotPw').click(function() {
        showCaptcha();
        return false;
    });

    // Shows captcha after submitting Captcha and refreshing.
    if ((queryString("result") == "cf") || (queryString("result") == "un") || (queryString("result") == "unno")) {
        showCaptcha();
    }

    // If a room has all ready been selected add the appropriate classes
    $('.ratechoice input:checked').each(function() {
        $(this).parents().filter('.ratechoice').addClass('SelectedRateChoice');
        $(this).parents().filter('.stepChoiceRoom').addClass('SelectedRoomChoice');
    });

}
);

function editStep(stepToEdit) { 

	// This line determines if the div element after room preference's collapsing area is a clone of the selected room, and
	// if not, make a clone after the collapsing area.
	if (!$('#roomPreference .Collapse').next().is('.SelectedHeader')) {
		$('.SelectedRoomChoice').clone().insertAfter('#roomPreference .Collapse').addClass('SelectedHeader');
	}
	
	// If we're editing the room preference step, take out that header we just added
	if (stepToEdit == '#roomPreference') {	$(stepToEdit).find('.SelectedHeader').remove(); }
	
	// Then we'll hide all previously opened collapse-areas
	$('.Collapse').children().css('visibility','hidden');
	$('.Collapse').slideUp(500);
	
	// And we'll make sure that none of the reservation steps are declared as being selected
	$('.reservationStep').removeClass('selected');
	
	// Hide the "Continue" and "Previous" buttons for all panes
	$(".stepContinue").hide();
	$(".stepPrevious").hide();
	
	// Show the "Edit Settings" for the current pane
	$(stepToEdit).find('.stepPrevious').fadeIn(700);
	
	// Show the "Continue" button for the next pane (unless we're in the room preference pane)
	if (stepToEdit != "#roomPreference") { $(stepToEdit).next('.reservationStep').find('.stepContinue').fadeIn(700); }
	
	// Next, we'll show clicked elements
	$(stepToEdit).addClass('selected');
	$(stepToEdit + ' .Collapse').slideDown(500, function(){
		$(stepToEdit + ' .Collapse').children().css('visibility','visible');
	});

}

// Set 'Rate Plan' link URL according to the selected rate
function setPlanLink() {
    $("div.SelectedRoomChoice").each(function() {
        planLink = $(this).find("a.plan");
        if ($(this).find("div.SelectedRateChoice").attr("id").indexOf("Adv") > -1) {
            if (planLink.attr("href").indexOf("?") < 0) {
                planLink.attr("href", planLink.attr("href") + "?p=adv");
            }
        }
        else {
            planLink.attr("href", planLink.attr("href").replace(/\?p=adv/i, ""));
        }
    })
}

function finishPanelLoad(elId, panelIndex) {
    if ($(elId + ' .SelectedRoomChoice').length > 0) {
        $(elId).next('.reservationStep').find('.stepContinueDyn').show();
    }
}

// removes error box
function cancelError() {
	$('.error').remove();
}

// Highlights room and selects rate.
function selectRoom(target) {
    // uncheck checkbox, remove stepChoiceRoom class, remove selected class.
    $(target).parents('.roomChoice').find('input[type=checkbox]').attr('checked', false);
    $(target).parents('.roomChoice').find('.stepChoiceRoom').removeClass('SelectedRoomChoice');
    $(target).parents('.roomChoice').find('.ratechoice').removeClass('SelectedRateChoice');

    // And now add the "SelectedRoomChoice" class to this choice, check its checkbox, and add selected to fake radio button
    $(target).parents('.stepChoiceRoom').addClass('SelectedRoomChoice');
    $(target).parents('.ratechoice').find("input[type='checkbox']").attr('checked', true);
    $(target).parents('.ratechoice').addClass('SelectedRateChoice');

    // Determine if there's a selected room for every room choice
    if ($('.roomChoice').length == $('.SelectedRoomChoice').length) {
       // $('#userInfo .stepContinue').fadeIn(700);
	}
}

//Shows Captcha when needed
function showCaptcha() {
	$('.ForgotPw').slideUp();
	$('.captcha').slideDown();
}


// Grab Parameters from URL
function queryString(parameter) {
  var loc = location.search.substring(1, location.search.length);
  var param_value = false;

  var params = loc.split("&");
  for (i=0; i<params.length;i++) {
      param_name = params[i].substring(0,params[i].indexOf('='));
      if (param_name == parameter) {
          param_value = params[i].substring(params[i].indexOf('=')+1)
      }
  }
  if (param_value) {
      return param_value;
  }
  else {
      return false; //Here determine return if no parameter is found
  }
}
