$(function() {

    //itiniery dragger
    $("#itinerary").sortable({
		'handle': '.handle',
		'update': function(event, ui) {
			var ids = [];
			$('#itinerary .itinerary_event').each(function (i) {
				ids[i] = $(this).attr('id');
			});
			
			//save reorder request
			$.ajax({
				'url': 'save.php',
				'type': 'post',
				'data': {
					'ids': ids
				},
				'success': function(data, textStatus, xhr) {
					$('a.block_link.share').attr('href', data)/*.css('background-color', 'red').animate({'background-color': '#54301A'}, 500)*/;
					$('a.block_link.save').attr('href', data)/*.css('background-color', 'red').animate({'background-color': '#54301A'}, 500)*/;
					$('a.block_link.email').attr('href', 'mailto:name@example.com?body=' + data)
				}
			});
			
			//event.stopPropagation();
		}
	});
	$('#itinerary .itinerary_event h3 .arrow').click(function () {
		$(this).closest('.itinerary_event').find('.itinerary_content').slideToggle(function () {
			if($(this).css('display') == 'block') {
				$(this).parent().addClass('iten-event-open').removeClass('iten-event-closed');
			}
			else {
				$(this).parent().addClass('iten-event-closed').removeClass('iten-event-open');
			}
		});
	});
	
	$('.itinerary_store').click(function () {
		var $self = $(this);
		$.ajax({
			'url': 'store.php',
			'type': 'post',
			'data': {},
			'success': function () {
				window.location = $self.attr('href');
			}
		});
	});
	
	//this works on SAVED itinieraies
	$('.itinerary_remove').click(function () {
		var $self = $(this);
		var index = $self.data('index');
		var id = $self.data('id');
		
		$.ajax({
			'url': 'remove.php',
			'type': 'post',
			'data': {
				'index': index,
				'id': id
			},
			'success': function() {
				$self.parent().fadeOut(function () {$self.parent().remove()});
			}
		});
	})
	
	$('.itinerary_ajax').click(function () {
		var $self = $(this), mw;
		
		$self.append('<img class="ajax-loader" src="' + root + 'images/ajax-loader.gif" />');
		
		$.ajax({
			'url': $self.attr('href'),
			'type': 'get',
			'data': {
				'ajax': '1'
			},
			'success': function() {
				var offset, w, h;
				if($self.hasClass('block_link')) {
					$self.css('background-color', '#68933E').animate({'background-color': '#54301A'}, 500);
				}
				$self.find('.ajax-loader').remove();
				
				$msg = $('<div class="itinerary_msg">');
				$msg.html('<div><h3>Success, added item to itinerary!</h3><p><a href="' + root + 'itinerary/">View your itinerary</a> or <a href="#" class="close">keep browsing</a>.</p>');
				
				offset = $self.offset();
				w = $self.width();
				h = $self.height();
				
				//msg.width = 294 as defined in css
				mw = 294;
				mh = 121; //height of the background image
				$msg.css({
					'display': 'none',
					'left': offset.left - (mw-w)/2 - 20, //20 is the offset of the triangle pointer
					'top': offset.top - mh
				});
				
				$('body').append($msg);
				$msg.fadeIn();
			}
		});
		
		return false;
	});
	
	if($('#slideshow').size() > 0) {
    	//homepage hero slideshow, from http://malsup.com/jquery/cycle/
	    $('#slideshow').cycle({
			fx: 'fade',
			next:   '#ss_next', 
			prev:   '#ss_prev',
			pager:  '#slideshow_nav', 
			timeout: 5000,
		    // callback fn that creates a thumbnail to use as pager anchor 
		    pagerAnchorBuilder: function(idx, slide) { 
		        return '<a href="#" class="dot"></a>'; 
		    }/*,
			after: function(options) {
				$('#slide_index').html($(this).index() + 1);
			}*/
		});
	
		$('#hero').hover(function () {
			$('#slideshow').cycle('pause');
		}, function () {
			$('#slideshow').cycle('resume');
		});
	}
	
	$('input.room').blur(function () {
		var total = 0;
		$('input.room').each(function() {
			total += $(this).val() * 1;
		});
		$('#total_rooms').html(total);
	});
	
	if($('#event-slideshow').size() > 0) {
    	//homepage hero slideshow, from http://malsup.com/jquery/cycle/
	    $('#event-slideshow').cycle({
			fx: 'fade',
			timeout: 5000
		});
	
		$('#event-slideshow').hover(function () {
			$('#event-slideshow').cycle('pause'); 
		}, function () {
			$('#event-slideshow').cycle('resume'); 
		});
	}
	
	$('input.default').each(function () {
        var default_val = $(this).attr('default');
		if($(this).val() == '') {
			$(this).val(default_val);
		}

        $(this).focus(
            function() {
                if(default_val == $(this).val()) {
                    $(this).val('');
                }
                $(this).addClass('focus');
            }
        ).blur(
            function() {
                if('' == $(this).val()) {
                    $(this).val(default_val);
                }
                $(this).removeClass('focus');
            }
        );
    });

	$('form').submit(function() {
		$(this).find('input.default').each(function(index, value) {
			if($(value).val() == $(value).attr('default')) {
				$(value).val('');
			}
		});
	});

	$('input.datepicker').datepicker({});
	
	$('.message').live('click', function() {
		$(this).hide('puff', {
			percent: 95
		});
	});
	
	$('.itinerary_msg .close').live('click', function() {
		$('.itinerary_msg').fadeOut(function () { $(this).remove(); });
	});

	var $fancyLinks = $('a.fancybox');
	if($fancyLinks[0]) {
		$fancyLinks.fancybox();
	}

	BlockDateChanged();
	
	//process login
	$('#signin').fancybox({
		'type': 'iframe',
		'href': $('#signin').attr('href') + '?popup',
		'padding': '0',
		'width': 365,
		'height': 240
	});
	
	$('#account_links').hover(function () {$(this).addClass('hover')}, function () {$(this).removeClass('hover')});

});

