﻿var	showreviews = 10;
var redirecturl = ''

$(document).ready(function(){

	/**************************************************/
	/********* Global Functions ***********************/
	/**************************************************/

	if(!isLoggedIn()){
		if( $.cookie('views') == null ){
			$.cookie('views', '1', { path: '/', domain: 'vegasguide.com' })
		} else {
			var views = parseInt($.cookie('views'))
			$.cookie('views', views + 1, { path: '/', domain: 'vegasguide.com' })
			if(views == 3){
				showSignUpDialog()
				$.cookie('views', '4', { path: '/', domain: 'vegasguide.com' })
			}
		}
	}


	$('#close-home').click(function(){
		$('#home-booking').fadeOut('slow')
	});

	$('.popup').colorbox();

	// smooth scrolling for on page anchor links
	$('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 600);
				return false;
			}
		}
	});
	
	// item landing pages - UI functions
	$('.show-more').click(function(){
		$('.review-more').animate({"height": "toggle"}, "slow");
		$('.show-more-wrapper').hide()
		$('.show-less-wrapper').show()
	});

	$('.show-less').click(function(){
		$('.review-more').animate({"height": "toggle"}, "slow");
		$('.show-less-wrapper').hide()
		$('.show-more-wrapper').show()
	});

	// poker tournament listings pages to show poker tournament details
	$(".tournament").live('click', function(){
		var tournamentID = $(this).attr('id').replace('t-', '')
		$.ajax({
			url: "/app/ajax/content/poker-tournaments/?id=" + tournamentID,
			success: function(data){
				$.colorbox({html:data});
			}
		});
	});

	

	/******************************************************/
	/*   functions to handle the dialog to search hotels  */
	/******************************************************/


	$('#triptype').live('change', function(){
		if( $(this).val() == 'air' ){
			$('#air').slideDown('fast', function(){
				$('#input-air').autocomplete({
					source: '/app/ajax/autocomplete/airport/',
					dataType: 'json',
					minLength: 2,
					select: function(event, ui) {
						alert(ui.item.id)
					}
				});
				$.colorbox.resize();
			})
		} else {
			$('#air').slideUp('fast', function(){
				$.colorbox.resize();
			})
		}
	});
	
	$('.hotel-getrates-local').click(function(){
		$('.hotel-aff-url').each(function(){
			if( $(this).attr('checked') ){
				openCascadeWin( $(this).val() )
			}
		});
		cascadeWinTop = 0;
		cascadeWinLeft = 0;
	});

	$(".hotel-getrates").live('click', function(){
		var hotelID = $(this).attr('id')
		$.ajax({
			url: '/app/ajax/getrates/?id=' + hotelID,
			success: function(data){
				$.colorbox({html:data});
			}
		});
	});
	
    $('.checkin').live('click', function() {
        $(this).datepicker({showOn:'focus',numberOfMonths: 2}).focus();
    });
	
    $('.checkout').live('click', function() {
        $(this).datepicker({showOn:'focus'}).focus();
    });


	$('#button-rates').live('click', function(){
		$('.hotel-url-dialog').each(function(){
			if( $(this).attr('checked') ){
				openCascadeWin( $(this).val() )
			}
		});
		cascadeWnTop = 0;
		cascadeWinLeft = 0;
		$.colorbox.close();
	});


	//show the items in the guide in the header
	//updateGuideHeaderCount()
	
	//hideGuideItemsAlreadyInGuide()
	
	$('.tipit').cluetip({onShow: function(){
		updateGuideWithCurrentItem($(this).children(0).attr('id'));
		updateGuideHeaderCount();}, 
		clickThrough:'true', 
		fx: { open: 'slideDown', openSpeed:  '1000' }, 
		activation: 'hover', 
		sticky: true, 
		mouseOutClose: true, 
		waitImage: false, 
		closePosition: 'title', 
		arrows: true, 
		closeText: '<img src="/images/icons/close-icon.png">'
	});
	
	$('.view-as').click(function(){
		if( $(this).attr('id') != 'rows'){
			$('.view-as').removeClass('view-as-active')
			$(this).addClass('view-as-active')
			viewas = $(this).attr('id')
			updateResults(false)
		}
	});
	

	$('.pager-item').live('click', function(){
		var viewpage = parseInt($(this).attr('rel').replace('pager-', ''))
		if(viewpage != currentpage){
			currentpage = viewpage;
			$('.pager-item').removeClass('current')
			$(this).addClass('current')
			updateResults(false)
		}
	});

	if(typeof viewrows != "undefined"){
		$('#view-rows').val(10)
	}
	
	$('#view-rows').change(function(){
		viewrows = $(this).val()
		currentpage = 1;
		updateResults(false)
	});
	
	
	$('.add-to-guide').live('click', function(){
		$(document).trigger('hideCluetip');
		$(this).blur()
		var itemID = $(this).attr('id')
		if( $(this).attr('src') == '/images/red-x.png' ){
			$(this).fadeOut('fast')
			$(this).attr('src', '/images/green-plus.png')
			$(this).fadeIn('fast')
			removeItemFromGuide(itemID)
		} else if( $(this).attr('src') == '/images/red-x-large.png' ){
			$(this).fadeOut('fast')
			$(this).attr('src', '/images/green-plus-large.png')
			$(this).fadeIn('fast')
			removeItemFromGuide(itemID)
		} else {
			var itemDescription = $(this).attr('rel')
			$(this).fadeOut('fast')
			if(	$(this).attr('src') == '/images/green-plus-large.png'){
				$(this).attr('src', '/images/red-x-large.png')
			} else {
				$(this).attr('src', '/images/red-x.png')
				}
			$(this).fadeIn('fast')
			if( guideItemExists(itemID) ){
				//do nothing
	   		} else {
	   			addItemToGuide(itemID)
				}
			}
	});
	
	$('.clear-guide').live('click', function(){
		$.cookie('Guide', '', { expires: 356, path: '/', domain: 'vegasguide.com' })
		updateGuideHeaderCount()
	});
	
	$('#search-header').autocomplete({
		source: '/app/ajax/autocomplete/',
		dataType: 'json',
		minLength: 2,
		select: function(event, ui) {
			if(ui.item.id.length > 0){
				document.location.href = ui.item.id
			}
		}
	});
	
	$('.login-link').click(function(event){
		event.preventDefault()
		$.blockUI({ message: $('#login'), css: { width: '275px' } });
	});

	$('.thumb').click(function(event){
		event.preventDefault()
		$('#mainImg').attr('src', $(this).attr('href'))
	});

	$('.show-more-reviews').click(function(){
		var reviewtypeid = $('.show-review-type').val()
		var revieweditemid = $('.show-review-item').val()
		$.ajax({
			url: '/app/ajax/reviews/more/',
			data: 'id=' + reviewtypeid + '&item=' + revieweditemid + '&showreviews=' + showreviews,
			success: function(data){
				$('#more-reviews').append(data)
			},
			error: function(){
				alert('error')
			},
			dataType: 'html'
		});
		showreviews = showreviews + 10
		$('.current-review-count').html(showreviews)
	});
	

});

