/*/////////// JQUERY EXTENSIONS ///////////*/

jQuery.fn.center = function () {
	this.css("position","fixed");
	this.css("top", (($(window).height()/2) - (this.height()/2)+"px"));
	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	return this;
}

jQuery.fn.stretch = function () {
	this.css("height", $(window).height());
	this.css("width",  $(window).width());
	return this; 	
}



/*/////////// MISC ///////////*/

function ajaxLoadForm(destination,context){
	// "destination" is the element the new elements
	// will be loaded into
	var destination = destination;

	// "content" is the element pulled from the remote file
	// this will be loaded into "destination"
	var context = context;
	
	// get the CI baseURL for AJAX url property 
	// This function is on the page
	var baseURL = returnBaseURL();	
	
	// prep the url for the call
	var url = baseURL+"cms/ajax/forms/";
	
	// Ajax call
	// Get remote element ("content") 
	// from the remote file ("url")
	// and load it into local element ("desination")
	$(destination).load(url+" "+context);
}




/*/////////// ERROR HANDLING ///////////*/

function notice(params){
	var $notice = $("<div />").attr("id","errors").css("display","none");
	var $heading = $("<h1 />").text(params.title);
	var $message = $("<p />").text(params.message);
	var $button  = $("<button />").attr({
			className:"button",
			id:"errorsClose"
		}).text("Close");
	$notice.append($heading,$message,$button);
	$notice.appendTo($("#wrapper")).slideDown();

	// Close on click
	$("#errorsClose").live('click',function(){
		$("#errors").remove();	
	});		

	//Close on enter key
	$(window).keyup(function(e) {
		if(e.keyCode == 13) {
			$("#errors").remove();
			e.preventDefault();
		}
		if(e.keyCode == 27) {
			$("#errors").remove();
			e.preventDefault();
		}
	});    
}


function gutCheck(params){
	var $content = $("<div />").attr("className","modalWarning");
	var $warning = $("<h4 />").text(params.message);
	var $button = $("<button />").attr({
		className: "button blue",
		id: "warningContinue"	
	}).text("Continue");
	
	$content.append($warning,$button);
	var modal = new Modal("Warning",$content,400,150,"Cancel");	
	modal.init(); // fire it  up
	
	$("#warningContinue").live('click',function(){
		params.run();
		modal.destroy();
	});	
}





/*/////////// MODAL WINDOWS ///////////*/

function FileBrowser(trigger) {
	// Change the name of the function namespace
	// to leave the "this" keyword alone
	var FB = this; 

	// Fetch the base url. Function is on page.
	var baseURL = returnBaseURL();		
	
	// Create a jQuery object from the trigger
	// variable passed in the original FB call
	$trigger = $(trigger); 
	
	// If the trigger has a filetype attribute
	// then set it, otherwise leave it blank
	if($trigger.attr("filetype")!=''){
		FB.filetype = $trigger.attr("filetype");
	} else {
		FB.filetype = "";
	}
	
	// Grab the filter param from the trigger
	// This is used in the ajax call to the API
	FB.filter = $trigger.attr("filter");
	

	// Detect the context of the trigger button
	FB.params = {
		// The (hidden) input the file value is inserted to
		input	: $trigger.siblings("."+FB.filetype+"_input"),
		// The preview image the file preview is inserted to
		preview : $trigger.siblings("."+FB.filetype+"_preview")
	}
	

	// Set the title to be passed to the modal 
	FB.title = "Select "+FB.filetype;
	
	// Set up the content to be passed to the modal
	FB.content = function(){
	
		// Create the a table and the column heads
		var $table = $("<table >").attr("className","data").html("<thead><td>Preview</td><td>File Name</td><td>File Type</td><td>File Size</td></thead>"
		);
			
		$.ajax({ 
			type: "GET", 
			// connect to the API
			// pluralizes the filetype to match API urls
			// adds the filter to draw items from only certain upload_path column
			url: baseURL+"index.php/cms/api/"+FB.filetype+"s/"+FB.filter, 

			error: function(xhr, status, error){
			  console.log("Ajax error in file: /js/library.js method: FB.content pulling: " + baseURL+"index.php/cms/api/"+FB.filetype+"s/"+FB.filter);
			  console.log(xhr, status, error);
			},

			success:function(xml){
				// For each "file" tag in the XML...
			  $("file",xml).each(function(){
					// Create a JQ object
					var $this = $(this);
					// Grab some info
					var upload_path = $this.find("upload_path").text();
					var file_name = $this.find("file_name").text();
					var file_type = $this.find("file_type").text();				
					var file_size = $this.find("file_size").text();				
					
					// Create a table row with params for "click" functionality
					var $rowwrapper = $("<tr />").attr({
						className : "filerow",
						file:upload_path+file_name
					});

					// Create the preview image		
					var $pv_image = $("<img />").attr({
						src:baseURL+upload_path+file_name,
						className: FB.filetype
					});
					
					// Create each of the cells
					var $pvcell = $("<td />").attr({className:"fb_preview"}).html($pv_image);
					var $fncell = $("<td />").text(file_name);
					var $ftcell = $("<td />").text(file_type);
					var $fscell = $("<td />").text(file_size);
					
					// Insert the cells into the row, insert the row to the table
					$rowwrapper.append($pvcell,$fncell,$ftcell,$fscell).appendTo($table);
			  });						
			} // end success
		});	// end ajax			

		var $FBContent = $("<div />").attr("className","modalContent");
		$FBContent.append($table);

		return $FBContent;	
	}

	// Create a new modal window
	// Pass the created title and content
	var modal = new Modal(FB.title,FB.content(),'default','default',"Cancel");
	modal.init(); // fire it  up

	// Destroy the modal window
	FB.destroy = function(){
		modal.destroy();
	}
	
	// Set up some click observe functions
	$("tr.filerow").live('click',function(){
		
		// Grab the file param of the row
		var file = $(this).attr("file");
		
		// insert the file value to the input
		FB.params.input.val(file);
		
		// insert the file to the preview
		FB.params.preview.show().attr({src:baseURL+file});
		
		// Kill the modal window
		FB.destroy();				
	});

}










