$(document).ready(function(){ // wait for document to load 
	$("a.email").each(function(i) {
		var text = $(this).text();
		var address = text.replace(' at ', '@');
		$(this).attr("href", "mailto:" + address);
		$(this).text(address);
	});

	window.recommendationSuggest = function(activityid){
		$('#recommendation_text_'+activityid).autocomplete("site.ajax.beersuggest.php",{},$('#recommendation_id_'+activityid));
	}

	window.deleteActivity = function(activityid){
		var dataString = 'mode=DELACTIVITY&activityid='+ activityid;
	  $.ajax({  
	    type: "POST",  
	    url: "index.save.php",  
	    data: dataString,  
	    success: function() {  
	      	// remove the li
	      	$('#activity_'+activityid).fadeOut(300);
	      }
	    });  
	}
	
	window.openAttendees = function(eventid, userid){
		// check if a hidden field is set to open for this attendee group
		if ($('#attendee_slide_state_'+eventid).val() == '0'){
			$.getJSON('site.ajax.attendee.php?eventid=' + eventid,
		        function(data){
					var registered = false;
					var html = '<div class="commentdiv"><ul id="attendee_list_'+eventid+'">';
					if (data.items.length > 0){
						$.each(data.items, function(i,item){
							if (userid == item.userid){
								registered = true;
								delhtml = '<a href="#" onclick="deleteAttendee('+item.attendeeid+');return false;" class="delete">delete</a>';
							} else {
								delhtml = '';
							}
							var guest_html = '';
							if (item.guestcount != ''){
								guest_html = '+'+item.guestcount+' guests  ';
							}
							html += '<li id="attendee_li_'+item.attendeeid+'"><img width="18px" height="18px" style="float:left;" src="'+item.user_avatar_path+'" alt="user_img"/><div class="comment"><a href="user.php?id='+item.userid+'">'+item.screenname+'</a>'+item.comment+'<strong>'+guest_html + delhtml+'</strong></div></li>';
						});
					} else {
						if (userid > 0){
							html += '<li>Be the first to attend!</div></li>';
						} else {
							html += '<li>Register and you can attend!</div></li>';
						}
					}
					html +=	'</ul></div>';
					if (userid > 0){
						html += '<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeAttendees('+eventid+');return false;"><img src="assets/images/27close.png" alt="close"/></a><div class="comment_entry">+Guests:<input id="attendee_guests_'+eventid+'" type="text" maxlength="2" style="width:20px;"/>Say:<input id="attendee_text_'+eventid+'" maxlength="160" type="text" style="width:130px;"/><button onclick="saveAttendee('+eventid+', '+userid+');return false;">Attend</button></div></div>';
					} else {
						html += '<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeAttendees('+eventid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					}
					$('#attendee_'+eventid).html(html);
					// open the div
					$('#attendee_'+eventid).slideDown('slow');
					$('#attendee_guests_'+eventid).focus();
					$('#attendee_slide_state_'+eventid).val('1');
		        }
			);		
		} else {
			closeAttendees(eventid);
		}		
	}
	
	window.closeAttendees = function(eventid){
		$('#attendee_'+eventid).slideUp("fast");
		$('#attendee_slide_state_'+eventid).val('0');
	}	
	
	window.deleteAttendee = function(attendeeid){
		var dataString = 'mode=DELETE&id='+attendeeid;
	  	$.ajax({  
			type: "POST",  
			url: "site.ajax.attendee.php",  
			data: dataString,  
			success: function() {  
				// get the last attendee and append to attendee list
				$('#attendee_li_'+attendeeid).fadeOut(300);
			}
	    });  
	}
	
	window.saveAttendee = function(eventid, userid){
		var guestcount = $('#attendee_guests_'+eventid).val();
		if (guestcount != ''){
			if (!isNumeric(guestcount)){
				alert('Guest count must be an integer!');
				$('#attendee_guests_'+eventid).focus();
				return false;			
			}
		}
		var comment = $('#attendee_text_'+eventid).val();
		// save
		var dataString = 'mode=ADD&userid='+userid+'&guestcount='+guestcount+'&comment='+urlencode(comment)+'&eventid='+ eventid;
	  	$.ajax({  
			type: "POST",  
			url: "site.ajax.attendee.php",  
			data: dataString,  
			success: function() {  
				// get the last attendee and append to attendee list
				reloadAttendees(eventid, userid);
			}
	    });  
	}	
	
	window.reloadAttendees = function(eventid, userid){
		// fade out attendee_list_
		$('#attendee_list_'+eventid).slideUp('slow', function(){
			$.getJSON('site.ajax.attendee.php?getlatest=1&eventid=' + eventid,
		        function(data){
					var guestcount = 0;
					var html = '';
					if (data.items.length > 0){
						$.each(data.items, function(i,item){
							guestcount++;
							if (userid == item.userid){
								registered = true;
								delhtml = '<a href="#" onclick="deleteAttendee('+item.attendeeid+');return false;" class="delete">delete</a>';
							} else {
								delhtml = '';
							}
							var guest_html = '';
							if (item.guestcount != ''){
								guestcount += parseInt(item.guestcount);
								guest_html = '+'+item.guestcount+' guests  ';
							}
							html += '<li id="attendee_li_'+item.attendeeid+'"><img width="18px" height="18px" style="float:left;" src="'+item.user_avatar_path+'" alt="user_img"/><div class="comment"><a href="user.php?id='+item.userid+'">'+item.screenname+'</a>'+item.comment+'<strong>'+guest_html + delhtml+'</strong></div></li>';
						});
					} else {
						html += '<li>Whoops, an error occurred.</div></li>';
					}
					$('#attendee_list_'+eventid).html(html);
					$('#attendee_list_'+eventid).slideDown('slow');
					$('#attendee_guests_'+eventid).val('');
					$('#attendee_text_'+eventid).val('');
					$('#attendee_guests_'+eventid).focus();
					// update the count
					$('#attendee_count_'+eventid).fadeOut(300, function(){
						$('#attendee_count_'+eventid).html('<strong>('+guestcount+')</strong>');
						$('#attendee_count_'+eventid).fadeIn(300);
					});
		        }
			);		
		});
	}
		
	
	window.openComments = function(activityid, actuserid, userid ){
		// fetch data
		$('#comment_'+activityid).html('');
		// check if the Comments div is open, if it is, close that first, then open the recommendations
		if ($('#recommendation_slide_state_'+activityid).val() == '1'){
			closeRecommendations(activityid);
		}
		// check if a hidden field is set to open for this comment group
		var html = '';
		if ($('#comment_slide_state_'+activityid).val() == '0'){
			html += '<div class="commentdiv enter"><div class="comment_entry">Say:<input id="comment_text_'+activityid+'" maxlength="140" style="width:300px;" type="text"/><button onclick="closeComments('+activityid+');return false;">Close</button><button onclick="saveComment('+activityid+', '+actuserid+', '+userid+');return false;">Add</button></div></div>';
			$('#comment_'+activityid).html(html);
			// open the div
			$('#comment_'+activityid).slideDown(300);
			$('#comment_text_'+activityid).focus();
			$('#comment_slide_state_'+activityid).val('1');
		} else {
			closeComments(activityid);
		}
	}
	
	window.reloadComments = function(activityid){
		// fade out comment_list_
		$('#comment_list_'+activityid).slideUp('slow', function(){
			$.getJSON('site.ajax.comment.php?getlatest=1&activityid=' + activityid,
		        function(data){
					var html = '';
					if (data.items.length > 0){
						$.each(data.items, function(i,item){
							html += '<li><img width="18px" height="18px" style="float:left;" src="'+item.user_avatar_path+'" alt="user_img"/><div class="comment"><a href="user.php?id='+item.userid+'">'+item.screenname+'</a>'+item.comment+'<strong>'+item.displaydate+'</strong></div></li>';
						});
					} else {
						html += '<li>Whoops, an error occurred.</div></li>';
					}
					$('#comment_list_'+activityid).html(html);
					$('#comment_list_'+activityid).slideDown('slow');
					$('#comment_text_'+activityid).val('');
					$('#comment_text_'+activityid).focus();
					// update the count
					$('#comment_count_'+activityid).fadeOut(300, function(){
						$('#comment_count_'+activityid).html('<strong>('+data.items.length+')</strong>');
						$('#comment_count_'+activityid).fadeIn(300);
					});
		        }
			);		
		});
	}
	
	window.deleteComment = function(commentid){
		var dataString = 'mode=DELETE&id='+commentid;
	  	$.ajax({  
			type: "POST",  
			url: "site.ajax.comment.php",  
			data: dataString,  
			success: function() {  
				// get the last comment and append to comment list
				$('#comment_li_'+commentid).fadeOut(300);
			}
	    });  
	}
	
	window.saveComment = function(activityid, actuserid, userid){
		// get userid, comment, activityid
		var comment = $('#comment_text_'+activityid).val();
		// save
		var dataString = 'mode=ADD&userid='+userid+'&comment='+urlencode(comment)+'&activityid='+ activityid +'&activityuserid='+actuserid;
	  	$.ajax({  
			type: "POST",  
			url: "site.ajax.comment.php",  
			data: dataString,  
			success: function(resp) {  
				// get the last comment and append to comment list
				// add this comment to DOM
				// close the div
				closeComments(activityid);
				$('#comment_list_'+activityid).append(resp);
				$('#comment_list_'+activityid).fadeIn(300);
			}
	    });  
	}

	function isNumeric(string){
		var numericExpression = /^[0-9]+$/;
		if(string.match(numericExpression)) {
			return true;		
		} else {
			return false;
		}
	}

	function urlencode (str) {
	    var hexStr = function (dec) {
	        return '%' + dec.toString(16).toUpperCase();
	    };

	    var ret = '',
	            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
	    str = (str+'').toString();

	    for (var i = 0, dl = str.length; i < dl; i++) {
	        var ch = str.charAt(i);
	        if (unreserved.test(ch)) {
	            ret += ch;
	        }
	        else {
	            var code = str.charCodeAt(i);
	            // Reserved assumed to be in UTF-8, as in PHP
	            if (code === 32) {
	                ret += '+'; // %20 in rawurlencode
	            }
	            else if (code < 128) { // 1 byte
	                ret += hexStr(code);
	            }
	            else if (code >= 128 && code < 2048) { // 2 bytes
	                ret += hexStr((code >> 6) | 0xC0);
	                ret += hexStr((code & 0x3F) | 0x80);
	            }
	            else if (code >= 2048 && code < 65536) { // 3 bytes
	                ret += hexStr((code >> 12) | 0xE0);
	                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
	                ret += hexStr((code & 0x3F) | 0x80);
	            }
	            else if (code >= 65536) { // 4 bytes
	                ret += hexStr((code >> 18) | 0xF0);
	                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
	                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
	                ret += hexStr((code & 0x3F) | 0x80);
	            }
	        }
	    }
	    return ret;
	}
	
	window.closeComments = function(activityid){
		$('#comment_'+activityid).slideUp("fast");
		$('#comment_slide_state_'+activityid).val('0');
	}
	
	
	window.openRecommendations = function(activityid, userid, recommendedtouserid){
		// fetch data
		$('#recommendation_'+activityid).html('');
		// check if the Comments div is open, if it is, close that first, then open the recommendations
		if ($('#comment_slide_state_'+activityid).val() == '1'){
			closeComments(activityid);
		}
		// check if a hidden field is set to open for this recommendation group
		if ($('#recommendation_slide_state_'+activityid).val() == '0'){
			$.getJSON('site.ajax.recommendation.php?activityid=' + activityid,
		        function(data){
					var html = '<div class="commentdiv"><ul id="recommendation_list_'+activityid+'">';
					if (data.items.length > 0){
						$.each(data.items, function(i,item){
							if (userid == item.userid){
								delhtml = '<a href="#" onclick="deleteRecommendation('+item.recommendationid+');return false;" class="delete">delete</a>';
							} else {
								delhtml = '';
							}
							html += '<li id="recommendation_li_'+item.recommendationid+'"><img width="18px" height="18px" style="float:left;" src="'+item.user_avatar_path+'" alt="user_img"/><div class="comment"><a href="user.php?id='+item.userid+'">'+item.screenname+'</a> thinks you should try a <a href="beer.php?beerid='+item.beerid+'" class="recommendation">'+item.recommendation+'</a><strong>'+item.displaydate+''+delhtml+'</strong></div></li>';
						});
					} else {
						if (userid > 0){
							html += '<li>Be the first to recommend a beer!</div></li>';
						} else {
							html += '<li>Register and can recommend a beer!</div></li>';
						}
					}
					html +=	'</ul></div>';
					if (userid > 0){
						html +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeRecommendations('+activityid+');return false;"><img src="assets/images/27close.png" alt="close"/></a><div class="comment_entry">Try:<input id="recommendation_text_'+activityid+'" maxlength="250" type="text"/><input id="recommendation_id_'+activityid+'" type="hidden"/><input id="recommendedtouserid_'+activityid+'" type="hidden" value="'+recommendedtouserid+'"/><button onclick="saveRecommendation('+activityid+','+userid+');return false;">Recommend</button></div></div>';
					} else {
						html +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeRecommendations('+activityid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					}
					$('#recommendation_'+activityid).html(html);
					recommendationSuggest(activityid);
					// open the div
					$('#recommendation_'+activityid).slideDown('slow');
					$('#recommendation_text_'+activityid).focus();
					$('#recommendation_slide_state_'+activityid).val('1');
		        }
			);		
		} else {
			closeRecommendations(activityid);
		}
	}
	
	window.reloadRecommendations = function(activityid){
		// fade out recommendation_list_
		$('#recommendation_list_'+activityid).slideUp('slow', function(){
			$.getJSON('site.ajax.recommendation.php?getlatest=1&activityid=' + activityid,
		        function(data){
					var html = '';
					if (data.items.length > 0){
						$.each(data.items, function(i,item){
							html += '<li><img width="18px" height="18px" style="float:left;" src="'+item.user_avatar_path+'" alt="user_img"/><div class="comment"><a href="user.php?id='+item.userid+'">'+item.screenname+'</a> Recommends a <a href="beer.php?beerid='+item.beerid+'" class="recommendation">'+item.recommendation+'</a><strong>'+item.displaydate+'</strong></div></li>';
						});
					} else {
						html += '<li>Whoops, an error occurred.</div></li>';
					}
					$('#recommendation_list_'+activityid).html(html);
					$('#recommendation_list_'+activityid).slideDown('slow');
					$('#recommendation_text_'+activityid).val('');
					$('#recommendation_text_'+activityid).focus();
					// update the count
					$('#recommendation_count_'+activityid).fadeOut(300, function(){
						$('#recommendation_count_'+activityid).html('<strong>('+data.items.length+')</strong>');
						$('#recommendation_count_'+activityid).fadeIn(300);
					});
		        }
			);		
		});
	}
	
	window.deleteRecommendation = function(recommendationid){
		var dataString = 'mode=DELETE&id='+recommendationid;
	  	$.ajax({  
			type: "POST",  
			url: "site.ajax.recommendation.php",  
			data: dataString,  
			success: function() {  
				// get the last recommendation and append to recommendation list
				$('#recommendation_li_'+recommendationid).fadeOut(300);
			}
	    });  
	}
	
	window.saveRecommendation = function(activityid, userid){
		// get userid, recommendation, activityid
		var beerid = $('#recommendation_id_'+activityid).val();
		var recommendedtouserid = $('#recommendedtouserid_'+activityid).val();
		// save
		if (beerid != ''){
			var dataString = 'mode=ADD&beerid='+beerid+'&userid='+userid+'&recommendedtouserid='+recommendedtouserid+'&activityid='+ activityid;
		  	$.ajax({  
				type: "POST",  
				url: "site.ajax.recommendation.php",  
				data: dataString,  
				success: function() {  
					// get the last recommendation and append to recommendation list
					reloadRecommendations(activityid);
				}
		    });  
		} else {
			alert('You can only recommend beers we know.')
			$('#recommendation_text_'+activityid).select();
			$('#recommendation_text_'+activityid).focus();
		}
	}
	
	window.closeRecommendations = function(activityid){
		$('#recommendation_'+activityid).slideUp("fast");
		$('#recommendation_slide_state_'+activityid).val('0');
	}	
	
	// open user followers

	window.getUserFollowers = function(userid){
		if ($('#user_followers_'+userid).html() == ''){
			$.getJSON('user.feed.php?mode=FOLLOWERS&userid=' + userid,
		        function(data){
					var list = '';
					$.each(data.items, function(i,item){
						list += '<div class="like"><a href="user.php?id='+item.userid+'" title="'+item.screennamefull+'" class="like_img">'+item.avatar+'</a><a href="user.php?id='+item.userid+'" title="'+item.screennamefull+'">' + item.screenname + '</a></div>'; 
					});
					list +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeUserFollowers('+userid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					$('#user_followers_'+userid).html(list);
					$('#user_followers_'+userid).slideDown('slow');
		        }
			);
		}
	}
	
	window.closeUserFollowers = function(userid){
		$('#user_followers_'+userid).slideUp('slow',function(){
			$('#user_followers_'+userid).html('');
		});		
	}

	
	// open user histogram
	window.getUserBeers = function(userid){
		if ($('#beer_like_'+userid).html() == ''){
			$.getJSON('user.feed.php?mode=USERLIKE&userid=' + userid,
		        function(data){
					var list = '';
					$.each(data.items, function(i,item){
						list += '<div class="like"><a href="beer.php?beerid='+item.beerid+'" title="'+item.beernamefull+'" class="like_img">'+item.avatar+'</a><a href="beer.php?beerid='+item.beerid+'" title="'+item.beernamefull+'">' + item.beername + '</a></div>'; 
					});
					list +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeUserBeers('+userid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					$('#beer_like_'+userid).html(list);
					$('#beer_like_'+userid).slideDown('slow');
		        }
			);
		}
	}
	
	window.closeUserBreweryFollowing = function(userid){
		$('#brewery_follow_'+userid).slideUp('slow',function(){
			$('#brewery_follow_'+userid).html('');
		});
	}	


	window.getUserBreweryFollowing = function(userid){
		if ($('#brewery_follow_'+userid).html() == ''){
			$.getJSON('user.feed.php?mode=BREWERYFOLLOW&userid=' + userid,
		        function(data){
					var list = '';
					$.each(data.items, function(i,item){
						list += '<div class="like"><a href="brewery.php?breweryid='+item.breweryid+'" title="'+item.brewerynamefull+'" class="like_img">'+item.avatar+'</a><a href="brewery.php?breweryid='+item.breweryid+'" title="'+item.brewerynamefull+'">' + item.breweryname + '</a></div>'; 
					});
					list +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeUserBreweryFollowing('+userid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					$('#brewery_follow_'+userid).html(list);
					$('#brewery_follow_'+userid).slideDown('slow');
		        }
			);
		}
	}
	
	window.closeUserBeers = function(userid){
		$('#beer_like_'+userid).slideUp('slow',function(){
			$('#beer_like_'+userid).html('');
		});
	}	

	
	window.getUserHistogram = function(userid){
		if ($('#user_histogram_'+userid).html() == ''){
			$.getJSON('user.feed.php?mode=HISTOGRAM&userid=' + userid,
		        function(data){
					var list = '';
					list += '<div id="userhistogram" style="margin-top:20px; margin-bottom:20px; margin-left:30px; width:200px; height:150px;"></div>'; 
					list +=	'<div class="commentdiv enter"><a href="#" style="float:right;" onclick="closeUserHistogram('+userid+');return false;"><img src="assets/images/27close.png" alt="close"/></a></div>';
					$('#user_histogram_'+userid).html(list);
					renderHistogram(data);
					$('#user_histogram_'+userid).slideDown('slow');
		        }
			);
		}
	}

	window.closeUserHistogram = function(userid){
		$('#user_histogram_'+userid).slideUp('slow',function(){
			$('#user_histogram_'+userid).html('');
		});
	}	
	
	function renderHistogram(line){
		plot3c = $.jqplot('userhistogram', [line], {
		    legend: {
		        show: true,
		        location: 'ne'
		    },
		    title: 'Rating Trend',
		    seriesDefaults: {
		        renderer: $.jqplot.BarRenderer,
		        rendererOptions: {
		            barPadding: 6,
		            barMargin: 20
		        }
		    },
		    series: [{
		        label: 'Ratings'
		    }],
		    axes: {
		        xaxis: {
		            renderer: $.jqplot.CategoryAxisRenderer,
		            ticks: ['1', '2', '3', '4', '5']
		        },
		        yaxis: {
             		min: 0,
					numberTicks: 5
				}
		    }
		});		
		
	}
	
})
