var None = null;
var formControls = {}

$(document).ready(function(){
    bindTabClicks();
	bindExpandMenu();
});

function loadMap(mapId, lat, long, hotelData){
	var hotelData = (hotelData == null) ? {'thumbnail': '', 'name': ''} : hotelData;
	
	if ($('#' + mapId).html()){
		return false; //map is already displayed.
	}

	if (!lat || !long){
		$('#' + mapId).html('<img src="/images/no-map.png" alt="" />');
		return false;
	}
	if (!GBrowserIsCompatible()) {
		return false;
	}
		var mapIcon = new GIcon();
		var markerOptions = null;
		var marker = null;
		mapIcon.image = "/images/map-point.png";
		mapIcon.shadow = "/images/map-point-shadow.png";
		mapIcon.iconSize = new GSize(17,22);
		mapIcon.shadowSize = new GSize(30,22);
		mapIcon.iconAnchor = new GPoint(9, 1);
		mapIcon.infoWindowAnchor = new GPoint(5, 1);
		markerOptions = { icon:mapIcon };

		var map = new GMap2(document.getElementById(mapId));
		var latlng = new GLatLng(lat,long);
		var mapTypeControl = new GMapTypeControl();
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
		map.setCenter(new GLatLng(lat, long), 13);
		map.setUIToDefault();
		marker = new GMarker(latlng, markerOptions);
		map.addOverlay(marker);
		GEvent.addListener(marker, 'click', function() {
			map.openInfoWindowHtml(latlng, '<h4>' + hotelData['name'] + '</h4><img src="' + hotelData['thumbnail'] + '" alt="" />');
		});
}

function photoLoader(photos, photoId){
	var pid = $('#' + photoId + ' div.thumbs');
	var imageCount = $('#' + photoId + ' img').length; // we need to check to see if the photos tab has already loaded images.
	var showFirst = false;
	if(imageCount){
		return false;
	}

	thumbs = false;
	for(p in photos){
		if(photos[p]['thumbnail']){
			thumbs = true;
			if(showFirst == false)
				showLargeImage(photos[p]['url'], 'mainPhoto-' + photoId);
			showFirst = true;
			pid.append('<img src="' + photos[p]['thumbnail'] + '" alt="" onclick="showLargeImage(\'' + photos[p]['url'] + '\', \'mainPhoto-' + photoId + '\');" />');
		}
	}
	if (!thumbs){
		showLargeImage('/images/no-photo.jpg', 'mainPhoto-' + photoId);
		pid.addClass('hidden');
	}
}

function showLargeImage(url, id){
	$('#' + id).html('<img src="' + url + '" alt=""/>');    
}


function groupHotel(e,stayId,fromId,toId) {
     $.blockUI({ message: '<div class="uiBlockPrompt saving"><span>saving</span></div>' });
    	$.ajax({
	   type: 'GET',
	   url: '/user/movehotel/?nr=True&id='+stayId+'&from='+fromId+'&to='+toId,
	   dataType: 'json',
	   cache: false,
	   timeout: 15000,
	   error: function(){
		$.unblockUI(); 
                $(e).addClass('ajaxError');
                $(e).html('An error occurred');
	   },
           success:  function(json){
		//put in try/catch block in case of myghty template error
		try {
		    // as long as there wsa not a myghty template error, there should be 'options'
		    if(!json['errors']){
                        $.unblockUI();
                        $(e).addClass('ajaxSuccess');
                        $(e).html('Tracking in <a href="/mytrips/trip/?id=' + toId + '&hv=true">My Trips</a>');
		    } else {
			$.unblockUI();
			$(e).addClass('ajaxError');
                        $(e).html('An error occurred');
		    }
		} catch(err) {
                    $.unblockUI();
                    $(e).addClass('ajaxError');
                    $(e).html('An error occurred');
		}  
	    }
	});
}


function handleMultItinGroups(e,stayId,itinGroups) {
    fromId=itinGroups[0].id;
    html = '<div style="overflow:auto;" class="uiBlockPrompt editAlertTarget">'
        + '<h2>Choose a trip to place this hotel in.</h2><ul>';
    for (var i in itinGroups) {
        html += '<li><a onclick="groupHotel(\''
            +e+'\','+stayId+','+fromId+','+itinGroups[i].id
            +')" href="javascript: void(0);">'+itinGroups[i].name
            +'</a><br /><span class="caption">'+itinGroups[i].caption+'</span></li>';
    }
    for (var i in 10) {
        html += '<li><a href="javascript: void(0);">test...</a></li>';
    }

    html += '</ul></div>';
    
    $.blockUI({ message: html });
    $('.blockUI').css('cursor','default');
    $('.blockUI').css('z-index','9999998');
    $('.blockUI.blockMsg').css('z-index','9999999');
}
        
