$(document).ready(function () {
	
	$('#resources_list h3:first').each(function(){
		$(this).next().next().find('li a').each(function(){
			
			if ($(this).html() != 'e-mail') { 
				var name = $(this).html();
				var website = $(this).attr('href');
				//$.post(base_url+'resources/add', {name:name, website:website, id:2});
				//alert(name + ' ' + website);
			} else {
				var email = $(this).attr('href');
				var name = $(this).prev().html(); 
			//	$.post(base_url+'resources/add', {name:name, email:email});
				//alert(name + ' ' + email);
			}
			
		});
	});
	
	$('form #row_nonprofit_category input:checkbox').click(function(){
		if ($("input:checkbox:checked").length > 3) {
			alert("You may only choose up to three categories");
			return false;
		}
	});
	
	if ($('p.error').size() > 0){
		$('div.input').show();	
	}
	
	if ($('#tags_help').size() > 0) {
		
		$('a#tags_help').mouseover(function(){
			show_tags_help($(this));
		});
				
		$('a#tags_help').mouseout(function(){
			hide_tags_help();
		});
		
	}
	
	$('#header .home_link').click(function(){
		redirect(base_url);
	});

	
	//smooth scrolling
	if ($('.localscroll').size() > 0){
		$('.localscroll').localScroll();
	}
	
	if ($('#admin').size() > 0){

		$('select.event_photo').change(function(){
			var id = $(this).attr('event_id');
			var file = $(this).val();
			
			$.post(base_url+'events/associate_photo/'+id, {file_name:file}, function(){
				alert('Image has been associated with this event');
			});
		});
		
		$('a.feature').click(function(){
			var id = $(this).attr('rel');
			var me = $(this);
			var confirm = window.confirm('Are you sure you want to feature this event?');
			if (confirm) {
				$.post(base_url+'events/feature/'+id, {}, function(){
					me.html('&#x2714;');
				});
			}
			
		});

		$('a.delete').click(function(){
			var id = $(this).attr('rel');
			var name = $(this).attr('title');
			var controller = $(this).attr('controller');
			var me = $(this);
			var table = $(this).closest('table');
			var confirm = window.confirm('Are you sure you want to delete "'+name+'"?');
			if (confirm) {
				me.html('<img src="'+public_folder+'images/loading.gif"/>');
				$.post(base_url+controller+'/delete_data/'+id, {}, function(){
					me.closest('tr').remove();
					table.find('tr').removeClass('alt');
					table.find('tr:odd').addClass('alt');
				});
			}
			
		});
		
		$('a.edit_hero').click(function(){
			$(this).closest('tr').next().show();
			$(this).closest('tr').hide();
		});

		$('a.delete_hero').click(function(){
			var id = $(this).attr('rel');
			var name = $(this).attr('title');
			var me = $(this);
			var confirm = window.confirm('Are you sure you want to delete "'+name+'"?');
			if (confirm) {
				me.html('<img src="'+public_folder+'public/images/loading.gif"/>');
				$.post(base_url+'admin/delete_hero/'+id, {}, function(){
					me.closest('tr').remove();
				});
			}
		});
		
	}
	
	if ($('#np_search').size() > 0) {
		setup_autocomplete_np();
	}

	if ($('#resources_search').size() > 0) {
		setup_autocomplete_resources();
	}
	
	if ($('#calendar').size() > 0) {
		
		setup_autocomplete();
		
		$('.input_date').datepicker({
			dateFormat: 'yy-mm-dd'
		});

		$('.input_time').ptTimeSelect();

		var d = new Date();
		var y = d.getFullYear();
		var m = d.getMonth();
		//grab the username off the end of the url
		var username = window.location.href.substr((base_url+'calendar/').length) || '';
		//console.log(username);
		$('#calendar').fullCalendar({
			timeFormat: 'h(:mm)tt',
			allDayDefault: false,
			//theme: true,
			events: base_url+'calendar/events/'+username,
			eventRender: function(calEvent, element){outline_featured_event(calEvent, element);},
			eventClick: function(calEvent, e){calendar_popup(calEvent, e); e.preventDefault();},
			loading: function(bool) {
				if (bool) $('#loading').show();
				else $('#loading').hide();
			}
		});
		//if the dialog does not exist yet (it doesn't)
		if( $('#calendar_popup').size() <= 0 ){
			$('body').append('<div id="calendar_popup" class="event_info"></div>');
		}
		//make the dialog for the element
		$('#calendar_popup').dialog({
			modal: true,
			autoOpen: false,
			width: 600
		});
	}
	
	/*
   $('<div id="qtip-blanket">')
      .css({
         position: 'absolute',
         top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
         left: 0,
         height: $(document).height(), // Span the full document height...
         width: '100%', // ...and full width

         opacity: 0.7, // Make it slightly transparent
         backgroundColor: 'black',
         zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially
	*/
	
});

function show_tags_help(a) {
	a.after('<div id="tags_help_box"><p>Tags are keywords you wish to associate with your organization. For example, an <strong>Animal Shelter</strong> might use these tags:</p><p><strong>dogs, cats, pets, animals</strong> </p></div>');
	$('#tags_help_box').fadeIn();
}

function hide_tags_help(a) {
	$('#tags_help_box').fadeOut();
}

