//Setup a PlanetTagger namespace
var PT = PT || {};


//Setup the share event
PT.share = function( e, options ){
	
	//ref the form
	var $form = $j(options.target);
	
	//ref the submit button
	var $submit = $form.find(':submit');
	
	//ref all non-hidden text fields
	var $inputs = $form.find('textarea,:text');
	
	//ref the comment area
	var $comment = $form.find('textarea.comment'); 
	
	//show the user that this submit button is processing
	SDNA.loading( $submit );
       
	//do a simple test to see if there is a comment
	if( (/\S/).test( $comment.val() ) && !$comment.hasClass('watermarked') ){						
		
		//unwatermark inputs
		$inputs.unWatermark();

		$form.append('<input type="hidden" name="context_url" value="' + window.location.href + '" />');

		//now serialize the data
		var formData = $form.serialize();
		
		//re watermark inputs
		$inputs.reWatermark();
		
		$j.post( 
			options.url,
			formData, 
			function(response){
				
				$form.trigger('submitted');
				
				//attach the target to the response
				$j.extend(response,options);
				
				//TODO: send success:false back from the server
				response.success = true;
				
				if( response.success == true ){
					
					PT.shared( response );
				
				//There was an error checking in	
				}else{
					
					Window.pop( response.errors, {error:true} );
					
				}
			},
			'json'
		);
	
	//if no comment, then 
	} else {
	
		//pop a message
		$content = $j('<div />')
					.append( '<h2>Whoopsy Daisy!</h2>' )
					.append( '<p><strong>Whoa there.</strong> We couldn\'t post your comment because it was blank.</p>' );
		
		//open the modal
		Window.pop( $content , {alert: true} );				
		
		
		SDNA.loaded( $submit );
	
	}
}

//Once the information has successfully been shared
PT.shared = function( response ){
	
	//blank the form
	var $form = $j(response.target);	
	
	//ref all non-hidden text fields and blank them out
	var $inputs = $form.find('textarea,:text').val('');
	
	//rewatermark inputs
	$inputs.filter('.watermark').reWatermark();
	
	//remove all files in the drawer
	$form.find('.cabinet .drawer .file').remove();	
	
	//Change the photo prompt back to "Add a photo"
	$form.find('.cabinet label.file span a').text('Add a photo?');	
	
	//submit button
	var $submit = $form.find(':submit');
	SDNA.loaded( $submit );
	
	//Now that the share has occured,
	//Publish a share event to all listeners
	SDNA.Event.publish('share',response);
	
}

//Share form submit handler
PT.share.submit = function( e ){

	//stop the form from submitting
	e.preventDefault();
	
	//Trigger the global like action
	SDNA.Event.trigger(
		'share',  
		{ 
			url: $j(this).attr('action'), 
			target: this 
		}
	);
	
}

//Share form click handler
PT.share.click = function( e ){
	
	var form = $j(this).parents('form.share').get(0);
	
	PT.share.submit.call( form, e);
	
	//stop the form from submitting
	e.preventDefault();

}

PT.share.updateActivity = function( e, response ){
	
    // if the share is actually a reply 
    // then run a different update handler
	if (response.reply) {
	    PT.share.reply.update(e, response);
	    return;
	}
	
	//find the activity stream to plug the content into
	var $activity = $j('#location_activity,#home_activity_all,#event_activity_all');
	
	//find the list items in the activty stream
	var $listItems = $activity.find('.item_list>li:not(.share)');
	
	//setup a ref to the new html 
	var $new = $j(response.html);
	
	//insert the new content into the DOM
	if( $listItems.length == 0 ){
		$activity.find('.item_list').prepend( $new );	
	} else {
		$listItems.eq(0).before( $new );
	}

	//remove empty items
	$listItems.filter('li.empty').remove();
	
	//make sure the right tab is shown
	$activity.showTab( {} );

}

PT.share.remember = function(e){
	
	if( !$j.cookie ){
		return false;
	}
	
	if( this.type.match('checkbox|radio') ){
	
		$j.cookie( this.name, this.checked, {path:'/', expires:365} );
		
	}else{
		
		$j.cookie( this.name, this.value, {path:'/', expires:365} );
		
	}
	
	return true;	
}

PT.share.recollect = function( $fields ){

	$fields.each(
		function(){
			if( this.type.match('checkbox|radio') ){
				if( $j.cookie( this.name ) != null ){
					this.checked = Boolean($j.cookie(this.name));
				} 
			}else{
				if( $j.cookie( this.name ) != null ){
					this.value = $j.cookie(this.name);
				} 
			}
		}
	);

}



PT.share.getShortUrl = function( url, callback ) {
    
    //get the short url to append to their comment
    $j.getJSON(
    	'/ajax/Shorten/Index.jsn', 
    	{ 
    		'url' : url
    	}, 
    	callback 
    );
    
}

PT.share.injectShortUrl = function( $form ){

	//attempt to find a short url
	var $input = $form.find(':input[name=shorturl]');
	
	if( $input.length < 1 ){
		
		PT.share.getShortUrl( 
			window.location.href, 
			function( data ){
				
				$form.prepend( $j('<input />').attr({type:'hidden',name:'shorturl'}).val( data.url) );
				
			}		
		);
	}		

}


