// set these in the global scope so we can use them elsewhere

var bindUpdateDelete = {};
var bindUpdateEdit = {};

jQuery(document).ready(function(jQuery){

	// start character counter
	jQuery('#quickUpdateText').charCounter(140, {
		container: '#updateTextCounter'
	});

	// validate the New Venue form when it is submitted.  If valid, submit form via AJAX.
	jQuery('#quickUpdateForm').validate({
		errorClass: 'validationError',
		rules: {
			update_text: 'required'
		},
		messages: {
			update_text: 'Please enter some text.'
		},
		submitHandler: function(form) {
			//alert('here');		
			var options = {
	        	//dataType: 'json', //for some reason, passig the datatpye is killing it.
	        	success: processJson			
	        };
			
			jQuery('#update_post_button').hide();
			jQuery('#update_ajax_image').show();

			jQuery(form).ajaxSubmit(options);
			return false; // so form doesn't submit in browser in IE
		}
	});
	//return;
	// After submitting new venue, close thickbox and update display as needed
	function processJson(data)  {
		//alert(data);
	    //alert(data.message);
	    //alert(data.content);
		//alert(data.attempts);
		if(data.attempts){
			for(var i in data.attempts){
				//alert(data.attempts[i]);
				//check if thing meant to post did or not...
			}
		}
	    
	    jQuery('#quickUpdateText').val(''); // empty out update post box

	    
	    jQuery('#quickUpdatesStatus').html(data.message);  	
    	if ($('#facecheck').length) { //only run in on facebook page
    		//alert("here");
    		jQuery('#quickUpdatesStatus').delay(7200).fadeOut('fast', function() {
    			//setTimeout(LoadSite('facebook'),9000); //delay further to make sure it's up there before loading
    			LoadSite('facebook');
    			resetStatus();
    		});
    	}else if ($('#trends_container').length) { //only run in on twitter? page
    		//alert("here");
    		jQuery('#quickUpdatesStatus').delay(3600).fadeOut('fast', function() {
    			LoadSite('twitter');
    			resetStatus();
    		});
    	}else if($('#quickUpdates').length){ //only on updates page
			LoadSite('home');
			resetStatus();
    	    //jQuery('#quickUpdates').html(data.content);
    	}else{
    		//alert("there");
    		//if not fb fade out "updating" faster
    		jQuery('#quickUpdatesStatus').fadeOut('slow');
    		resetStatus();
    	}
		jQuery('#update_post_button').show();
		jQuery('#update_ajax_image').hide();

	    //not showing edit entry now
	    //bindUpdateDelete(); // bind delete button to new update
	    //bindUpdateEdit(); // bind edit button to new update


	}

	// callback function that executes after status message fades out
	function resetStatus() {
		jQuery('#quickUpdatesStatus').html('').fadeIn(1); // clear out current contents and fade it in
		jQuery('#update_ajax_image').hide();
	}


	// bind delete button for each update
	bindUpdateDelete = function() {
		jQuery('.deleteUpdateButton').each(
				
			// For each delete button, bind the onclick behavior.
			function() {

				// Bind the onclick event
				jQuery(this).bind (
					'click',
					function(){

						if (confirmSubmit('Are you sure you want to delete this update?\nThis cannot be undone!')) {

							var theId = jQuery(this).attr('id'); // get ID of clicked element, eg: delete123
							var update_id = theId.substr(6); // strip off the user ID from the element ID, eg: 123

							jQuery('#quickUpdate' + update_id).hide().load('/ajax/deleteQuickUpdate.php?update_id=' + update_id, function() {
								jQuery(this).fadeIn('slow').fadeOut(2500);
								if (typeof(pageTracker) !== 'undefined') {
									pageTracker._trackPageview('/ajax/deleteQuickUpdate.php'); // track this AJAX call in google analytics
								}
							});

							return false; // return false so the link doesn't actually click anywhere

						} else {
							return false;
						}
					}
				);
			}
		);
	};

	// bind edit button for each update
	bindUpdateEdit = function() {
		jQuery('.editUpdateButton').each(

			// For each delete button, bind the onclick behavior.
			function() {

				// Bind the onclick event
				jQuery(this).bind (
					'click',
					function(){

						var theId = jQuery(this).attr('id'); // get ID of clicked element, eg: delete123
						var update_id = theId.substr(4); // strip off the user ID from the element ID, eg: 123
						
						jQuery('#quickUpdate' + update_id).hide().load('/ajax/editQuickUpdate.php?update_id=' + update_id, function() {
							// start character counter
							jQuery('#quickUpdateTextEdit').charCounter(150, {
								container: '#updateTextCounterEdit'
							});

							jQuery(this).fadeIn('fast', function(){
								if (typeof(pageTracker) !== 'undefined') {
									pageTracker._trackPageview('/ajax/editQuickUpdate.php'); // track this AJAX call in google analytics
								}
								bindUpdateEditSubmit(); // form processing
								bindEditCancel();						
								
								
							}); // show the edit form (slow fadein)

						});

						return false; // return false so the link doesn't actually click anywhere

					}
				);
			}
		);
	};

	// bind onclick events on initial pageload
	bindUpdateDelete();
	bindUpdateEdit();


//## Submit Edit Update #####################################################################################################

	// Form handler for submitting votes.
	var bindUpdateEditSubmit = function() {

		var update_id = jQuery('input[name=update_id]').val(); // get id of current update



		var options = {
        	url:			'/ajax/editQuickUpdate.php',	// where to submit the form
        	target:			'#quickUpdate' + update_id, 	// target element(s) to be updated with server response
        	success:       	updateSubmitEditSuccess  		// post-submit callback
        };

        // bind form using 'ajaxForm'
	    jQuery('#editUpdateForm').submit(function() {
        	// inside event callbacks 'this' is the DOM element so we first
        	// wrap it in a jQuery object and then invoke ajaxSubmit
        	jQuery(this).ajaxSubmit(options);

        	// !!! Important !!!
        	// always return false to prevent standard browser submit and page navigation
        	return false;
    	});
	};

	// post-submit callback.
	// After submitting update, hide the update form
	function updateSubmitEditSuccess()  {

	    var update_id = jQuery('input[name=update_id]').val(); // get id of current update

	    jQuery('#quickUpdate' + update_id).hide().fadeIn('slow');
	    bindUpdateDelete(); // re-bind delete buttons so that new comment can be deleted.
	    bindUpdateEdit();	// re-bind edit buttons so that comment can be edited.
	    jQuery('#quickUpdatesEditStatus').fadeOut(2500);
	    //jQuery('#quickUpdatesEditStatus').remove();
	}

	// function to handle user cancelling the editing of an update
	var bindEditCancel = function() {
		jQuery('#cancelButton').bind (
			'click',
			function(){

				var update_id = jQuery('#update_id').val(); // get id of current update

				jQuery('#quickUpdate' + update_id).hide().load('/ajax/printQuickUpdate.php?update_id=' + update_id, function() {
					bindUpdateDelete();
					bindUpdateEdit();
					jQuery(this).fadeIn('slow');
					if (typeof(pageTracker) !== 'undefined') {
						pageTracker._trackPageview('/ajax/printQuickUpdate.php'); // track this AJAX call in google analytics
					}
				});
			}
		);
	}

//## END Submit Edit Update #####################################################################################################


});


function getUpdatesCountsLatest(siteurl) {

		url = siteurl+'ajax/getUpdatesCounts.php';
		jQuery.post(url, function(data) {

			var arrResult = data.split("#~~#");
			if(arrResult[0] > 0) {
				jQuery("#tw_link").html("<span>"+arrResult[0]+"</span>").show();
			}
			if(arrResult[1] > 0) {
				jQuery("#face_link").html("<span>"+arrResult[1]+"</span>").show();
			}
			if(arrResult[2] > 0) {
				jQuery("#myspace_link").html("<span>"+arrResult[2]+"</span>").show();
			}
			if(arrResult[3] > 0) {
				jQuery("#news_link").html("<span>"+arrResult[3]+"</span>").show();
			}

		});
		jQuery('#notificationBar').ajaxError(function() {
			showNotification("Grrr! bompa is not available at the moment. Please try again later.");
		});


}