//////////////////////
// SURVEY POPUP CODE

var surveyTimer
var surveyTimerMsec = 2000;
var surveyWaitSecs	= 150;

$(document).ready(function() {

	var endTime		= getSimpleCookie('endTime');

	if(!endTime)
	{
		var objDate		= new Date();
		var nowTime		= objDate.getTime();

		//console.log('nowTime = '+nowTime);

		endTime		= nowTime + (1000 * surveyWaitSecs);
		setSimpleCookie('endTime',endTime);

		//console.log('Creating endTime cookie');
	}

	//console.log('endTime = '+endTime);
	//console.log('setting timer');
	surveyTimer		= setTimeout("SlideSurveyCheckTime()", surveyTimerMsec);
});

function SlideSurveyCheckTime()
{
	console.log('SlideSurveyCheckTime()');

	clearTimeout(surveyTimer);
	var objDate		= new Date();
	var nowTime		= objDate.getTime();
	var endTime		= getSimpleCookie('endTime');

	//console.log('nowTime = '+nowTime);
	//console.log('endTime = '+endTime);

	if(nowTime > endTime)
	{
		//console.log('show thing!');
		setTimeout("SlideSurveyPopup()", 0);
	}
	else
	{
		//console.log('setting timer');
		surveyTimer	= setTimeout("SlideSurveyCheckTime()", surveyTimerMsec);
	}
}

function SlideSurveyPopup()
{
	$('.TT_SurveyPopup').show();
	$('.TT_SurveyPopup').animate({marginTop: '500px'}, 1500);
}

function SurveyPopupClicked()
{
	$('.TT_SurveyPopup').fadeOut(300);

	setSimpleCookie('survey_popup_clicked','yes');
}

// SURVEY POPUP CODE
//////////////////////

function signin(type) {
	$.fancybox({
		'type': 'iframe',
		'href': $('#signin').attr('href') + '?popup&type=' + type,
		'padding': '0',
		'width': 365,
		'height': 240
	});
	
	//return false;
}

function ad_popup(field) {
	window.open('advertising_popup.php?&element_id=' + field, 'admin_pop','width=400,height=400,scrollbars=yes');
}

function event_popup(field) {
	window.open('event_popup.php?&element_id=' + field, 'admin_pop','width=400,height=400,scrollbars=yes');
}