PT.share.domChanged = function(e, response ){
		
	if( response.target ){
		PT.share.bind( response.target );
	}
}

//Binds a form with 
PT.share.bind = function( $dom ){
	
	//default the $dom in which to find to the document
	$dom = $j($dom) || $j(document);
	
	var $form = $dom.find('form.share');
	
	var $twitter = $form.find(':checkbox[name=share_social_twitter]');
	var $facebook = $form.find(':checkbox[name=share_social_facebook]'); 
	
	//bind the click function for facebook
	$facebook
		.unbind('click.share_facebook')
		.bind('click.share_facebook', PT.share.facebook.click );
	//$twitter
	//	.unbind('click.share_twitter')
	//	.bind('click.share_twitter', PT.share.twitter.click );
	
	//bind the click function
	$form.find(':submit').live('click.share', PT.share.click );
		
	//remember the settings
	var $checkboxes = $form.find(':checkbox');
	
	$checkboxes
		.unbind('click.remember')
		.bind('click.remember', PT.share.remember )
		.unbind('click.shorturl')
		.bind('click.shorturl', 
			function(){
				if( this.checked ){
					PT.share.injectShortUrl( $j(this).parents('form.share') );
				}
			} 
		);
		
	//recollect any settings remembered
	PT.share.recollect( $checkboxes );	
	
	//uncheck the checkbox if they cant post to facebook
	if( PT.currentUser && PT.currentUser.canPostToFacebook == false && $facebook.length > 0){
		$facebook.get(0).checked = false;
		$facebook.trigger('click.remember');	
	}
	
	//inject a short url if it is not there
	if( $twitter.length > 0 && $twitter.get(0).checked ){
		PT.share.injectShortUrl( $form );	
	}
	
	// setup binding for deleting comments
	$j('a.delete_comment').live('click.delete_comment', PT.share.remove.click);
	$j('a.delete_reply').live('click.delete_reply', PT.share.remove.click);
	
	$j('a.reply').live('click.reply', PT.share.reply.click);
	$j('a.show_all_replies').live('click.show_all_replies', PT.share.reply.showAll.click);
	
};

PT.share.facebook = {};

PT.share.facebook.connected = function( status, check){
	
	if( FB.Connect.get_status().result != FB.ConnectState.connected ){
		
		check.checked = true;
		$j(check).trigger('click.remember');
		SDNA.fb.onConnect();
			
	}
}

PT.share.facebook.connect = function(e, response ){
	if( response.error ){
		var $facebook = $j('#share_social_facebook');
		if( $facebook.length > 0 ){
			$facebook.get(0).checked = false;
			$facebook.trigger('click.remember');
		}
	}
	SDNA.Event.unsubscribe('facebook_connect', PT.share.facebook.connect );
}

PT.share.facebook.click = function(e){
	
	if( this.checked == true && FB ){
		
		if( PT.currentUser.hasFacebook == true && PT.currentUser.canPostToFacebook == true){
		
			return;
		
		}else	if( FB.Connect.get_status().result != FB.ConnectState.connected ){
			
			//prevent this checkbox from being clicked until they say yes
			this.checked = false;
			
			var check = this;
			FB.Connect.requireSession( 
				function( status ){
					PT.share.facebook.connected( status,  check ); 
				}
			);
		}else{
			SDNA.Event.subscribe('facebook_connect', PT.share.facebook.connect );
			SDNA.fb.onConnect();
		}
	}
}

/*
PT.share.twitter = {};

PT.share.twitter.click = function(e){
	
	if( this.checked == true ){
		
		window.open('/Twitter/Login','twitter','location=0,status=0,scrollbars=0,width=800,height=400');
			
	}
}
*/

PT.share.photoUploaded = function( e, response ){

    if( response.response ){
        
        var $input = $j(response.target);
        var $form = $input.parents('form.share').eq(0);
        
        if( $form.length > 0 ){
            
            
            //change the label prompt to say "Change photo"
            var $label = $input.parent();
            $label.find('span a,span span').text('Change photo?');      
        
        }
    }
};

PT.share.photoAdded = function( e, response ){
	
	//get the target to which the photo was added
	var $file = $j(response.target);
	
	//create a input for the caption
	var $captionInput = $j('<input type="text" name="caption" title="Optional photo caption" class="watermark caption" />');
	
	//now add that input to the file
	$file.prepend( $captionInput );
	
	//watermark it
	SDNA.forms.bindWatermarks( $file );
};

PT.share.photoRemoved = function( e, response ){
	
	if( response && response.input ){
	
		var $input = $j(response.input);
		
		var $form = $input.parents('form.share').eq(0);
		
		if( $form.length > 0 ){
			
			var $label = $input.parent();
			$label.find('span a,span span').text('Add a photo?');						
		
		}
	}	
};

/**
 * Remove a comment or a reply (remember, a reply IS a comment)
 */
