/**
 * suites.js / page-suites-suites.php
 * Defines functions used for suites page.
 * Copyright (c) 2009 Great Wolf Resorts, Inc.
 */
(function() {

// Define local namespace
var namespace = GWR.Namespace("Suites");

var todayDate = new Date(), 
	tomorrowDate = new Date(todayDate);
tomorrowDate.setDate(tomorrowDate.getDate() + 1);

// Special drupal-based indicator for all types
var suiteTypeAll = '**ALL**';

// Default suite type displayed.  This will contain the current theme suite type 
var defaultSuiteType = suiteTypeAll,
	defaultMinOccupancy = 4;

var currentSuiteType = defaultSuiteType,
	currentMinOccupancy = defaultMinOccupancy;
	
// Keeps track of the current list of displayed suite nodes
var suiteNodes;

/**
 * Returns true if a textbox still has its default value
 */
var isTextboxDefaultValue = function(textbox) {
    return $(textbox).val() == $(textbox).attr('rel');
}

/**
 * Global datepicker options applied to all datepickers
 */
var datepickerOptions = {
	changeFirstDay: false,
	changeMonth: false,
	changeYear: false,
	showAnim: 'fadeIn',
	dayNamesMin: ['S','M','T','W','T','F','S'],
	hideIfNoPrevNext: true,
	showOn: 'focus',
    prevText: '',
    nextText: '',
	buttonImageOnly: true,
	dateFormat: 'm/d/yy',
    beforeShow: function() {
        $.datepicker.dpDiv.css('margin-top', '0');
    }
};

var dateFormat = 'm/d/yy';

/**
 * Function that returns true if the suite node has a max occupancy greater than or equal to minOccupancy
 */
var checkSuiteOccupancy = function(suiteNode) {
	return suiteNode.find('.max-occupancy').html() >= currentMinOccupancy;
}

/**
 * Updates the suite to display the new selection
 */
var updateSuites = function(suiteType, occupancy) {
	if(suiteType == 'All') {
		suiteType = suiteTypeAll;
	}
	currentSuiteType = suiteType;
	currentMinOccupancy = occupancy;

	suiteNodes = suiteNodes || $('#body .suite-node');
	
	// keep track if there is a result displayed
	var hasResults = false;
	
	suiteNodes.each(function() {
		// Check suite type and occupancy to determine if we should show or hide
		var show = (suiteType == suiteTypeAll || $(this).attr('rel') == suiteType) &&
					checkSuiteOccupancy($(this));
        if(show) {
            $(this).show()
            .toggleClass('suite-node-first', !hasResults);
        }
        else {
            $(this).hide();
        }
		// Keep track of result shown to determine if reset panel should be displayed
		hasResults = hasResults || show;
	});
	
	// Hide or show the No Results found div
    if(!hasResults) {
        $('#body .suite-noresults').show();
    }
    else {
        $('#body .suite-noresults').hide();
    }
	
	// Suite Type selectors - Remove highlight from old, add highlight to new
	$('#suite-categories span').each(function() {
		if($(this).attr('rel') == suiteType) {
			$(this).addClass('selected');
		}
		else {
			$(this).removeClass('selected');
		}
	});
	
	if(suiteType == suiteTypeAll) {
		suiteType = 'All';
	}
	
	GWR.Hash({
		type: suiteType,
		occupancy: occupancy
	});
}

GWR.Init(function() {

    // Check on initial page load if there are hash value set
	var initSuiteType = GWR.Hash('type');
	if(initSuiteType && initSuiteType != '') {
		currentSuiteType = initSuiteType;
	}
	var initOccupancy = GWR.Hash('occupancy');
	if(initOccupancy && initOccupancy != '') {
		currentMinOccupancy = initOccupancy;
	}
	
	var keywordList = GWR.GetHashKeywords();
	
	if(keywordList.length > 0) {
		var keyword = keywordList[0];
		
		$('#body .suite-node').each(function() {
			var title = $('.title', this).html();
			if(GWR.HashString(title, keyword)) {
				$('#body .view-content').prepend(this);
				return false;
			}
		});
	}
	
	// Remove top border
    $('#body .suite-node:first').css('border-top','0');
	
	// If the current parameters are different than the default, create an update initializer to run on page ready
	if(currentSuiteType != defaultSuiteType || currentMinOccupancy != defaultMinOccupancy) {
        updateSuites(currentSuiteType, currentMinOccupancy);
	}

    /**
     * Attach events to all textbox input controls in the body
     */
                  
    // Keyup event makes the text color darker by toggling a CSS class 
    // when the text has changed from the default value
    $('#body input:text').keyup(function(e) {	
        // Add or remove the CSS class that will make the text a darker color
        $(this).toggleClass('textbox-text', !isTextboxDefaultValue(this));
    })
    
    // Blur event handler resets the control to the default value if the text is cleared
    .blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('rel'))
                .removeClass('textbox-text');
        }
    })
    
    // Focus event handler to clear text
    .focus(function() {
        // Check for default value
        if(!isTextboxDefaultValue(this)) {
            // Highlights all text in the textbox
            this.select();
        }
        else {
            // Clear text and switch classes
            $(this).val('')
                   .addClass('textbox-text');
        }
    })
	
	// Remove hint text colors if it is not default value
	.each(function() {
		if(!isTextboxDefaultValue(this)) {
			$(this).addClass('textbox-text');
		}
	});
    
    // Attach click event handlers to the check availability buttons
    $('#body .restool .check-availability a').click(function() {
    
        // Find the arrival and departure date textboxes associated with this
        // check availability button
        var suiteNode = $(this).closest('.suite-node');
        var arrivalDate = suiteNode.find('.restool .arrival input').val();
        var departureDate = suiteNode.find('.restool .departure input').val();
        
        // Get the path        
        var path = $(this).attr('href');
        
        if(arrivalDate && arrivalDate != '') {
            path += '&resArrival=' + arrivalDate;
        }
        
        if(departureDate && departureDate != '') {
            path += '&resDeparture=' + departureDate;
        }
        
        // Navigate to the new URL
        window.location = path;
        return false;
    });
    
    /**
	 * Attach onclicks for the suite images
	 */
	$('.image-thumb').click(function() {
		/**
		 * swap out room images with the main image and
		 * pop room layouts up in a modal div
		 * The thumbnail's rel attribute tells us if its a room image or layout
		 */
		 var thumbnailType = $(this).attr('rel');
		 if (thumbnailType == 'RoomImage') {
			// swap out the main image.  Locate the main image:
			$(this).closest('.suite-node').find('.image-main img')
			// Change the image source to be the same as  thumbnail's image source
				.attr('src',$(this).find('img').attr('src'));
		}
		else {
			// set the room-layout-image div's title and image source to the thumbnails
			var dialogTitle = $(this).attr('title'); 
			$('.room-layout-header #room-layout-title').html(dialogTitle);
			$('#room-layout-content #room-layout-image').attr('src',$(this).find('img').attr('src'));
            GWR.Util.ShowModalDialog('#room-layout-dialog', 550, 575);
		}
		// prevent event bubbling (omniture lag)
		return false;
	});
    
	/**
	 * Room layout dialog close button click event handler
	 */
	$('#room-layout-dialog .room-layout-header .top-close').click(function() {
		GWR.Util.HideModalDialog();
	});    
    
	var policyTextLoaded = false;
	
	/**
	 * Attach onclicks for policy links
	 */
	$('.suite-policy-link').click(function() {
		if(!policyTextLoaded) {
			var nodeId = $(this).attr('id');
			// get the url to load the content from
			$("#suite-policy-content").html('<div class="loading">Loading..</div>')
			
			// load the content into the policy link dialog
				.load('/node/' + nodeId + ' #body .rounded-template', function() {
					policyTextLoaded = true;
				});
		}
		
		// display the policy dialog box
		GWR.Util.ShowModalDialog('#suite-policy-dialog', 800, 600);
		
		// Prevent default navigation
		return false;
	});
	
	/**
	 * Suite policy dialog close button click event handler
	 */
	$('#suite-policy-dialog .suite-policy-header .top-close').click(function() {
		GWR.Util.HideModalDialog();
	});
	
	/**
	 * Sets the slider label to indicate number of occupants
	 */
	var setSliderLabel = function(val) {
		$('#suite-slider-display').html(val);
	}
	/**
	 * Initialize the slider jQuery UI widget
	 * The slider is used to sort by occupancy
	 */
     var midSlidePos = 4;
     var maxSlide = 8;        
     if(namespace.HasCondo){
        midSlidePos = 8;
        maxSlide = 16;
       $('#suite-slider').addClass('ui-slider-condo');
     }
     $('#suite-slider-display').html(midSlidePos);
	$('#suite-slider').slider({
		min: 1,
		max: maxSlide,
		step: 1,
		value: currentMinOccupancy,
		
		/**
		 * Function that is called when the slider has slid to a new value but the final value of the slider is not determined.
		 */
		slide: function(e, ui) {
			//updateOccupancy(Math.round(ui.value));
			setSliderLabel(Math.round(ui.value));
		},
		
		/**
		 * Function that is called when the value of slider has changed; mouse is released
		 */
		change: function(e, ui) {
			// Update suite results
			updateSuites(currentSuiteType, Math.round(ui.value));
		}
	});
	
	// Initialize the slider label
	setSliderLabel(currentMinOccupancy);

	/**
	 * Initialize the onclick event for the reset link in the No Results div
	 */
	$('.reset', '.suite-noresults,.suite-updating').click(function() {
		// Hide the No Results found div
		$('.suite-noresults').hide();
		
		// Reset the occupancy slider and label to the default min occupancy value
		$('#suite-slider').slider('option', 'value', defaultMinOccupancy);		
		
		// update suite results
		updateSuites(defaultSuiteType, defaultMinOccupancy);
		return false;
	});
	
	$('#suite-categories span').click(function() {
		// Perform AJAX callback with new suite selection
		updateSuites($(this).attr('rel'), currentMinOccupancy);
		return false;
	})
    
	// initialize mouseover event effect
	.hover(function() {
		$(this).addClass('hover');
	},
    
	function() {
		$(this).removeClass('hover');
	});
});



