/**
 * Starwood Resorts general JS code
 * Sagan Bolliger, 28 June 2011
 */

$(function() {

	resize();
	$(window).resize(resize);
	
	/* lightbox */
	$('.lightbox-shadow').height($(document).height());
	
	$('.lightbox-shadow, .lightbox-container img.close').live('click',hideLightbox);
	
	/* background rotation */
	if($('.bg-frame').children().length >= 2) {
		window.setInterval(function() {
			if($('.results-views').is(':visible'))
				return;
			
			var current = $($('.bg-frame .active'));
			var next = $($(current).next().length != 0 ? $(current).next() : $(current).parent().children().first());

			next.addClass('next');

			current.fadeOut(1500, function() {
				current.removeClass('active');
				next.removeClass('next').addClass('active');

				current.show();
			});
			
		}, 10000);
	}

	
	
	/* gallery */
	$('.gallery .arrows img').live('click',function(eObj) {
		
		var current = $('.gallery .images img.active');
		current.removeClass('active');
		
		if($(eObj.target).hasClass('forward')) {
			var next = current.next('img');
			if(next.length)
				next.addClass('active');
			else
				current.parent().children('img:first-child').addClass('active');
		} else if($(eObj.target).hasClass('backward')) {
			var prev = current.prev('img');
			if(prev.length)
				prev.addClass('active');
			else
				current.parent().children('img:last-child').addClass('active');
		}
	});
	
	$('.explore-destinations-button, .close-button').click(toggleExploreDestinations);
	
	$('.closeall-button').click(closeEverything);
	
	$('.country-button').click(function(eObj) {
		$('.country-button').removeClass('active');
		$('.destinations').hide();
		var activeClass = $(eObj.target).attr('data-active-class');
		$('.' + activeClass).show();
		$(eObj.target).addClass('active');
	});
	
	/* required to fix IE6 100% height bug */
	$('.top-box .shader').height($('.top-box').height());
	
	/* expand promo boxes on click */
	$('.promo-boxes .promo').click(function() {
		$('.promo-boxes .promo').each(function(idx,item) {
			var padding = $(item).innerHeight() - $(item).height();
			var newHeight = 92 - padding;
			$(item).animate({height: newHeight},'fast');			
		});
		$('.promo-boxes .promo').click(function(eObj) {
			window.location = $(eObj.target).parents('.promo').find('.learn-more').attr('href');
		});
	});
	
	/* adjust promo box heading size */
	$('.promo-boxes .promo h3').each(function(idx,item) {
		var lh = parseInt($(item).css('line-height'));
		while($(item).height() > lh) {
			$(item).css('font-size',parseInt($(item).css('font-size'))-1);
		}
		$(item).height(lh);
	});
	
	$('.' + $('.country-button.active').attr('data-active-class')).show();
	
	/* search field */
	$('#search').keyup(function() {
		Property.performQuery($('#search').val());
		Property.filterViewByActiveIds('.results-views .switch-view');
		Map.filterMarkers(Property.getActiveIds());
		$('#subset').html(Property.getActiveIds().length);
	});
	
	/* search field default text */
	$('#search').focus(function() {
		if($(this).val() == 'ex. Hotel Name, Brand') {
			$(this).val('');
		}
		$(this).css('color','#000000');
	}).blur(function() {
		if($(this).val() == '') {
			$(this).css('color','#bababa').val('ex. Hotel Name, Brand');
		}
	});
	
	/* search field clear box */
	$('.results-views .search-box .reset').click(function() {
		$('#search').focus().val('').keyup();
	});

	
	/* toggle buttons. clunky class name structure required for IE6 compatibility */
	$('.results-views .search-box .toggle-buttons div').click(function(eObj) {
		$('.results-views .search-box .toggle-buttons div').removeClass('list-active')
		.removeClass('map-active').removeClass('image-active');
		$('.results-views .switch-view').removeClass('list-view').removeClass('image-view');
		$('.results-views .view').hide();
		$('.additional-dates-popup').hide();
		if($(eObj.target).hasClass('list')) {
			$(eObj.target).addClass('list-active');
			$('.results-views .switch-view').show().addClass('list-view');
		} else if($(eObj.target).hasClass('image')) {
			$(eObj.target).addClass('image-active');
			$('.results-views .switch-view').show().addClass('image-view');
		} else if($(eObj.target).hasClass('map')) {
			$(eObj.target).addClass('map-active');
			$('.results-views .map-view').show();
			Map.drawMap();
		}
		displayBackToTop();
	});
	
	/* set default state */
	$('.results-views .search-box .toggle-buttons .list').click();
	
	/* increment/decrement buttons */
	$('.booking .arrow.increment').live('click',function(eObj) {
		var input = $(eObj.target).parents('.booking').find('input.rooms');
		input.val(parseInt(input.val())+1);
	});
	
	$('.booking .arrow.decrement').live('click',function(eObj) {
		var input = $(eObj.target).parents('.booking').find('input.rooms');
		input.val(Math.max(parseInt(input.val())-1,1));
	});
	
	/* scroll to top button */
	$('.back-to-top').click(function() {
		$(window).scrollTop(0);
	});
	
	
	/* comparison scroll bar code */
	var fsft = ($('.lightbox-content.comparison .stripe').height() - 
					$.getScrollbarWidth()) / 2;
	$('.lightbox-content.comparison .fake-scroll-frame').css('bottom',fsft);
	
	$('.lightbox-content.comparison .fake-scroll-frame').scroll(function() {
		$('.lightbox-content.comparison .comparison-view').css('left',
			$('.lightbox-content.comparison .fake-scroll-frame').scrollLeft() * -1);
	})
	
		
	/* avoid passing default text in check in and check out inputs */
	$('.item form').live('submit',function(eObj) {
		$(eObj.target).find('input.check-in, input.check-out').each(function(idx,item) {
			if($(item).attr('value') == 'CHECK IN' || $(item).attr('value') == 'CHECK OUT')
				$(item).attr('disabled','disabled');
		});
	});
	
	/* comparison button event handler */
	$('.item .bottom-buttons .comparison').live('click',false).live('click',function(eObj) {
		if($(eObj.target).hasClass('added'))
			displayCompare();
		else
			addToComparisonList($(eObj.target).parents('.item').attr('data-property-id'));
	});
	
	/* comparison remove buttons */
	$('.comparison-view .item .remove-button').live('click',function() {
		var id = $(this).parents('.item').attr('data-property-id');
		$(this).parents('.item').remove();
		removeFromComparisonList(id);
	});
	
	
	/* slideshow */
	$('.item .slideshow').live('click',false).live('click',function(eObj) {
		displayQuickview($(eObj.target).parents('.item').attr('data-property-id'));
	})
	
	/* additional dates popup */
	$('.view .item .additional-dates-popup .close').live('click',function(eObj) {
		$(eObj.target).parents('.additional-dates-popup').hide();
	});
	
	$('.view .item .additional-dates').live('click',function(eObj) {
		$(eObj.target).parents('.item').find('.additional-dates-popup').show();
	});
	
	$('.view .item .offer').live('click',function(eObj) {
		var offer_id = $(eObj.target).attr('data-offer-id');
		var item = $(eObj.target).parents('.item');
		Property.populateOffer(item,offer_id);
		
		item.find('.offer').removeClass('active');
		$(eObj.target).addClass('active');
		
		window.setTimeout(function() {
			item.find('.additional-dates-popup').hide();
		}, 150);
		
	});
	
	/* booking */
	$('.check-rates, .book-package').live('click',function(eObj) {
		eObj.preventDefault();
		
		// change date back
		var checkin = $(this).parent().parent().find('input.check-in');
		var checkout = $(this).parent().parent().find('input.check-out');
		var roomnights = $(this).parent().parent().find('select.numberOfNights');
		
		if (checkin.val() != undefined) {
			if (checkin.val() != 'CHECK IN') {
				var dateIn = checkin.val().split('-');
				checkin.val(dateIn['2'] + '-' + dateIn['0'] + '-' + dateIn['1']);
				
				
				gap = roomnights.val();
				
				if (gap != undefined) {
					var ed = new Date(dateIn[2], dateIn[0] - 1, dateIn[1]);
					var ed2 = new Date(dateIn[2], dateIn[0] - 1, dateIn[1]);
					
					ed2.setDate(ed.getDate() + parseInt(gap));
					
					checkout.val(
						ed2.getFullYear() + '-' + 
						pad(Number(ed2.getMonth() + 1), 2) + '-' +
						pad(ed2.getDate(), 2));
				} else {
					checkout.val('');
				}
				
				// var dateOut = checkout.val().split('-');
				// checkout.val(dateOut['2'] + '-' + dateOut['0'] + '-' + dateOut['1']);
				
				$(eObj.target).parents('.item').find('form').submit();
				
				checkin.val(dateIn['0'] + '-' + dateIn['1'] + '-' + dateIn['2']);
				
				// checkout.val(dateOut['0'] + '-' + dateOut['1'] + '-' + dateOut['2']);
			}
		} else {
			$(eObj.target).parents('.item').find('form').submit();
		}
	});
	
	/* auto-show properties */
	if(typeof jump_to_list !== 'undefined')
		displayResults('all');
	
	/* more special offers tooltip */
	$('.item .comparison').live('mouseenter', function(eObj) {
		var button = $(eObj.target);
		var tooltip = $('<div class="tooltip">To compare resorts side-by-side, just click the "Add to Compare List" button and then click "Compare Hotels" button to view all Resorts added.</div>');
		button.parent().append(tooltip);
		
		$(tooltip).position({
			my: 'left top',
			at: 'left bottom',
			of: button,
			offset: '0 5'
		});
	});

	$('.item .comparison').live('mouseleave',function(eObj) {
		var button = $(eObj.target);
		button.parent().find('.tooltip').remove();		
	});
	
	/* magnifying glass */
	$('.item .display-image').live('mouseenter',function(eObj) {
		var hoverstate = $('<div class="magnifying-glass"><div class="shader"></div><img src="/assets/images/magnifying-glass.png" alt="magnifying glass" /></div>');
		$(eObj.target).parent().append(hoverstate);
		hoverstate.position({
			my: 'left top',
			at: 'left top',
			of: eObj.target
		});
		hoverstate.width($(eObj.target).width());
		hoverstate.height($(eObj.target).height());
		var img = hoverstate.find('img');
		img.css('left',hoverstate.width() / 2 - 26);
		img.css('top',hoverstate.height() / 2 - 20);
	});
	
	$('.item .magnifying-glass').live('mouseleave',function(eObj) {
		$(eObj.target).parents('.magnifying-glass').remove();
	});
	
	$('.item .magnifying-glass').live('click',function(eObj) {
		displayQuickview($(eObj.target).parents('.item').attr('data-property-id'));
	});
	
	$('input.check-in').change(function() {
		var pathname = window.location.pathname;
		var pattern = /sunsational/i;
		
		// if (pathname.match(pattern)) {
			gap = $(this).attr('gap');
			
			if (gap != undefined) {
				sd = new Date($(this).val());
				var dateArray = $(this).val().split('-');
				
				var ed = new Date(dateArray[2], dateArray[0], dateArray[1]);


				var ed2 = new Date();
				
				ed2.setDate(ed.getDate() + parseInt(gap));
				
				// $(this).parent().find('input.check-out').val(
					// pad(Number(ed2.getMonth() + 1), 2) + '-' +
					// pad(ed2.getDate(), 2) + '-' + 
					// ed2.getFullYear());
			}
		// }
	});
});