PT.share.remove = function (e, options) {

    var target = options.target;
    
    SDNA.loading(target);
    
    if (confirm('Are you sure?')) {
        // post the request to delete comment by comment_id
        $j.post(
            options.url,
            { comment_id : options.comment_id },
            /**
             * Response callback
             * If successful, reload the parent tab to reflect the deleted comment
             * otherwise display warning message
             */
            function (response) {
                if (response.success) {
                    // hide replies and comments, then remove from DOM
                    if (options.reply) {
                        var reply = $j(target).getContainer('reply');
                        reply.hide(300, function () { reply.remove(); });
                    } else {
                        var comment = $j(target).getContainer('comment');
                        comment.hide(300, function () { comment.remove(); });
                    }
                } else {
                    alert(response.message);
                }
                SDNA.loaded(target);
            },
            'json'
        )
    } else {
        SDNA.loaded(target);
    }
};

/**
 * Handle a click event on 'Delete' to fire the handler
 */
PT.share.remove.click = function (event) {
    event.preventDefault();
    
    SDNA.Event.trigger(
        'delete_comment',  
        { 
            url: $j(this).attr('data-href'), 
            target: this,
            comment_id : $j(this).attr('data-comment-id'),
            reply : $j(this).hasClass('delete_reply')
        }
    );
};

/**
 * Replies to comments (other entities)
 */
PT.share.reply = {};

/**
 * Handle the click event on 'Reply' to show the reply form
 */
PT.share.reply.click = function (event) {
    
    // grab the container for this reply link (the comment itself)
    var container = $j(this).getContainer();
    // grab the hidden form
    var form = container.find('div.reply_form');
    // show it
    form.show(300);
    
    // setup handling of form hiding if the user clicks outside of it
    var callback = function (event) {
        // grab the dom element that was clicked
        var target = $j(event.target);
        // only react if the user has clicked *outside* of the textarea
        // AND it's not the reply link itself OR the show/hide link
        // OR the rotating FSM widget link (since this is automated we don't
        // want the automatic rotation to cancel a reply form)
        if (target.length && !target.is('textarea.comment') && !target.is('a.reply') && !target.is('a.show_all_replies') && !target.is('a.refresh_promo_message')) { 
            
            if (target.is('button')) {
                // if the target is the save button, then only hide *it's* reply form
                target.getContainer().find('div.reply_form').hide();
            } else {
                // otherwise hide all reply forms immediately
                $j('div.reply_form').hide(300);
            }
            return true; // allow propogation of click event so we don't conflict with other click handlers
        }
    };
    // setup a general click event on the body
    $j('body').live('click.toggle_replies', callback);
};

PT.share.reply.showAll = {};

/**
 * Handle the click event on 'X replies' which toggles showing/hiding the replies
 */
PT.share.reply.showAll.click = function (event) {
    var $this = $j(this);
    // get the collection of replies (list items)
    var listItems = $this.parents('div.replies').find('li');
    // get the current text of the "Show/Hide all X replies" link
    var text = $this.text();
    // if all replies are visible then then hide
    // otherwise show. in either case, update the text View/Hide
    if (listItems.filter(':visible').length === listItems.length) {
        listItems.hide(300);
        $this.text(text.replace('Hide', 'View'));
    } else {
        listItems.show(300);
        $this.text(text.replace('View', 'Hide'));
    }
};

/**
 * Update the DOM with the new reply
 * @see PT.share.updateActivity (above) which delegates 
 *      the share event to this handler for replies
 */
PT.share.reply.update = function (event, response) {
    // get the entity being replied to from the response
    var entityId = response.entity_id; // notice, we can reply to more than just comments! hence, "entity"
    // find the block of replies for this entity
    var entity = $j('div.tabs_content div:visible div.replies[data-entity-id=' + entityId + ']').eq(0);
    // get the link for showing replies so we can update the count
    var countLink = entity.find('a.show_all_replies');
    // retreive the count
    var currentCount = parseInt(countLink.find('span').text());
    // increment it
    currentCount++;
    // replace with the new count
    countLink.find('span').text(currentCount);
    
    var newReply = $j(response.html);
    // append the new reply into the list
    entity.find('ul').append(newReply);
    // reveal it
    newReply.show(300);
    
};

//Create the share event
SDNA.Event.create('share', PT.share );

//Subscribe to a share event so that the activity stream can be updated
SDNA.Event.subscribe('share', PT.share.updateActivity );

//Subscribe to a before dom changed event so that the share module can be bound
SDNA.Event.subscribe('tab_loaded', PT.share.domChanged );

//Subscribe to uploaded events to see if any pictures are uploaded
SDNA.Event.subscribe('uploaded', PT.share.photoUploaded, {within:"form.share"} );

//Subscribe to uploaded file added events 
SDNA.Event.subscribe('uploaded_file_added', PT.share.photoAdded, {within:"form.share"} );

//Subscribe to uploaded_file_removed events to see if any pictures are uploaded, then removed
SDNA.Event.subscribe('uploaded_file_removed', PT.share.photoRemoved, {within:"form.share"} );

SDNA.Event.create('delete_comment', PT.share.remove);