function trackHotel(e, hotelId, searchId, mapIndex){
	var mapIndex = (mapIndex == null) ? '' : mapIndex;
	$(e).addClass('ajaxInProcess')
	$(e).html('saving...');
	$.ajax({
	   type: 'GET',
	   url: '/search/hotels/track/?searchId=' + searchId + '&hotelId=' + hotelId,
	   dataType: 'json',
	   cache: false,
	   success: function(json){
		   var stayId = null
		   if(!json['errors']){
			   stayId = json['results'][0]['stay']['id'];
                           itinGroups = json['results'][0]['itineraryGroups']
			   $(e).removeClass('ajaxInProcess')
			   if(stayId && itinGroups.length>0){
                               if (itinGroups.length == 1) {
                                   $(e).addClass('ajaxSuccess');
				   $(e).html('Tracking in <a href="/mytrips/trip/?id=' + itinGroups[0].id + '&hv=true">My Trips</a>');
                               } else {
                                   handleMultItinGroups(e,stayId,itinGroups);
                               }
			   }else{
				   $(e).addClass('ajaxError');
				   $(e).html('An error occurred');
			   }
		   }else{
				if(json['errors'][0]['code'] == "NOUSER"){
					$(e).html(json['errors'][0]['message']);
					if (mapIndex)
						mapIndex = '&mapIndex=' + mapIndex;
					window.location = "/login/?returnTo=" + escape(window.location.pathname + window.location.search + '&track=' + hotelId + mapIndex + window.location.hash);
				}
				else{
					$(e).addClass('ajaxError');
					$(e).html('An error occurred');
				}
		   }
	   }
	});
}


function pageResults(page){
	filters['page'] = page;
	moveToTop();
	filterHotels(filters, {'filterMessage': 'Loading page ' + page + '...', 'instant': true});
	return false;
}



function sortResults(sort){
	filters['sort'] = sort;
	filterHotels(filters, {'filterMessage': 'Sorting results...', 'instant': true});
	return true;
}

function sortHotelBrowseResults( sort ) {
    location.search = $.query.set("sort", sort);
}


function filterAmenity(amenity){
    return filterListItem(filterHotels,'amenity',amenity,'~','Filtering amenities...');
}

function filterChains(chainId){
    return filterListItem(filterHotels,'chainId',chainId,'0','Filtering chains...');
}

function filterName(name){
	var n = $(name);
	nv = n.val();
	if (!nv)
		nv = '~';
	if (filters['name'] != nv){
		filters['name'] = nv;
		if (nv == '~')
			nv = '';
		filterHotels(filters, {'filterMessage': 'Filtering name ' + nv});
	}
}

function doFilter(filter, opts){
	filtersReady=true;
	if(filterHotels(filter, opts)){
		return true;
	}
	return false;
}


function clearFilters(){
	filters = {'rating': None, 'page': None, 'sort': None, 'amenity': ''};
	filterHotels(filters, {"filterMessage": "Clearing filters...", 'instant': true});
}

function filterHotels(filter, opts){
    return filterItems(filter, opts, 'hotelResults','/search/hotels/results/filter/');
}

function setupSliders(settings){
	var settings = (settings == null) ? {} : settings;
	var rating = (settings['rating'] == null) ? [1,5] : settings['rating'];
	var price = (settings['price'] == null) ? [0,999] : settings['price'];
	if(!rating.length)
		rating = [1,5];
	filters['rating'] = rating[0] + ',' + rating[1];

	$("#rating-selection").val(rating[0] + ' - ' + rating[1] + ' stars');	
	var starElement = "#star-slider";
	$(starElement).slider({
        orientation: 'horizontal',
		range: true,
		min: 0,
		max: 4,
		step: 1,
		values: [rating[0] - 1, rating[1] - 1],
		slide: function(event, ui) {
			resetTimer();
			$(".ui-slider-handle").blur();
			$("ol.stars li").css("background-position","center bottom");
			$("ol.stars li").slice(ui.values[0], ui.values[1] +1).css("background-position","center top");
			$("#rating-selection").val((ui.values[0] + 1) + ' - ' + (ui.values[1] + 1) + ' stars');
		},
		stop: function(e, u) {
			filters['rating'] = ($(starElement).slider("values", 0) + 1) + ',' + ($(starElement).slider("values", 1) + 1);
			filterHotels(filters, {'filterMessage': 'Filtering by rating...'});
		}
	});

	setupDoubleSlider(price,'price',function(v){return '$'+v;},5);
}


