///////////////////////
//Global Variables
//////////////////////
/**User's current longitude and latitude**/
var longitude=0;
var latitude=0;
var accuracy=0;
/**geolocation polling, used to end polling on logout**/
var watchId;
var numEvents=10;
//////////////////////////////////////////////////////
//Global Methods
///////////////////////////////////////////////////////
                                  
//initialzeds navigator
function initiate_geolocation() {
            watchId=navigator.geolocation.watchPosition(handle_geolocation_query,handle_errors,{enableHighAccuracy:true, maximumAge:32000, timeout:27000});
        }
		//outputs location errors
        function handle_errors(error)
        {
            switch(error.code)
            {
                case error.PERMISSION_DENIED: showFailureMessage("User did not share geolocation data");
                break;

                case error.POSITION_UNAVAILABLE: showNotificationMessage("Could not detect your current position");
                break;

                case error.TIMEOUT: /*showNotificationMessage("retrieving position timed out");*/
                break;

                default: //alert("unknown error");
                break;
            }
        }
		//sets location
        function handle_geolocation_query(position){
           longitude=position.coords.longitude;
		   latitude=position.coords.latitude;
		   accuracy=position.coords.accuracy;
        }
		
		
		/**
		 * Great date string in form of Wed Jan. 3, 2003 7:12 am
		 * @param {Object} string
		 */
		function fullDateFormat(stringDate){
			var dateToParse=new Date();
			if(typeof stringDate !== 'undefined' && stringDate)
				dateToParse=stringDate;
			return Date.parse(dateToParse).toString("ddd. MMM. d, yyyy h:mm tt");
		}
		/**
		 * Creates timestamp from formatted date
		 * @param {Object} string
		 */
		function timestampFormat(string){
			return Date.parse(string).toString("yyyy-MM-dd HH:mm:00");
		}
		/**
		 * Append whays to list
		 * @param {Object} ul
		 * @param {Object} data
		 */
		function appendWhays(ul, data){
			var htmlItem="";
			if(data.length<1)
				htmlItem='<label class="secondary-text">No Current WHAYs</label>';
			$.each(data, function(i, item){
				htmlItem+="<li><div class='whay'>";
				htmlItem+="<a href='event.php?id="+item.id+"'>"+item.name+"</a><br />";
				htmlItem+= "<abbr class='timeago secondary-text' title='"+fullDateFormat(item.start_ts)+"'>"+$.timeago(item.start_ts)+"</abbr>";
				htmlItem+="</div></li>";
			});
			ul.html(htmlItem);
			$(".whay abbr.timeago").timeago();
		}
		/**
		 * Appends user whay 
		 * @param {Object} id
		 * @param {Object} text
		 * @param {Object} container
		 */	
		function appendUserWhay(id,text,container){
			var currentWhay=$(".current-whay")
			if(currentWhay)
				currentWhay.remove();
			var htmlItem="<div class='current-whay'>";
			htmlItem+="<a href='event.php?id="+id+"'>"+text+"</a><br />";
			var date= new Date();
			htmlItem+= "<abbr class='timeago secondary-text' title='"+fullDateFormat(date)+"'>"+$.timeago(date)+"</abbr>";
			htmlItem+="<button class='end-whay float-right delete-button' title='End Whay' data-id='"+id+"'></button>";
			htmlItem+="</div>";
			container.after(htmlItem);
			$(".current-whay abbr.timeago").timeago();
		}
		/**
		 * Append comments to list
		 * @param {Object} ul
		 * @param {Object} data
		 */
		function appendComments(div, data){
			var htmlItem="";
			if (data.length < 1) {
				htmlItem = "No Comments";
				div.html(htmlItem);
			}
			else {
				div.html("");
				$.each(data, function(i, comment){
					appendComment(div, comment);
					
				});
			}
			
		}
	/**
		 * Append comment list
		 * @param {Object} div
		 * @param {Object} data
		 */
		function appendComment(div, comment){
			var htmlItem="";
					htmlItem+="<div class='comment'>";
					var profileImageUrl="images/profiles/default/placeholder_smallest.jpg";
					if(typeof comment.profile_pic_url !== 'undefined' && comment.profile_pic_url){
							profileImageUrl=comment.profile_pic_url+"_smallest.jpg";							
					}
					var linkId=comment.user_id;
					if(typeof comment.username !== 'undefined' && comment.username)
						linkId=comment.username;
					htmlItem+="<a class='watch-list' href='user.php?id="+linkId+"'><img src='"+profileImageUrl+"' title='"+comment.first_name+" "+comment.last_name+"'></img></a>";
					htmlItem+="<a href='user.php?id='"+linkId+"'>"+comment.first_name+" "+comment.last_name+"</a>";
					//for delete comment, it assumes user id is in content div data
					if(comment.user_id==$('#data').data('id')){//if comment creator provide delete button
						htmlItem+= "<button class='delete-comment float-right delete-button' title='Delete Comment' data-id='"+comment.id+"'></button>";
					}
					htmlItem+="<br />";
					htmlItem+=comment.comment+"<br />";
					htmlItem+= " <abbr class='timeago secondary-text' title='"+fullDateFormat(comment.timestamp)+"'>"+$.timeago(comment.timestamp)+"</abbr>";
					htmlItem+="<hr />";					
					htmlItem+="</div>";

			
			div.append(htmlItem);
			$(".comment abbr.timeago").timeago();
		}
		/**
		 * Shows message generic method. Used by showSuccessMessage, showFailureMessage, showNotificationMessage
		 * @param {String} text text to display. Can be array of text
		 * @param {String} className css class name
		 * @param {String} position 'top'|'bottom'
		 * @param {Object} elem
		 */
		function showMessage(text,className,position,elem){
			var message;
			var body=$('body');
			if(text instanceof Array){
				message=text;
			}else{
				message=[text];
			}
			if(typeof elem !== 'undefined' && elem){
							body=elem;							
			}
			body.showMessage({'thisMessage':message,
										className:className,
										opacity: 95,
										autoClose: true,
										closeText:'close me',
										position:position										
			});
		}
		/**
		 * Shows success message
		 * @param {Object} text
		 * @param {Object} elem
		 */
		function showSuccessMessage(text,elem){
			showMessage(text,'success', 'top',elem);
		}
		/**
		 * SHows notification message
		 * @param {Object} text
		 * @param {Object} elem
		 */
		function showNotificationMessage(text,elem){
			showMessage(text,'notification', 'bottom',elem);
		}
		/**
		 * Shows notification message
		 * @param {Object} text
		 * @param {Object} elem
		 */
		function showFailureMessage(text,elem){
			showMessage(text,'fail','top',elem);
		}