cascadeWinTop = 0;
cascadeWinLeft = 0;

function openCascadeWin(URL){
	cascadeWinTop += 20;
	cascadeWinLeft += 20;
	var winAttributes = "width=1100,height=500,toolbar=1,menubar=1,scrollbars=1,resizable=1,top=" + cascadeWinTop +",left=" + cascadeWinLeft;
	return (open(URL, "", winAttributes));
}

function updateGuideWithCurrentItem(sID){
	if(guideItemExists(sID)){
		$('#current-item-options').html('Click on the <img src="/images/red-x-small.png"> to remove ' + $('#'+sID).attr('rel') + ' from your guide')
	} else {
		$('#current-item-options').html('Click on the <img src="/images/green-plus-small.png"> to add ' + $('#'+sID).attr('rel') + ' to your guide')
		}
}


function isLoggedIn(){
	$.cookie('uid') == null  ? retval = false: retval = true;
	return retval;
}


function addItemToGuide(itemID){
	if($.cookie('Guide') == null){
		$.cookie('Guide', itemID, { expires: 356, path: '/', domain: 'vegasguide.com'})
	} else {
		var newCookie = ''
		var arCurrentItems = $.cookie('Guide').split('|')
		for (var x = 0; x < arCurrentItems.length; x++){
			newCookie += arCurrentItems[x] + '|'
		}
		newCookie += itemID
		$.cookie('Guide', newCookie, { expires: 356, path: '/', domain: 'vegasguide.com'})
	}
	updateGuideHeaderCount()
}

function removeItemFromGuide(itemID){
	var newCookie = ''
	var arOldItems = $.cookie('Guide').split('|')
	for(var x = 0; x < arOldItems.length; x++){
		if(arOldItems[x] != itemID){
			newCookie += arOldItems[x] + '|'
		}
	}
	newCookie = newCookie.substring(0, newCookie.length-1)
	$.cookie('Guide', newCookie, { expires: 356, path: '/', domain: 'vegasguide.com'})
	updateGuideHeaderCount()
}