//make the dialog body and 
function calendar_popup(calEvent, e) {
	buy_link = '';
	if(calEvent.buy_link && calEvent.buy_link.length>0){
		buy_link = ' ('+calEvent.buy_link+')';
	}
	
	html = '<p>';
	
	if(typeof calEvent.event_link != 'undefined' && calEvent.event_link != ''){
		link = calEvent.event_link;
		html += '<div class="fblike">';
		html += '<iframe src="https://www.facebook.com/plugins/like.php?href='+link+'&amp;layout=button_count&amp;show_faces=false&amp;width=400&amp;action=like&amp;font=lucida+grande&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:400px; height:21px;" allowTransparency="true"></iframe>';
		html += '</div>';
	}
	
	if(typeof calEvent.organization != 'undefined' && calEvent.organization != ''){
		html += '<strong>Organization</strong>: ' + calEvent.organization + '<br/>';
	}
	
	if(typeof calEvent.profile_link != 'undefined' && calEvent.profile_link != ''){
		html += '<strong>Post by</strong>: ' + calEvent.profile_link + '<br/>';
	}
    
    if(typeof calEvent.day != 'undefined' && calEvent.day != ''){
		html += '<strong>Date</strong>: ' + calEvent.day + '<br/>';
	}
    if(typeof calEvent.start_hour != 'undefined' && calEvent.start_hour != ''){
		html += '<strong>Time</strong>: ' + calEvent.start_hour + ' - ' + calEvent.end_hour + '<br/>';
	}
	if(typeof calEvent.ticket_price != 'undefined' && calEvent.ticket_price != ''){
		html += '<strong>Price</strong>: ' + calEvent.ticket_price + '<br/>';
	}
	if(typeof calEvent.buy_tickets != 'undefined' && calEvent.buy_tickets != ''){
		html += '<strong>Tickets</strong>: ' + calEvent.buy_tickets + '<br/>';
	}
	if(typeof calEvent.description != 'undefined' && calEvent.description != ''){
		html += '<strong>Description</strong>: ' + calEvent.description + '<br/>';
	}
	if(typeof calEvent.url != 'undefined' && calEvent.url != ''){
		html += '<strong>Website</strong>: <a href="' + calEvent.url + '" target="_blank">' + calEvent.url + '</a>';
	}
    html += '</p>';
	
	/*
	$(element).qtip({
        content: {
            title: {
                text: calEvent.title,
                button: 'Close'
            },
            text: html
        },
        position: {
            target: $(document.body),
            // Position it via the document body...
            corner: 'center'
            // ...at the center of the viewport
        },
        show: {
            when: 'click',
            // Show it on click
            solo: true
            // And hide all other tooltips
        },
        hide: false,
        style: {
            width: {
                max: 450
            },
            padding: '14px',
            border: {
                width: 5,
                radius: 10,
                color: '#666666'
            },
            name: 'light'
        },
        api: {
            beforeShow: function()
            {
                // Fade in the modal "blanket" using the defined show speed
                $('#qtip-blanket').fadeIn(this.options.show.effect.length);
            },
            beforeHide: function()
            {
                // Fade out the modal "blanket" using the defined hide speed
                $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
            }
        }

    });
	*/
	
	$('#calendar_popup').html(html).dialog({'title':calEvent.title}).dialog('open');
	
}

//adds a stlye (outline) to featured events. Fancy shmancy
function outline_featured_event(calEvent, element){
	window.log(calEvent.title +': '+ calEvent.is_featured);
	if(typeof calEvent.is_featured != 'undefined' && calEvent.is_featured == true){
		$(element).addClass('is-featured');
		
	}	
}

function validate_checkboxes() {
	if ($("input:checkbox:checked").length == 0) {
		alert("You must choose at least one category");
		return false;
	}
	return true;
}

function google_search_setup(){
	var query = $('div.site_search form input[name="query"]').val();
	$('div.site_search form input[name="query"]').val('');
	$('div.site_search form input[name="q"]').val('site:chicagononprofit.org '+query);
}

function setup_autocomplete() {
	$("input.organization").autocomplete(base_url+"calendar/get_non_profits", {
		minChars: 1,
		max: 25,
		autoFill: false,
		mustMatch: false,
		//highlight: true,
		scrollHeight: 220,
		selectFirst: false
	});
}

function setup_autocomplete_np() {
	$("#np_search").autocomplete(base_url+"calendar/get_non_profits", {
		minChars: 1,
		max: 25,
		autoFill: false,
		mustMatch: false,
		matchContain: true,
		//highlight: true,
		scrollHeight: 220,
		selectFirst: false
	});
}

function setup_autocomplete_resources() {
	$("#resources_search").autocomplete(base_url+"resources/get_resources", {
		minChars: 1,
		max: 25,
		autoFill: false,
		mustMatch: false,
		//highlight: true,
		scrollHeight: 220,
		selectFirst: false
	});
}

function delete_data(id, controller) {
		

}

// Start Twitter Feed

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};

function get_tweets(account){
	
	if(account != undefined && account != "") {
		var url = 'https://twitter.com/statuses/user_timeline/';  
		var user = account;
		var opts = '.json?count=3&callback=?';
		$.getJSON(url+user+opts, function(data){
	   		$.each(data, make_tweet);
			$('#tweets .loading').fadeOut('fast');
		});
	} else {
		$('.twitter_feed').hide();
	}
}
function make_tweet(i, tweet){
	//var post_date = tweet.created_at.substring(0, tweet.created_at.lastIndexOf(':'));
	var post_date = tweet.created_at.substring(4, 10);
	var html = '<div class="tweet">'+
					'<div class="tweet_date">'+post_date+'</div>'+
					'<div class="tweet_text">'+tweet.text.parseURL()+'</div>'+
				'</div>';
	$(html).hide().appendTo('#tweets').fadeIn(400);
}

// End Twitter Feed

function redirect(where) {
	if(!where || (typeof where == 'undefined')){
		 window.location.reload(true);
	}else{
		window.location = where;
	}
}

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};