/**
 * Initialize the datepickers.
 * Applies datepickers to all active input fields on the suites pages that do not currently have a datepicker attached
 */
$(function() {
    var suiteArrivalTextboxes = $('.restool .arrival input', '#body');
    var suiteDepartureTextboxes = $('.restool .departure input', '#body');

	// Set the global vars to remember dates picked for future client callback updates
	var setDatepickerValues = function(arrival, departure) {
        // Format the date as a string
        arrivalDate = $.datepicker.formatDate(dateFormat, arrival);
		departureDate = $.datepicker.formatDate(dateFormat, departure);
        
        // Set all arrival textboxes
		$('#restool-arrival').val(arrivalDate).addClass('textbox-text');
        suiteArrivalTextboxes.val(arrivalDate).addClass('textbox-text');
		
        // Set all departure textboxes
        $('#restool-departure').val(departureDate).addClass('textbox-text');
        suiteDepartureTextboxes.val(departureDate).addClass('textbox-text');
	}
	
	// When the arrival date changes, adjust the departure date if necessary to keep date range valid
	var selectArrivalDate = function(txt) {   
		var departure = $(this).closest('.suite-node').find('.restool .departure input');
        if(departure.length == 0) {
            departure = $('#restool-departure');
            GWR.Header.showRestoolExtend();
        }
        
		var d1 = new Date(txt); //arrival
		var d2 = new Date(departure.val()); //departure
        
        // Calculate a day 5 days after the selected date
        var d3 = new Date(d1);
        d3.setDate(d3.getDate() + 5);
        
        if(d2 == null || isNaN(d2) || d2 <= d1 || d2 > d3) {
			d2 = new Date(d1);
			d2.setDate(d2.getDate() + 1);
		}
		setDatepickerValues(d1,d2);
		
		$('#restool-arrival').datepicker('hide');
		$.datepicker.dpDiv.hide()
	}
	
	// When the arrival date changes, adjust the arrival date if necessary to keep date range valid
	var selectDepartureDate = function(txt) {
		var arrival = $(this).closest('.suite-node').find('.restool .arrival input');
        if(arrival.length == 0) {
            arrival = $('#restool-arrival');
            GWR.Header.showRestoolExtend();
        }
        
		var d1 = new Date(arrival.val()); //arrival
		var d2 = new Date(txt); //departure
		
        // Calculate a day 5 days before the selected date
        var d3 = new Date(d2);
        d3.setDate(d3.getDate() - 5);
        
        if(d1 == null || isNaN(d1) || d2 <= d1 || d1 < d3) {
			d1 = new Date(d2);
			d1.setDate(d1.getDate() - 1);
		}
		setDatepickerValues(d1,d2);
		
		$('#restool-departure').datepicker('hide');
		$.datepicker.dpDiv.hide()
	}

	// Apply datepicker to arrival date input fields
	suiteArrivalTextboxes.datepicker($.extend({
        minDate: todayDate,
        onSelect: selectArrivalDate
        },
        datepickerOptions));
	
	// Apply datepicker to depature date input fields
	suiteDepartureTextboxes.datepicker($.extend({
        minDate: tomorrowDate,
        onSelect: selectDepartureDate
        },
        datepickerOptions));
		
	// Add click event handlers to the datepicker icons
	$('#body .restool .arrival-datepicker').mousedown(function() {
		$(this).closest('.restool').find('.arrival input').datepicker('show');
		return false;
	});
	
	$('#body .restool .departure-datepicker').mousedown(function() {
		$(this).closest('.restool').find('.departure input').datepicker('show');
		return false;
	});
	
	// Change the onselect events of the header res tool datepicker
	//$('#restool-arrival').datepicker('option', 'onSelect', selectArrivalDate);
	//$('#restool-departure').datepicker('option', 'onSelect', selectDepartureDate);
});