function pad(number, length) {
	var str = '' + number;
	while (str.length < length)
		str = '0' + str;
	return str;
}

/* handle bg dynamic bg repositioning */

function resize() {
	$('.bg-pane').css('left',(Math.max($(window).width(),$('.page-wrapper').width())-$('.bg-pane').width())/2 + 'px');
	$('.bg-frame').height(Math.max($(document).height(),970));
}

function displayResults(id) {

	$('.results-views .switch-view .item[data-property-id]').remove();

	toggleExploreDestinations();
	$('.destination-dropdown').hide();
	$('.content-container .results-views').show();

	$('.content-container .results-views .loading-message').show();

	var callback = function(data) {
		
		// fade out results while they load
		$('.results-views .switch-view').css('opacity','.3').css('filter','alpha(opacity=30)');
		
		Property.populateView('.results-views .switch-view', function() {

			// if map is the active view, simulate clicking on its toggle button to reset view
			$('.results-views .search-box .toggle-buttons div.map-active').click();

			$('#total, #subset').html($('.switch-view .item[data-property-id]').length);

			$('.location-heading').html(data['heading']);
			
			displayBackToTop();
			
			// reset results fading
			$('.results-views .switch-view').css('opacity','1').css('filter','alpha(opacity=100)');
			
			$('.content-container .results-views .loading-message').hide();
			
		});
		
	}
	
	Property.switchToCity(id,callback);


}

