/**
 * Change submit button to stylized png button.
 * author: nod 
 * created: 23-11-2010
 */

jQuery.fn.pngbutton = function(OS){
	var OS = jQuery.extend({
		btnId: "pngButton", // id который будет присвоен всему новосозданному элементу кнопки
		bgImage: "/i/btn-all.png",
        bgImageHoverIndex: 1,
        bgImageClickIndex: 2,
		lrWidth: 18, // ширина в px боковых плашек
		height: 35, // высота кнопки в px
		textTopOffset: 8, // отступ сверху для текста в кнопке
		color: '#000',
		colorHover: '#000',
		colorClick: '#000'
	},OS);
	
	return this.each(function() {
        
        if($(this).data('pngbuttonEnabled')) {
            return;
        }
        
        $(this).data('pngbuttonEnabled', true);
        
		var btnTitle = $(this).val();
		var replaceCSS = function(parent, bgDispMultiplier, color) {
			jQuery(parent).find('span').css({
				backgroundPosition:function(i,val) {
				    var split = val.split(" ");
				    return split[0] + " " + (-1 * OS.height * (2 * bgDispMultiplier + ((split[1].replace(/[^0-9]/g, "") * 1 / OS.height) % 2))) + "px"
				},
				color:color
			});
		}
		
	    var newBtn = jQuery(
    		'<a href="#" style="height:'+OS.height+'px; display:inline-block;text-decoration: none;outline: none;white-space: nowrap;" id="'+OS.btnId+'">'
		    +'<span style="width:'+OS.lrWidth+'px;background: url('+OS.bgImage+') no-repeat 0px 0px;">&nbsp;</span>'
		    +'<span style="background: url('+OS.bgImage+') repeat-x 0px -'+OS.height+'px;">'+btnTitle+'</span>'
		    +'<span style="width:'+OS.lrWidth+'px; background: url('+OS.bgImage+') no-repeat -'+OS.lrWidth+'px 0px;">&nbsp;</span>'
		    +'</a>'
	    );
	    jQuery(newBtn).find('span').css({display:'inline-block', color:OS.color, cursor:'default'});

		jQuery(this)
		.hide()
		.after(newBtn)
		.after('<input type="submit" style="position:absolute; right:100000px;" value="'+btnTitle+'" />');
		
		// pseudo Vertical-Align
		jQuery(newBtn).find('span').css({height:(OS.height-OS.textTopOffset)+'px', padding:OS.textTopOffset+'px 0 0 0'});
		
		// replace BG IMAGE on HOVER, MOUSEDOWN, MOUSEUP
		jQuery(newBtn)
			.hover(
				function(){replaceCSS(this, OS.bgImageHoverIndex, OS.colorHover);},
				function(){replaceCSS(this, 0, OS.color);}
			)
			.mousedown(function(){replaceCSS(this, OS.bgImageClickIndex, OS.colorClick);})
			.mouseup(function(){replaceCSS(this, 0, OS.color);});
		
		// onsubmit event
		var THIS=this;
		jQuery(newBtn).click(OS.action ? OS.action : function(){jQuery(THIS).trigger('click'); return false;});
	});
};