/**
 * Packaging event handlers
 */
$(function() {

	var displayPackage = function(item, suiteNode) {
		suiteNode.find('.package .package-node').attr('rel', item.PackageCode);
		suiteNode.find('.package .image img').attr('src', item.Image);
		suiteNode.find('.package .title').html(item.Title);
		suiteNode.find('.package .description').html(item.Description);
		suiteNode.find('.package .rate').html(item.Price);
		suiteNode.find('.package .checkbox').attr('value',item.PackageCode);
		if(ResCookie.HasPackage(item.PackageCode)){
			suiteNode.find('.package .checkbox').attr('checked',true);
		}
		else{
			suiteNode.find('.package .checkbox').attr('checked',false);
		}
	};

	/**
	 * Add event to "View additional Package Options" links
	 */
	$('.package .expand').click(function() {
		var suiteNode = $(this).closest('.suite-node');		
		var packagePanel = suiteNode.find('.package .panel');
		var packageList = packagePanel.find('.list');
		packageList.empty();

		// Only process if packageinfo has more than 1 item in it.  
		// The expand link should be hidden in this situation so this should not occur.
		if(namespace.PackageInfo && namespace.PackageInfo.length > 0) {
            var packageInfo = namespace.PackageInfo;
        
			// Populate the package list
			var lastPackageViewed = ResCookie.GetLastPackage();
			
			if (!lastPackageViewed) {
				// no packages have been viewed yet, set the first package as the last package viewed
				lastPackageViewed = packageInfo[0].PackageCode;
				ResCookie.SetLastPackage(lastPackageViewed);
			}
			for(var i = 0; i < packageInfo.length; i++) {
				var packageItem = packageInfo[i];
				packageList.append('<div class="package-list-item" packagecode="' + packageItem.PackageCode +'" rel="' + i + '">' + packageItem.Title + '</div>');

			}
			$('.package-list-item',packageList).each(function(){
				if($(this).attr('packagecode') == lastPackageViewed){
					$(this).addClass('selected');
					displayPackage(packageInfo[$(this).attr('rel')], suiteNode);
				}
				// check to see if package has been checked
				if (ResCookie.HasPackage($(this).attr('packagecode'))){
					$(this).addClass('package-checked');
				}	
				else{
					$(this).removeClass('package-checked');
				}
			});
			
		}
		/*hide all package panels - not hiding other suite's packages for now
		 instead, displaying a "hide link"
		$('.package .panel').hide();
		$('.expand').show();
		*/
		// Show this package panel
		packagePanel.slideDown();
		
		// Hide the view additonal package options div
		$(this).hide();
		
		// Show the divider line
		suiteNode.find('.package .divider').show();
	});
	// hide package onclick event
	$('.package .close-package').click(function() {	
		var suiteNode = $(this).closest('.suite-node');		
		var packagePanel = suiteNode.find('.package .panel');
		var expand = suiteNode.find('.package .expand');
		$(expand).show();
		packagePanel.slideUp();
	});
	
	// Add mouseover hover event
	$('.package .list div').live('mouseover', function() {
		if(!$(this).hasClass('selected')) {
			$(this).addClass('hover');
		}
	})
	
	// Add mouseout hover event
	.live('mouseout', function() {
		$(this).removeClass('hover');
	})
	
	// Add click mouse event
	.live('click', function() {
		var suiteNode = $(this).closest('.suite-node');
		suiteNode.find('.package .list div').removeClass('selected');
		$(this).addClass('selected');
		// set this package as last viewed
		ResCookie.SetLastPackage(namespace.packageInfo[$(this).attr('rel')].PackageCode);

		// Show package node
		displayPackage(namespace.packageInfo[$(this).attr('rel')], suiteNode);
	});
    
    // add package check/uncheck event
	$('.package .checkbox').live('click', function() {
		var suiteNode = $(this).closest('.suite-node');		
		var packagePanel = suiteNode.find('.package .panel');
		var packageList = packagePanel.find('.list');	
		var packageCode = $(this).attr('value');
		if ($(this).is(':checked')){
			ResCookie.AddPackage(packageCode);
			// change the list item's color to indicate the package has been checked
			$('.package-list-item',packageList).each(function(){
				if($(this).attr('packagecode') == packageCode){
					$(this).addClass('package-checked');
				}
			});
		}
		else{
			ResCookie.RemovePackage(packageCode);	
			// change the list item's color to indicate the package has been un-checked
			$('.package-list-item',packageList).each(function(){
				if($(this).attr('packagecode') == packageCode){
					$(this).removeClass('package-checked');
				}
			});			
		}
	});   
});
})();
