
/**
 * Search Stuff
 * 	 - Autocomplete
 *   - Flatten query string for analytics
 *   - Event handlers for search popup
 */
$(document).ready(function()
{	
	// flatten query string for analytics
	$('#search form').submit(function()
	{
		// remove any placeholder text
		$('input.placeholder, textarea.placeholder', this).each(function()
		{
			if(this.value == this.originalText) { this.value = ''; }
		});
		
		// interrupt the search query, and replace it with a single search string
		var form = $(this);
		var searchText = $("input[type=text][name='query[]']", form);
		var queries = searchText.val() ? [ searchText.val() ] : [ ];
		$('input:checked').each(function() { queries.push($(this).val()); });
		$('input[name=q]', form).val(queries.join(' '));
		window.location = '/search/?query=' + encodeURIComponent(queries.join(' '));
		return false;
	});
	
	// autocomplete
	$('#base-query, #pop-query, input#post_topic').each(function()
	{
		var field = this;
		var options = field.id == 'post_topic' ? { } :
			{ 'resultsClass': 'ac_search', 'width': 213, 'selectFirst': false };		
		$(field).autocomplete('/posts/topics-autocomplete/', options)
		.result(function()
		{
			if(field.id == 'base-query')
			{
				//$(field).val('"' + $(field).val() + '"');
				$(field.form).submit();
			}
		});
	});
	
	// event handlers for search popup
	$('#view-topics').click(function()
	{
		$('#pop-query').val($('#base-query').val());
		$('#topics-pop').fadeIn('fast', function()
		{
			$('#pop-query').focus();
		});
	});	
	$('#close-pop').click(function() { $('#topics-pop').fadeOut('fast'); });
});

/**
 * PNG Fix 
 */
$(document).ready(function()
{
	$.ifixpng('/images/required/pixel.gif');
	$('img[src$=.png]').ifixpng(); 	
});


/** 
 * Set up events for placeholder <input> tags
 */
$(document).ready(function()
{
	$('form:not(form.search-bar)').submit(function()
	{
		$('input.placeholder, textarea.placeholder', this).each(function()
		{
			if(this.value == this.originalText)
			{
				this.value = '';
			}
		});
	});
	
	$('input.placeholder, textarea.placeholder').each(function()
	{
		this.originalText = $(this).val();
		$(this).focus(function()
		{
			if(this.value == this.originalText) { this.value = ''; }
		})
		.blur(function()
		{
			if(this.value == '') { this.value = this.originalText; }
		});
	});
});


/**
 * Provider Map or Contact View 
 */
$(document).ready(function()
{
	var contactLink = $('#map-nav a.contact');
	var mapLink = $('#map-nav a.directions');
	var map = $('#google-map');
	var form = $('#provider-contact');

	// activate the contact form
	contactLink.click(function()
	{
		contactLink.addClass('active');
		mapLink.removeClass('active');
		form.show();
		map.hide();
	});
	
	// activate the google map
	mapLink.click(function()
	{
		contactLink.removeClass('active');
		mapLink.addClass('active');
		map.show();
		form.hide();
	});
});


/**
 * Fix the minimum height of short pages
 */
$(document).ready(function()
{
	var footer = $('#footer');
	var originalHeight = footer.height();
	
	function setFooterSize()
	{		
		var gap = $(window).height() - (footer.position().top + originalHeight);
		footer.height(gap > 0 ? (originalHeight + gap) : originalHeight);
	}
	
	setFooterSize();
	$(window).resize(setFooterSize);
});


/** 
 * Share Popup
 */
$(document).ready(function()
{	
	$('.holder, #wide-column, .left-column').each(function()
	{
		var group = $(this);
		var url = $('form', group).attr('action');
		var slideout = $('.share-slideout', group);
		var shareLinks = $(".share-options a", group);
		var popup = $('.send-email-pop', group);
				
		shareLinks.click(function()
		{
			var pk = $(this).attr('rel');
			var type = $(this).attr('rev');			
			var url = "";
			if($(this).hasClass('announcement'))
			    url = '/announcements/share/';
			else if($(this).hasClass('provider'))
			    url = '/providers/share/';
			else if($(this).hasClass('deal'))
			    url = '/deals/share/';			    			    
			if(url)
			{
    			$.getJSON(url, { pk: pk, type: type }, function(result)
    			{ 
    				if(result.success)
    				{
    					$('.shares-' + pk).text(result.count);
    				}
    			});
            }
		});	
		
		function clearValidation() 
		{
			$('.error', group).css({ display: 'none' });
		}
		
		function validateFields() 
		{
			var success = true;
			var emailPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
			function fail(field) { success = false; $('.' + field).css({ display: 'inline' }); }
			
			// name is missing
			if($("input[name='sender-name']", group).val() == '')
				fail('missing-name');
			 
			// sender email is missing
			if($("input[name='sender-email']", group).val() == '')
				fail('missing-email');
			// sender email is invalid
			else if(!$("input[name='sender-email']", group).val().match(emailPattern))
				fail('invalid-email')
						
			// recipients are missing
			if($("input[name='recipients']", group).val() == '')
			{
				fail('missing-recipients');
			}
			// recipient email(s) are invalid
			else
			{
				var recipients = $("input[name='recipients']", group).val().split(/\s*,\s*/);
				for(var i=0;i<recipients.length;i++)
				{
					if(recipients[i] != '' && !recipients[i].match(emailPattern))
					{
						fail('invalid-recipients');
						break;
					}
				}
			}
			
			return success;
		}
		
		function closeAll()
		{
			$('.share-slideout[open=yes]').each(function()
			{				
				$('.send-email-pop').css({ display: 'none' });
				var slideout = $(this);
				slideout.attr('open', 'no');
				slideout.animate({ height: 0, paddingBottom: 0 }, 'fast', function() 
				{ 
					slideout.css({ display: 'none', overflow: 'hidden' });
					if(window.ResizeGoogleMap) { window.ResizeGoogleMap(); }
				});
			});
		}
						
		// open email popup
		$('.send-email', group).click(function() 
		{
			$('.send-email-pop').css({ display: 'none' });
			$('input.text, textarea', group).val('');
			clearValidation();
			popup.show();
		});
		
		// close email popup
		$('.close-pop', group).click(function() 
		{
			popup.hide("fast", function() { popup.css({ display: 'none' }); });
		});
		
		// send email 
		$('.send-email-pop input[type=submit]', group).click(function()
		{
			clearValidation();
			if(validateFields()) 
			{
				var params = 
				{
					name: $("input[name='sender-name']", group).val(),
					email: $("input[name='sender-email']", group).val(),
					recipients: $("input[name='recipients']", group).val(),
					message: $("textarea[name='message']", group).val()
				};
				
				$.getJSON(url, params, function(results)
				{
					popup.hide("fast", function() { popup.css({ display: 'none' }); });
				});				
			}
			return false;			
		});
	});
	
});


