﻿/*
 * Style File - jQuery plugin for styling file input elements
 *  
 * Copyright (c) 2007-2008 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Based on work by Shaun Inman
 *   http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
 *
 * Revision: $Id: jquery.filestyle.js 303 2008-01-30 13:53:24Z tuupola $
 *
 */

(function($) {

	$.fn.filestyle = function(options) {

		/* TODO: This should not override CSS. */
		var settings = {
			image: null,
			imageheight: 0,
			imagewidth: 0,
			width: 250,
			hover: false
		};

		if (options) {
			$.extend(settings, options);
		}
		
		if( settings.image ) {
			return this.each(function() {
	
				var self = this;
				
				var wrapper = $("<div>").css({
					"display": "inline",
					"position": "absolute",
					"overflow": "hidden",
					"width": settings.imagewidth + "px",
					"height": settings.imageheight + "px",
					"background-image": "url(" + settings.image + ")",
					"background-repeat": "no-repeat",
					"background-position": "100% 0%",
					"vertical-align": "top",
					"margin": "0",
					"padding": "0"
				});
	
				var filename = $('<input class="file">').addClass($(self).attr("class")).css({
					"display": "inline",
					"width": settings.width + "px"
				});
	
				$(self).before(filename);
				$(self).wrap(wrapper);
	
				$(self).css({
					"position": "relative",
					"height": settings.imageheight + "px",
					"width": settings.width + "px",
					"display": "inline",
					"cursor": "pointer",
					"opacity": "0.0"
				});
				
				/* add the image hover, if user set it (requires the image to have a hover image) */
				if( settings.hover ) {
					$(self).mouseover(function() {
						$(this).parent("div").css({
							"background-position": "100% 100%"
						});
					}).mouseout(function() {
						$(this).parent("div").css({
							"background-position": "100% 0%"
						});
					});
				}
	
				if ($.browser.mozilla) {
					if (/Win/.test(navigator.platform)) {
						$(self).css("margin-left", "-142px");
					} else {
						$(self).css("margin-left", "-168px");
					}
				} else {
					$(self).css("margin-left", settings.imagewidth - settings.width + "px");
				}
	
				$(self).bind("change",
				function() {
					filename.val($(self).val());
				});
	
			});
		}

	};

})(jQuery);