function displayBackToTop() {
	if($('.back-to-top').offset()['top'] > $(window).height())
		$('.back-to-top').css('opacity','1').css('filter','alpha(opacity=100)');
	else
		$('.back-to-top').css('opacity','0').css('filter','alpha(opacity=0)');
}

var dqvGo = true;
function displayQuickview(id) {
	
	if(!dqvGo)
		return;
	
	dqvGo = false;
	
	$('.lightbox-content.quickview.item').remove();

	$.get('/item/campaign/' + Property.getCampaignIdForProperty(id) + '/view/quickview-item',function(rt) {
		
		$('.lightbox-container.view').append(rt);
		
		Property.populateFieldsForItem($('.lightbox-content.quickview'),id);
		$('.lightbox-content').hide();
		$('.lightbox-shadow, .lightbox-container, .quickview').show();
		$('.lightbox-container').css('left',($(window).width()-$('.lightbox-container').width())/2);
		$('.lightbox-container').css('top',($(window).height()-$('.lightbox-container').height())/2);
		$('.lightbox-content .additional-dates-popup').hide();

		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			$('.lightbox-container').css('top',Number($(window).scrollTop() + 48) + 'px');
			$('.lightbox-shadow').height($(document).height())
		}
		
		dqvGo = true;
	});

}