//////////////
//on dom ready constructor
///////////////////
$(function() {//Equivalent to DOM.READY
		//get location if html5
        if(!!navigator.geolocation)
			initiate_geolocation();
        
		//Timeago on all time fields
		jQuery.timeago.settings.allowFuture = true;
		$("abbr.timeago").timeago();

		 //all text areas are elastic
       $('textarea').elastic();
	   
	   //add click to edit to all boxes
		$(".clickEdit").click2Edit();
		/********************************
		 * Comments Setup
		 ******************************
		 */
		$('.comment-box').advanceTextarea({width:'100%',
									buttonClass: "qc-button blue",
									submitButton:"Comment",
									helpText: "Enter Comment",
									onSubmit: function(textarea, div){
										//alert("submit comment "+textarea.data('id'));
										var text=textarea.val();
										ajaxComment({eid:textarea.data('id'),
													comment:text},
													function(item){
														//create comment and insert
														if (item.success) {
															appendComment(div.prev('.comments-container'),item.output);
															var numComments = div.prev('.comments-container').parents(".event").find('.number-comments');
															numComments.text(parseInt(numComments.text())+1);
														}else{
															showFailureMessage(item.output);
														}
													});
										}
									});
		
       /*******************************************
		 * Whay Setup
		 * ****************************************
		 */
		//whay input
		$('#whayTextarea').advanceTextarea({width:'100%',
									buttonClass:"qc-button blue",
									submitButton:"Post WHAY",
									maxSize: 160,
									helpText: "What's Happening Around You?",
									onSubmit: function(textarea, container){
												var text=textarea.val();
												ajaxCreateWhay({whay:text, longitude:longitude, latitude:latitude},function(item){
													if(item.success){
														appendUserWhay(item.output.id,text,container);
													}else{
															showFailureMessage(item.output);
													}
												});
											}
									});
		
			
		//scrolling whay
		$('#currentWhays').vTicker({updateCallback: function(ul){
														ajaxWhays({},function(item){
															if(item.success){
																appendWhays(ul,item.output);
															}else{
																showFailureMessage(item.output);
															}
														});
														
													},
									updateInterval:180000
		 							});
	   
	   /**Invite box**/
	  var tempInviteText="Friend's email";
	  $('.invite-textbox').placeholderText({replacementText:tempInviteText});
	  $(".invite-textbox").live('keyup',function(event){
	  	 var textbox=$(this); 
		 if (event.keyCode == 13) {
		 	var email = textbox.val();
		    var AtPos = email.indexOf("@");
			var StopPos = email.lastIndexOf(".");
			if(email != "" && (AtPos != -1 || StopPos != -1) && StopPos > AtPos && (StopPos - AtPos != 1)){//contains @ and perioud
				ajaxInviteUser(textbox.val(),function(response){
					if(response.success){
						showSuccessMessage("Friend has been invited");
						textbox.val("");
					}else{
						showFailureMessage(response.output);
					}
				});
			}else{
				showFailureMessage("Please provide a valid email");
			}
		  }
	  });
	    /**Button link**/
		//saving the user
		$('#user-update').submit(function(e){
			e.preventDefault();
			ajaxUpdateUser($(this).serialize(),function(item){
					if(item.success){
						showSuccessMessage(item.output);
					}else{
						showFailureMessage(item.output);
					}
				});
		});
				
		$(".more-detail").live('click', function(e){
			e.preventDefault();
			if($(this).text()=="More Details"){
				$(this).text("Hide Details");
			}else if($(this).text()=="Hide Details"){
				$(this).text("More Details");
			}
			$(this).next(".more-detail-content").slideToggle(500);
			///.next().find(".more-detail-content")
		});
		
		
		
		$(".get-comments").live('click', function(e){
			e.preventDefault();
			var button= $(this);
			var eventId=button.data('id');
			var parentDiv=button.parents(".comments-container");
			parentDiv.html("Loading...");
			ajaxGetComments(eventId, function(item){
				if (item.success) {
					appendComments(parentDiv, item.output);
				}else{
					showFailureMessage(item.output);
				}
			});
			//alert(eventId);
		});
       
	//whay end button hover	
	 	$(".current-whay").live("hover", function(){$(this).children(".end-whay").toggle();});
		$(".end-whay").live('click', function(e){
	   		var button= $(this);
           var eventId=button.data('id');
			//alert(eventId);
			ajaxEndWhay(eventId,function(item){
				if (item.success) {
					var parentDiv=button.parents(".current-whay");
					parentDiv.slideUp("normal", function() { parentDiv.remove(); } );
					showSuccessMessage("WHAY ended.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
		$(".follow").live('click', function(e){
			var button= $(this);
            var userId=button.data('uid');
			button.text('Requesting...');
			button.attr('disabled', 'disabled');
			//alert(userId);
			ajaxRequestConnection(userId,function(item){
				button.removeAttr('disabled');
				if (item.success) {
					button.text("Cancel Request");
					button.addClass('unfollow');
					button.removeClass('follow');
					showSuccessMessage("Track request has been sent.");
				}else{
					showFailureMessage(item.output);
					button.text('Track');
				}
			});
			
        });
		
		$(".accept").live('click', function(e){
			var button= $(this);
			var requestId=button.data('id');
			//alert(requestId);
			ajaxAcceptConnection(requestId,function(item){
				if (item.success) {
					var parentDiv=button.parents(".request");
					parentDiv.slideUp("normal", function() { parentDiv.remove(); } );
					showSuccessMessage("Track request accepted.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
    	
		 $(".unfollow").live('click', function(e){
            var button= $(this);
			var userId=button.data('uid');
			//alert(userId);
			ajaxRemoveConnection(userId,function(item){
				if (item.success) {
					button.text("Track");
					button.addClass('follow');
					button.removeClass('unfollow');
					showSuccessMessage("No longer following user.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
		/* $(".unblock").live('click', function(e){
            var button= $(this);
			var userId=button.data('uid');
			//alert(userId);
			ajaxDeclineConnection(userId,function(){
				if (item.success) {
					button.fadeOut("normal", function(item){ $(this).remove();});
					showSuccessMessage("User has been unblocked.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });*/
		
		 $(".reject").live('click', function(e){
			var button= $(this);
			var requestId=button.data('id');
			//alert(requestId);
			ajaxDeclineConnection(requestId,function(item){
				if (item.success) {
					var parentDiv=button.parents(".request");
					parentDiv.slideUp("normal", function() { parentDiv.remove(); } );
					showSuccessMessage("Track request has been rejected.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
	
		$(".interest-in").live('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxInterestInEvent(eventId,function(item){
				if (item.success) {
					button.text(parseInt(button.text())+1);
					button.attr("title","Click to remove interest");
					button.addClass('uninterest-in');
					button.removeClass('interest-in');
					showSuccessMessage("Event has been added to your agenda.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
    	
		$(".uninterest-in").live('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxUninterestInEvent(eventId,function(item){
				if (item.success) {
					button.text(parseInt(button.text())-1);
					button.attr("title","Click to show interest");
					button.addClass('interest-in');
					button.removeClass('uninterest-in');
					showSuccessMessage("Event has been removed from your agenda.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
		$(".check-in").live('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxCheckin(eventId,function(item){
				if (item.success) {
					button.text("Check-out");
					button.addClass('check-out');
					button.removeClass('check-in');
					showSuccessMessage("You have checked in.");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
		$(".check-out").live('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxCheckout(eventId,function(item){
				if (item.success) {
					button.text("Check-in");
					button.addClass('check-in');
					button.removeClass('check-out');
					showSuccessMessage("You have checked out.");
				}else {
					showFailureMessage(item.output);
				}
			});
        });
		$(".yes-go").bind('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxWannagoYes(eventId,function(item){
				if (item.success) {
					$('.watch-list.current-user').appendTo($('.wannago-in'));
					showSuccessMessage("Your friend has been notified, you are going");
				}else{
					showFailureMessage(item.output);
				}
			});
        });
		
		$(".no-go").bind('click', function(e){
            var button= $(this);
			var eventId=button.data('id');
			//alert(eventId);
			ajaxWannagoNo(eventId,function(item){
				if (item.success) {
					$('.watch-list.current-user').appendTo($('.wannago-out'));
					showSuccessMessage("Your friend has been notified, you are not going");
				}else {
					showFailureMessage(item.output);
				}
			});
        });
        ///logout
         $(".logout").click(function(e){
				e.preventDefault();
                ajaxLogout(function(data){
                                    if(data.success){
                                        if(!!navigator.geolocation)
											navigator.geolocation.clearWatch(watchId);              
                                        window.location="index.php";
                                    }
                             });
            });
		/**************
	     *Deletion Buttons that require dialog popups for confirmation. Must have the dialog created and html and hidden on the page 
	     */
		//Comment delete button hide and show
		$(".comment").live("hover", function(){$(this).children(".delete-comment").toggle();});
		
		$(".delete-comment").live('click', function(e){
            var button= $(this);
			var commentId=button.data('id');
			var confirm=$( "#confirm-comment-delete" );
				confirm.dialog({
				resizable: false,
				height:200,
				width:500,
				modal: true,
				buttons: {
					"Delete comment": function() {
						$( this ).dialog( "close" );
						ajaxDeleteComment(commentId,function(item){
							if (item.success) {
								var parentDiv=button.parents(".comment");
								parentDiv.slideUp("normal", function() { parentDiv.remove(); } );
								var numComments = parentDiv.parents('.event').find('.number-comments');
								numComments.text(parseInt(numComments.text())-1);
							}else{
								showFailureMessage(item.output);
							}
						});
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			confirm.dialog( "open" );	
			
        });
		$(".delete-pic").bind('click', function(e){
            e.preventDefault();
			var confirm=$( "#confirm-picture-delete" );
				confirm.dialog({
				resizable: false,
				height:200,
				width:500,
				modal: true,
				buttons: {
					"Delete picture": function() {
						$( this ).dialog( "close" );
						$('input[name=profile_pic_url]').val("null")
						$('img.profile-pic-normal').attr('src',"images/profiles/default/placeholder_normal.jpg");
						showSuccessMessage("To confirm change, please click update");
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			confirm.dialog( "open" );		
			
        });
	   $(".delete-event").live('click', function(e){
			var button= $(this);
           var eventId=button.data('id');
			var confirm=$( "#confirm-event-delete" );
				confirm.dialog({
				resizable: false,
				height:200,
				width:500,
				modal: true,
				buttons: {
					"Delete event": function() {
						$( this ).dialog( "close" );
						ajaxDeleteEvent(eventId,function(item){
							if (item.success) {
								showSuccessMessage("Event Deleted");
								window.location = "calendar.php";								
							}else{
								showFailureMessage(item.output);
							}
						});
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			confirm.dialog( "open" );
			
        });
		$(".delete-user").bind('click', function(e){
	   			e.preventDefault();
				var confirm=$( "#confirm-acccout-delete" );
				confirm.dialog({
				resizable: false,
				height:200,
				width:500,
				modal: true,
				buttons: {
					"Delete account": function() {
						$( this ).dialog( "close" );
						ajaxDeleteUser(function(item){
							if (item.success) {
								ajaxLogout(function(data){
			                                    if(data.success){
			                                        navigator.geolocation.clearWatch(watchId);              
			                                        window.location="index.php";
													showSuccessMessage("Your account has been deleted. If you would like to reactivate it please sign with your email and password.")
			                                    }
			                             });
							}else{
								showFailureMessage(item.output);
							}
						});
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			confirm.dialog( "open" );
        });
		
		/*$(".block").live('click', function(e){
			var button= $(this);
			var requestId=button.data('id');
			var confirm=$( "#confirm-block" );
				confirm.dialog({
				resizable: false,
				height:200,
				width:500,
				modal: true,
				buttons: {
					"Block user": function() {
						$( this ).dialog( "close" );
						ajaxBlockConnection(requestId,function(item){
							if (item.success) {
								var parentDiv=button.parents(".request");
								parentDiv.slideUp("normal", function() { parentDiv.remove(); } );
							}else{
								showFailureMessage(item.output);
							}
						});
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			confirm.dialog( "open" );
			
        });*/
                        
});