// Hours of Operation fields
$(function() {
    
    var schedule = $('.schedule');
    var copySchedule = $('.copy-schedule input[type=checkbox]');
    var days = schedule.find('.day');
    var openFields = schedule.find('input.open');
    var closeFields = schedule.find('input.close');
    var closedFields = schedule.find('input.closed');
    
    // apply to all button
    function applyToAll(enabled) {
        if(enabled) {
            // copy values
            openFields.val(openFields.val());
            closeFields.val(closeFields.val());
            closedFields.attr('checked', closedFields.attr('checked'));
            // disable all others
            openFields.filter(':gt(0)').attr('disabled', true);
            closeFields.filter(':gt(0)').attr('disabled', true);
            closedFields.filter(':gt(0)').attr('disabled', true);
        }
        else {
            copySchedule.attr('checked', false);
            // enable all (if they aren't closed)
            closedFields.attr('disabled', false);
            days.filter(':gt(0)').each(function() {
                var day = $(this);
                if(!day.find('input[type=checkbox]').attr('checked')) {
                    openFields.attr('disabled', false);
                    closeFields.attr('disabled', false);                    
                }
            })            
        }
    }        
    copySchedule.change(function() { applyToAll(copySchedule.attr('checked')); });
    
    // editing the first day
    function unapplyToAll() {
        applyToAll(false); 
    }
    openFields.filter(':lt(1)').change(unapplyToAll);
    closeFields.filter(':lt(1)').change(unapplyToAll);
    closedFields.filter(':lt(1)').change(unapplyToAll);
    
    // closed buttons
    days.each(function() {
        var day = $(this);
        day.find('input.closed').change(function() {
            if($(this).attr('checked')) {
                day.find('input[type=text]').val('').attr('disabled', true);
            }
            else {
                day.find('input[type=text]').attr('disabled', false);
            }
        })
    })
      
})

// disable the search form when there's no non-default text
$(function() {
    var form = $('form.search-bar');
    var fields = form.find('input[type=text]');
    fields.each(function() { 
        if($(this).val() == '') {
            $(this).val($(this).attr('original')); 
        }
    });
    fields.focus(function() { 
        if($(this).val() == $(this).attr('original')) {
            $(this).val('');
        } 
    })
    fields.blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('original'));
        }
    })
    form.submit(function() {
        var hasChanged = false;
        fields.each(function(){ 
            hasChanged = hasChanged || ($(this).val() != $(this).attr('original') && $(this).val() != ''); 
        });
        if(hasChanged) {
            fields.each(function(){
                if($(this).val() == $(this).attr('original')) {
                    $(this).val('');
                }
            })
        }
        return hasChanged;
    });
});

$(function() {
    $('a.make-live').click(function() {
        return confirm('You cannot edit a deal once it is published. Do you wish to continue?');
    });
    $('a.delete-icon').click(function() {
        return confirm('Are you sure you want to delete this deal?');
    });
    $('a.end-deal').click(function() {
        return confirm('Are you sure you want to end this deal?');
    });
    $('a.no-show').click(function() {
        return confirm('Are you sure you want to mark this appointment as "No Show"?');
    });
    $('#provider a.cancel-booking').click(function() {
        return confirm('Are you sure you want to cancel this booked appointment?');
    })
    $('a.unpublish-announcement').click(function() {
        return confirm('Are you sure you want to unpublish this announcement?');
    })
})

$(function() {
    $('.transactions .container-cell').each(function() {
        var container = $(this);
        var expander = container.find('a.expander');
        var appointments = container.find('table.mini');
        var expanded = false;
        expander.click(function() {
           expanded = !expanded;
           appointments[expanded ? 'show' : 'hide']();
        })
    });
    $("#time-period").change(function () {
        $(".time-period").submit();
    });
})