function addToComparisonList(id) {

	var button = $('.switch-view .item[data-property-id=' + id + '] .bottom-buttons .comparison');
	
	button.addClass('added').html('Compare (<span class="quantity"></span>) Hotels Now');

	var all_buttons = $('.switch-view .item .bottom-buttons .comparison.added');
	
	all_buttons.find('span.quantity').each(function(id,item) {
		$(item).html(all_buttons.length);
	});
}

function removeFromComparisonList(id) {
	var item = $('.switch-view .item[data-property-id=' + id + ']');
	
	item.find('.bottom-buttons .comparison').removeClass('added').html('Add to Compare List');
		
	var all_buttons = $('.switch-view .item .bottom-buttons .comparison.added');
	
	all_buttons.find('span.quantity').each(function(id,item) {
		$(item).html(all_buttons.length);
	});	
	
	var num_items = $('.lightbox-content.comparison .view .item[data-property-id]').length;
	
	if(num_items == 0)
		hideLightbox();
	
	$('.lightbox-content.comparison .view').width(257 * num_items);
	$('.lightbox-content.comparison .num-resorts').html(num_items);
}

var dcCount = 0;
function displayCompare() {
	
	if(dcCount > 0)
		return;
	
	dcCount = $('.switch-view .item .bottom-buttons .comparison.added').length;
	
	$('.comparison-view .item[data-property-id]').remove();
	
	var template = $('.comparison-view .item.template');
	
	$('.switch-view .item .bottom-buttons .comparison.added').each(function() {
		var propertyId = $(this).parents('.item').attr('data-property-id');
		
		$.get('/item/campaign/' + Property.getCampaignIdForProperty(propertyId) + '/view/comparison-item',function(rt) {
			var tmpl = $(rt);
			var item = Property.populateFieldsForItem($(tmpl).removeClass('template'),propertyId);
			$('.comparison-view').append(item);
			dcCount--;
			
			if(dcCount == 0) {
				finishDisplayCompare();
			}
		});
		
	});

	function finishDisplayCompare() {
		$('.lightbox-content').hide();
		$('.lightbox-shadow, .lightbox-container, .comparison').show();
		$('.lightbox-container').css('left',($(window).width()-$('.lightbox-container').width())/2);
		$('.lightbox-container').css('top',($(window).height()-$('.lightbox-container').height())/2);	
		
		var num_items = $('.lightbox-content.comparison .view .item[data-property-id]').length;
		
		if(num_items == 0)
			hideLightbox();
		
		$('.lightbox-content.comparison .view').width(257 * num_items);
		$('.lightbox-content.comparison .num-resorts').html(num_items);
		
		$('.lightbox-content.comparison .view').resize(updateScrollbar).resize();
		
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			$('.lightbox-container').css('top',Number($(window).scrollTop() + 48) + 'px');
			$('.lightbox-shadow').height($(document).height())
		}
	}
}

function updateScrollbar() {
	$('.lightbox-content.comparison .fake-scroll-pane').width($('.lightbox-content.comparison .view').width());
}

function hideLightbox() {
	$('.lightbox-shadow').hide();
	$('.lightbox-content').hide();
	$('.lightbox-container').hide();
}

function toggleExploreDestinations() {
	if($('.destination-dropdown').is(':visible')) {
		$('.destination-dropdown').slideUp('fast');
		$('.explore-destinations-button.closed').hide();
		$('.explore-destinations-button.open').show();
	   
   } else {
		$('.content-container .results-views').hide();
		$('.destination-dropdown').slideDown('fast');
		$('.explore-destinations-button.closed').show();
		$('.explore-destinations-button.open').hide();
   }
}

function closeEverything() {
	$('.content-container .results-views').hide();
	$('.explore-destinations-button.closed').hide();
	$('.explore-destinations-button.open').show();
}

/* mouseovers */
$(function() {
	$('img[mo]').each(function() {
		/* pre-load */
		var preload = $('<img/>');
		var mo_src = $(this).attr('mo');
		preload.attr('src',mo_src);
		preload.hide();
		$(document.body).append(preload);
		$(this).data('orig-src',$(this).attr('src'));
		$(this).mouseenter(function() {
			if(!$(this).is(':visible'))
				return;
			$(this).attr('src',mo_src);
		});
		$(this).mouseleave(function() {
			$(this).attr('src',$(this).data('orig-src'));
		});
	});
});