function itinerary_remove(id, type) {
	$('#' + type +'-' + id).fadeOut(function () { 
		$(this).remove(); 
		
		var ids = [];
		$('#itinerary .itinerary_event:visible').each(function (i) {
			ids[i] = $(this).attr('id').replace('event-', '');
		});
		
		//save reorder request
		$.ajax({
			'url': 'save.php',
			'type': 'post',
			'data': {
				'ids': ids
			},
			'success': function(data, textStatus, xhr) {
				$('a.block_link.share').attr('href', data);
				$('a.block_link.save').attr('href', data);
				$('a.block_link.email').attr('href', 'mailto:name@example.com?body=' + data)
			}
		});
	});
	
	return false;
}

// Fix FOUT for font replacement (http://paulirish.com/2009/fighting-the-font-face-fout/)
(function(){
	// if firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
	var d = document, e = d.documentElement, s = d.createElement('style');
	if(e.style.MozTransform === '') { // gecko 1.9.1 inference
		s.textContent = 'body{visibility:hidden}';
		e.firstChild.appendChild(s);
		var f = function(){s.parentNode && s.parentNode.removeChild(s);};
		addEventListener('load',f,false);
		setTimeout(f,3000);
	}
})();

var BlockDateChanged_InProgress = false;
function BlockDateChanged()
{
	if(BlockDateChanged_InProgress == false)
	{
		BlockDateChanged_InProgress = true;

		//	GET start and end dates
		var StartDateString = $('#BlockStartDate').val();
		var EndDateString	= $('#BlockEndDate').val();

		if(StartDateString)
		{
			var StartDateArray	= StartDateString.split('/');
			var EndDateArray	= EndDateString.split('/');

			//	SET end date
			var EndDate			= new Date(parseInt(EndDateArray[2]*1),	parseInt(EndDateArray[0]*1)-1,	 parseInt(EndDateArray[1]*1));

			//	CLEAR dates
			for(var i = 0 ; i < 14 ; i++)
			{
				$('#Block'+(i+1)+'Date').html('');
			}

			//	POPULATE dates
			for(var i = 0 ; i < 14 ; i++)
			{
				//	SET current date
				var CurrentDate	= new Date(parseInt(StartDateArray[2]*1), parseInt(StartDateArray[0]*1)-1, parseInt(StartDateArray[1]*1)+i);

				//	SET html for date
				$('#Block'+(i+1)+'Date').html((CurrentDate.getMonth()+1)+'/'+(CurrentDate.getDate()));

				//	BREAK if end date reached
				if(CurrentDate.toDateString() == EndDate.toDateString())
				{
					break;
				}
			}
		}

		BlockDateChanged_InProgress = false;
	}
}
function hideBilling() {
    if(document.getElementById("billing_option").checked)
        {
            document.getElementById("billing1").style.display = 'none';
            document.getElementById("billing2").style.display = 'none';
            document.getElementById("billing3").style.display = 'none';
            document.getElementById("billing4").style.display = 'none';
            document.getElementById("billing5").style.display = 'none';
            document.getElementById("billing6").style.display = 'none';
        }
    else
        {
            document.getElementById("billing1").style.display = '';
            document.getElementById("billing2").style.display = '';
            document.getElementById("billing3").style.display = '';
            document.getElementById("billing4").style.display = '';
            document.getElementById("billing5").style.display = '';
            document.getElementById("billing6").style.display = '';
        }

    
}
function hideMailing() {
    if(document.getElementById("mailing_option").checked)
        {
            document.getElementById("mailing1").style.display = 'none';
            document.getElementById("mailing2").style.display = 'none';
            document.getElementById("mailing3").style.display = 'none';
            document.getElementById("mailing4").style.display = 'none';
            document.getElementById("mailing5").style.display = 'none';
            document.getElementById("mailing6").style.display = 'none';
        }
    else
        {
            document.getElementById("mailing1").style.display = '';
            document.getElementById("mailing2").style.display = '';
            document.getElementById("mailing3").style.display = '';
            document.getElementById("mailing4").style.display = '';
            document.getElementById("mailing5").style.display = '';
            document.getElementById("mailing6").style.display = '';
        }


}

function setSimpleCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getSimpleCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");

	for (i = 0 ; i < ARRcookies.length ; i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
}
