/*
 * jQuery Rebrush Fileupload plugin 0.1 Beta
 *
 * Copyright (c) 2009 Marc Bonsels
 *
 */

;(function($) {
	$.rebrushfileupload = {
		defaults: {
			button_text: '',
			class_container: 'fileupload-rebrush',
			class_field: 'fileupload-rebrush-field',
			class_button: 'fileupload-rebrush-button'
		}
	};
	
	$.fn.extend({
		rebrushfileupload: function(settings) {
			// Check if user gave us some settings
			settings = $.extend({}, $.rebrushfileupload.defaults, settings);
			
			// Which attributes should be added to the width of the
			// created elements?
			var attributes = ["padding-left", "padding-right", "margin-left", "margin-right", "border-left-width", "border-right-width"];
	
			// Wrap the fileuploadfield with a div for positioning
			$(this).wrap('<div class="rebrush-container ' + settings['class_container'] + '" />');
			var obj_container_div = $(this).parent();
			
			// Create the new, stylable elements within the new div		
			obj_container_div.prepend('<input type="text" value="" readonly="readonly" class="rebrush-field ' + settings['class_field'] + '" /><input type="button" value="' + settings['button_text'] + '" class="rebrush-button ' + settings['class_button'] + '" />');
			var obj_rebrush_field = obj_container_div.find("input.rebrush-field");
			var obj_rebrush_button = obj_container_div.find("input.rebrush-button");
			
			// Calculate the real needed width of the container div for positioning
			var wrapperwidth = 0;
			for (var attr in attributes) {
				var val_field = Math.round(parseFloat(obj_rebrush_field.css(attributes[attr]) + 0)) + 0;
				var val_button = Math.round(parseFloat(obj_rebrush_button.css(attributes[attr]) + 0)) + 0;
				wrapperwidth += (isNaN(val_field) ? 0 : val_field) + (isNaN(val_button) ? 0 : val_button);
			}

			wrapperwidth += Math.round(parseFloat(obj_rebrush_field.width())) + Math.round(parseFloat(obj_rebrush_button.width()));
	
			// Give the containerdiv the calculated width and hide the original fileupload-field
			obj_container_div.css('width', wrapperwidth);
			
			$(this).css({
				'position': 'absolute',
				'z-index': 2,
				'font-size': '120px',
				'opacity': '0',
				'right': '0px',
				'top': '0px'
			});
			
			// Bind the changeevent on the original field and copy its value
			// to the new textfield (which is readonly of course ;-)) everytime
			// the original field is changed
			$(this).change(function() {
				$(this).parent().find("input[type=text].rebrush-field").val($(this).val());
			});
		}
	});
})(jQuery);