/**
 * Editable spots
 * Depends on jQuery and our custom String Utils library
 */

(function ($) {
	
	var data = {};
	var defaultTextBoxWidth  = 220;
	var defaultTextBoxHeight = 400;
	var defaultText = StringUtils.EMPTY;
	var permissionLevel = StringUtils.EMPTY; 
	var path = StringUtils.EMPTY;
	
	$.fn.initeditablespots	= function (spots, permLevel, url){
		
		if(StringUtils.isEmpty(permLevel) || StringUtils.isEmpty(url)) {
			throw {
				name : "InitializeException",
				message: "Please provide permLevel and URL parameters"
			}
		}
		
		path = url;
		permissionLevel = permLevel;
		for (var key in spots) {
			
			if(!spots[key]['w']){
				spots[key]['w'] = defaultTextBoxWidth;
			}
			if(!spots[key]['h']){
				spots[key]['h'] = defaultTextBoxHeight;
			}

			data[key] = {'old': spots[key]['b'], 'new': '', w: spots[key]['w'], h: spots[key]['h']};
			jQuery('#'+ key +'-EditButton').click( function(){ edit( this.id.substr(0, this.id.indexOf('-')) ) });
		}
	}

		 
	function edit(spot) {	
		
		jQuery('#'+spot+'-EditButton').unbind();
		
		/** before you do anything cache a copy to the current data -- only do this the first time edit button is selected **/
		if(StringUtils.isEmpty(data[spot]['old'])){
			data[spot]['old'] = jQuery('#'+spot+'-ContentContainer').html().replace(/^\s+/,'').replace(/\s+$/,'');
		}
		
		/** present the edit state **/
		jQuery('#'+spot+'-ContentContainer').html(
			'<textarea id="'+spot+'-TextArea" style="width:'+data[spot]['w']+'px;height:'+data[spot]['h']+'px;">'+data[spot]['old']+'</textarea>'
		).after('<div id="'+spot+'-ButtonContainer" class="portletbody"></div>');
		
		displayButtons(spot);		
	};

	function cancel(spot){
		jQuery('#'+spot+'-ContentContainer').html( data[spot]['old']);
		jQuery('#'+spot+'-ButtonContainer').html('');
		jQuery('#'+spot+'-EditButton').click( function(){ edit(spot); });
	}
	
	function preview(spot){			
		data[spot]['new'] = jQuery('#'+spot+'-TextArea').val().replace(/^\s+/,'').replace(/\s+$/,''); 
		jQuery('#'+spot+'-ContentContainer').html( data[spot]['new'] );
		
		//modify preview button
		jQuery('#'+spot+"-PreviewButton").val('Exit Preview');
		jQuery('#'+spot+"-PreviewButton").unbind('click').click(function(){ exitPreview(spot) });
	}
	
	
	function exitPreview(spot){
		
		/** add text area w/ new content and modify exit preview button **/
		jQuery('#'+spot+'-ContentContainer').html(
			'<textarea id="'+spot+'-TextArea" style="width: ' + data[spot]['w'] + 'px; height: ' + data[spot]['h']+ 'px;">'+data[spot]['new']+'</textarea>'
		);
		
		//modify preview button
		jQuery('#'+spot+"-PreviewButton").val('Preview');
		jQuery('#'+spot+"-PreviewButton").unbind('click').click(function(){ preview(spot) });
	}
	
	
	function save(spot){
		
		/** 
		 * check to see if the text area is present, if so use that, if not use the ContentContainer
		 * this is for the case when someone saves from preview mode (no text area in preview mode)
		 */
		var value = jQuery('#'+spot+'-TextArea').val();
		if( value !== undefined){
			value = jQuery('#'+spot+'-TextArea').val().replace(/^\s+/,'').replace(/\s+$/,'');
		}
		else{
			value = jQuery('#'+spot+'-ContentContainer').html().replace(/^\s+/,'').replace(/\s+$/,'');
		}
		
		if(data[spot]['old'] == value){
			alert('Nothing new to save!');
			return;	
		}
		
		$.ajax( 
				{
					type     : "POST",
					url      : path,
					dataType : "json",
					data     : "permLevel=" + encodeURIComponent(permissionLevel) + "&key=" + encodeURIComponent(spot) + "&body=" + encodeURIComponent(value),
					success  : function(json) {
									if (json.success) {
										alert('Content has been saved.');
										data[spot]['old'] = value;
										jQuery('#'+spot+'-ContentContainer').html(value);
										jQuery('#'+spot+'-ButtonContainer').remove();					
										jQuery('#'+spot+'-EditButton').click( function(){ edit(spot) });									
									} 
									else {
										alert("Error on save: " + json.error);
										throw {
											name:"RequestException",
											message: json.error
										}									
									}
								},
					error: function(request, text, errorThrown) {
						alert("Error on save");
						if(errorThrown) {
							throw errorThrown;
						}							
					}						
				});
	}
	
	function displayButtons(spot){				
		jQuery('#'+spot+'-ButtonContainer').html(				
				'<input type="button" id="'+spot+'-SaveButton" value="Save"/>&nbsp;'+
				'<input type="button" id="'+spot+'-PreviewButton" value="Preview"/>&nbsp;'+
				'<input type="button" id="'+spot+'-CancelButton" value="Cancel"/>'
		);
		
		//bind events to buttons
		jQuery('#'+spot+'-SaveButton').click( function(){ save(spot) });
		jQuery('#'+spot+'-PreviewButton').click( function(){ preview(spot) });
		jQuery('#'+spot+'-CancelButton').click( function(){ cancel(spot) });
	}
})(jQuery);