function setupHotelSearchForm(){
	suggestDefault = {width: 400, minChars: 3, selectFirst: true, autoFill: false, delay: 1};
	$("#hotelArriveCityDisplay").autocomplete('/search/hotels/autocomplete/', suggestDefault).result(function(event, data, formatted) {
		if (data){}	});

	$("#rating-selection").val('1 - 5 stars');	
	$("#rating-selection").focus(function(){
		$(this).blur();
	});
	var starElement = "#star-slider";
	$(starElement).slider({
		range: true,
		steps: 5,
		min: 0,
		max: 4,
		values: [0, 4],
		slide: function(event, ui) {
			$(".ui-slider-handle").blur();
			$("ol.stars li").css("background-position","center bottom");
			$("ol.stars li").slice(ui.values[0], ui.values[1] +1).css("background-position","center top");
			$("#rating-selection").val((ui.values[0] +1) + ' - ' + (ui.values[1] +1) + ' stars');
		},
		stop: function(e, u) {
			$("#ratingHidden").val(($(starElement).slider("values", 0) + 1) + ',' + ($(starElement).slider("values", 1) + 1));
		}
	});
	$.datepicker.setDefaults({
		showOn: '',
		currentText: 'Choose a date',
		multiPadding: 20,
		speed: '',
		numberOfMonths: 2,
		showStatus: false,
		closeAtTop: false,
		nextText: 'next &raquo;',
		prevText: '&laquo; prev',
		changeMonth: false,
		changeYear: false,
		minDate: new Date(),
		dayNamesMin: ['S','M','T','W','T','F','S']
	});

	$("#hotelArrive").datepicker({beforeShow: hotelAdjustArrive});
	$("#hotelDepart").datepicker({onSelect: hotelAdjustDepart}); 
}

HotelBrowse = (function () {
    return {
        init: function () {
            HotelBrowse.setupDatepicker();
            $('#hotelDepart').focus( function () {showCal('#hotelDepart');} );
            $('#hotelArrive').focus( function () {showCal('#hotelArrive');} );
            $('#hotelDepart2').focus( function () {showCal('#hotelDepart2');} );
            $('#hotelArrive2').focus( function () {showCal('#hotelArrive2');} );
        },
        setupDatepicker: function () {
            $.datepicker.setDefaults({
                showOn: '',
                currentText: 'Choose a date',
                multiPadding: 20,
                speed: '',
                numberOfMonths: 2,
                showStatus: false,
                closeAtTop: false,
                nextText: 'next &raquo;',
                prevText: '&laquo; prev',
                changeMonth: false,
                changeYear: false,
                minDate: new Date(),
                dayNamesMin: ['S','M','T','W','T','F','S']
            });
            $("#hotelArrive").datepicker({beforeShow: hotelAdjustArrive});
            $("#hotelDepart").datepicker({onSelect: hotelAdjustDepart});
            $("#hotelArrive2").datepicker({beforeShow: hotelAdjustArrive2});
            $("#hotelDepart2").datepicker({onSelect: hotelAdjustDepart2});
        },
        checkPrice: function (hotel) {
            // set hotel name filter
            $('#checkPrice-hotelName')[0].value = hotel;
            HotelBrowse.ui.block();
            return false;
        },
        ui: {
            block: function () {
                $.blockUI({message:$('#checkPriceForm'),
                            css:{'cursor':'default'},
                            overlayCSS:{'cursor':'default'}});
            },
            unblock: function () {
                $.unblockUI();
            }
        }
    };
})();

function hotelAdjustDepart(input){
	arriveDate=readDate('hotelArrive');
	if($('#hotelDepart').datepicker('getDate') > arriveDate){
	$('#hotelArrive').val($.datepicker.formatDate('mm/dd/yy', $('#hotelDepart').datepicker('getDate')));
	}
}

function hotelAdjustArrive(input){
	departDate=readDate('hotelDepart')
	departDate = new Date(departDate.setDate(departDate.getDate() + 1));;
	$('#hotelArrive').datepicker('change', { minDate: departDate} );
}
// refactor this
function hotelAdjustDepart2(input){
	arriveDate=readDate('hotelArrive2');
	if($('#hotelDepart2').datepicker('getDate') > arriveDate){
	$('#hotelArrive2').val($.datepicker.formatDate('mm/dd/yy', $('#hotelDepart2').datepicker('getDate')));
	}
}

function hotelAdjustArrive2(input){
	departDate=readDate('hotelDepart2')
	departDate = new Date(departDate.setDate(departDate.getDate() + 1));;
	$('#hotelArrive2').datepicker('change', { minDate: departDate} );
}

function showRooms(hotel, e){
	$(hotel).toggleClass('hidden');
	$(e).toggle();
	return true;

}

function deepLink(id,stayId,searchId,hotelId){
    trackBooking(stayId,searchId,hotelId,$('#'+id+' [name="url"]').val());
    $('#'+id).submit();
}

function trackBooking(stayId,searchId,hotelId,deepLink) {
    if (deepLink && (stayId || (searchId && hotelId))) {
        var url = '/ajax/hotel/book/?deepLink=' + escape(deepLink)
            + ((hotelId && searchId) ?
               ('&hotelId=' + hotelId + '&searchId='+searchId) :
               ('&stayId='+stayId));
        // we don't need any response; if it fails, we can't do anything about it
        $.ajax({type: 'GET',url: url, cache: false, timeout: 15000});
    }
}