function hideGuideItemsAlreadyInGuide(){
	if( $.cookie('Guide') != null ){
		if( $.cookie('Guide').length > 1){
			var arItems = $.cookie('Guide').split('|')
			for (var x = 0; x < arItems.length; x++){
				if(arItems[x].length > 2){
					if( $('#'+arItems[x]).attr('src') == '/images/green-plus-large.png'){
						$('#'+arItems[x]).attr('src', '/images/red-x-large.png')
					} else {
						$('#'+arItems[x]).attr('src', '/images/red-x.png')
						}
				}
			}
		}
	}	
}

function updateGuideHeaderCount(){
	if( $.cookie('Guide') != null ){
		if( $.cookie('Guide').length > 1){
			var totalItems = 0
			var arItems = $.cookie('Guide').split('|')
			for (var x = 0; x < arItems.length; x++){
				if(arItems[x].length > 2){
					totalItems++;
				}
			}
			if( totalItems != 1 ){
				$('#pluralPlaces').html('s')
			} else {
				$('#pluralPlaces').html('')
				}
			$('.guide-count').html( totalItems )
		} else {
			$.cookie('Guide', null)
			$('#pluralPlaces').html('s')
			$('.guide-count').html('0')
			}
	}
}

function guideItemExists(itemID){
	if( $.cookie('Guide') != null ){
		arGuideItems = $.cookie('Guide').split('|')
		for(var x = 0; x < arGuideItems.length; x++){
			if(arGuideItems[x] == itemID){
				return true;
				break;
			}
		}
	}
	return false;
}

function showOverlay(el, msg){
	if(msg.length > 0){
		msg = '<img src="/images/ajax-loader.gif" class="loading-icon"><strong>'+msg+'</strong>'
		$('#' + el).block({ 
			message: msg, 
			centerY: 0,
			css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: '#000', 
				'-webkit-border-radius': '10px', 
				'-moz-border-radius': '10px', 
				opacity: .5, 
				color: '#fff' 
			},
			overlayCSS:  { backgroundColor: '#A7A7A7', opacity: 0.5 }
		}); 
		$('.blockUI.blockPage').css('position','absolute');
	} else {
		$('#' + el).block({
			message: null,
			overlayCSS:  { backgroundColor: '#EEE', opacity: 0.8 }
		}); 
	}
}

function hideOverlay(el){
	setTimeout(function(){
		$('#' + el).unblock();	
	}, 500)
}

function oneChecked(el){
	var retVal = false;
	$('.' + el).each(function(){
		if( $(this).attr('checked') ){
			retVal = true;
		}
	});
	return retVal;
}

function checkedToInt(e){
	if( $('#'+e).attr('checked') ){
		return 1
	} else {
		return 0
	}
}

function confirmUserSubscribed(){
	$.ajax({url: '/app/ajax/login/'});
}


function moveMenu(){
	try{
		$('#rightmenu').show()
		var offset = $('#wrapper').offset()
		var menuleft = offset.left + 966
		$('#rightmenu').animate({top:$(window).scrollTop()+120+"px", left:menuleft},{queue: false, duration: 350});
	} catch(e) {
	
		}
}


function drawMap(rLat, rLon, sItemName, sItemAddress){
    var myLatlng = new google.maps.LatLng(rLat, rLon);
    var myOptions = {
      zoom: 13,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map"), myOptions);


    var contentString = '<div id="map-content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h1 id="firstHeading" class="firstHeading">'+sItemName+'</h1>'+
        '<div id="bodyContent">'+
        '<p>'+sItemAddress+'</p>'+
        '</div>'+
        '</div>';
        
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Uluru (Ayers Rock)'
    });
    
    infowindow.open(map,marker);

}


function showSignUpDialog(){
	$.ajax({
		url: '/app/ajax/content/signup/',
		success: function(data){
			$.colorbox({html:data}, function(){
				try{
					FB.XFBML.parse();
				}catch(ex){}
			});
		}
	});
}

function fblogin() {
	FB.login(function(response) {
		if(response.session.uid.length > 0){
			$.colorbox.close()
		}
		$('#facebooklogin').attr('src', '/images/fb-logout.png')
		$('#fbloginlink').bind('click', function(){
			fblogout();
		})
	}, {perms:'publish_stream,offline_access,email'});
}

function fblogout(){
	FB.logout(function(response) {
	  // user is now logged out
	});
}