function Modal(title,content,width,height,closeText) {
	// Change the name of the function namespace
	// to leave the "this" keyword alone
	var Modal = this; 
	
	
	Modal.params = {
		width: function(){
				if(width==''||width=='default'){
					return "840";
				} else {
					return width;			
				}
			},	
		height: function(){
				if(height==''||height=='default'){
					return "500";
				} else {
					return height;
				}			
			},
		closeText: function(){
			if(closeText==''){
				return "Cancel";
			}	else {
				return closeText;
			}			
		}				
	}
	
	
	// Set everything up
	// Called by default at the end of the Modal function
	Modal.init = function() {
		Modal.destroy(); // Destroy any existing modal windows, just in case
		Modal.overlay.build(); // Build the overlay
		Modal.window.build(); // Build the window
		Modal.observe(); // Keep and eye on things
	};	
	
	Modal.overlay = {
		attr : {
			className: "overlay"
			},
		css : {
			color : "#FFF",
			opacity: "0.75"
		},
		build : function(){
			$("<div/>").attr(this.attr).css(this.css).appendTo("body").stretch();			
		}
	}
	
	Modal.window = {
		attr : { 
			className : "modal"		
		},
		css : {
			width: Modal.params.width() + "px",
			height:Modal.params.height() + "px"
		},
		build : function(){
			var $wrapper = $("<div/>").attr(this.attr).css(this.css);
			var $header = $("<h3 />").text(title);
			var $closeLink = $("<a />").attr({ 
					className: "button inline red",  
					id: "modalClose"
				}).text(Modal.params.closeText);	
			$header.append($closeLink);	
			$wrapper.append($header,content).appendTo("body").center();
		}
	}
	
	
	Modal.position = function(){
		var $window = $("."+Modal.window.attr.className);
		$window.center();	// custom method --> jquery.extension.js	
	}
	
	Modal.observe = function(){
		// Set up JQ objects for overlay and window
		var $overlay = $("."+Modal.overlay.attr.className);
		var $window = $("."+Modal.window.attr.className);
		
		// Close the modal when user clicks on overlay
		$overlay.live('click',function(){
			Modal.destroy();		
		});	
		
		// Recenter everything on resize
		$(window).resize(function() {
			Modal.position();		
		});

		// Observe the close button
		$("#modalClose").live('click',function(){
			Modal.destroy();
		});
		
		//Close on esc key
		$(window).keyup(function(e) { 
			if(e.keyCode == 27) {
				Modal.destroy();
				e.preventDefault();
			}
		}); 
	}
	
	// Destroy that motherfucker	
	Modal.destroy = function(){
		var $overlay = $("."+Modal.overlay.attr.className);
		var $window = $("."+Modal.window.attr.className);
		$overlay.remove();
		$window.remove();
	}
	

}
