$(function(){
	
	//open modal automatically if user doesnt have cookie set
	if($("#newsletter").length > 0 && $.cookie('suppress_optin') == null) {
		$.get($("#newsletter").attr('href'),function(data) {
			$.modal(data,{dataCss:{width:'542px'}});
			cookieSubscribeShown();
		 });
	}
	
	$("#newsletter").click(function(e){
		e.preventDefault();
		$.get($(this).attr('href'),function(data) {
				$.modal(data,{dataCss:{width:'542px'}});
		 });
	});

	
	$("#form-subscribe").live("submit", function(e){
		e.preventDefault();
		handleSubscribe();
	});
	
	$('.close_opt_in').live('click',function(){
		$.modal.close();
	});
	
});

function cookieSubscribeShown() { //set a cookie so we dont bother them again
	$.cookie('suppress_optin', 'true', { expires: 10000, path: '/' });
}

function handleSubscribe() { //process user subscription
	
	var days = [];
	
	$('input.dayopt:checked').each(function(){
		days[days.length] = $(this).val();
	});
	
	 $.post('/block/subscribe', {
        'email': $('input#email').val(),
        'location': $('input#location').val(),
        'radius': $('select#radius').val(),
        'eso': $('input[name=eso]:checked').length,
        'source': $('input[name=source]').val(),
        'keywords': $('textarea[name=keywords]').val(),
		'days': days
	}, function(data) {
		
		$result = $('#subscribe p.error');
		
		if ($(data).find('success').text() == 'true' || /<success>true/.test(data)) { //ie is having issues with the jquery DOM methods so use regexes as a backup
        		
        		if($('#panel-2:visible').length == 0) {
        		
        			$('#panel-1').hide();
        			$('.modal-title').html("You're All Set!");
        			$('.modal-btm').find('a.button').html('Submit');
        			$('#panel-2').show();
        			$result.hide();

        		} else {
        		
        			$('#panel-2').hide();
        			$('.modal-btm').html('');
        			
        			$('.modal-title').html("Thank you for signing up!");
        			        		
	        		$('.modal-body').append('<h2 style="margin-bottom:15px">This window will automatically close in 15 seconds.</h2><p>You will now receive email notifications on the day(s) you chose when there are new estate sales in your area. You can update what day you receive emails on, filter by keywords, and more by going to your <a href="/subscriber/'+$('input#email').val()+'">email notification preferences page</a><br/><br/><a href="javascript:clearTimeout(closeTimeout);$.modal.close();">Close</a>.</p>');
	
            		closeTimeout = setTimeout(function(){
            			$.modal.close();
            		},15000);
	            		
        		}

        } else {
        	
        	$result.html('');
			$(data).find('error').each(function() {
             	$result.append($(this).text() + "<br />");
            });
            
			$result.show();
            
        }
			            
	});

}
