(function($) {
	$.iphoneStyle = {
		defaults: { checkedLabel: '', uncheckedLabel: '', background: 'transparent', callback: null }
	}

	$.fn.iphoneStyle = function(options) {
		options = $.extend($.iphoneStyle.defaults, options);

		return this.each(function() {
			var elem = $(this);

			if (!elem.is(':checkbox')) return;

			//elem.css({ opacity: 0 });
			elem.wrap('<div class="slidebutton" />');
			elem.after('<div class="sl_handle"><div class="sl_bg" style="background:transparent ' + options.background + '"/><div class="sl_slider" /></div>')
						.after('<label class="sl_off">' + options.uncheckedLabel + '</label>')
						.after('<label class="sl_on">' + options.checkedLabel + '</label>');

			var handle = elem.siblings('.sl_handle'),
			  handlebg = handle.children('.sl_bg'),
			  offlabel = elem.siblings('.sl_off'),
			  onlabel = elem.siblings('.sl_on'),
			  container = elem.parent('.slidebutton'),
			  rightside = container.width() - 45,
			  id = this.id;

			container.click(function() {
				var is_onstate = (handle.position().left <= 0);
				new_left = (is_onstate) ? rightside : 0,
				bgleft = (is_onstate) ? 34 : 0;

				handlebg.hide();
				handle.animate({ left: new_left }, 100, function() {
					handlebg.css({ left: bgleft }).show();
				});

//				if (is_onstate) {
//					offlabel.hide(); //.animate({ opacity: 0 }, 200);
//					onlabel.show(); //.animate({ opacity: 1 }, 200);
//				} else {
//					offlabel.show(); //.animate({ opacity: 1 }, 200);
//					onlabel.hide(); //.animate({ opacity: 0 }, 200);
//				}

				elem.attr('checked', is_onstate);

				if (options.callback) {
					var args = [id, is_onstate];
					options.callback.apply(null, args);
				}
				return false;
			});

			elem.bind("checked", function(e, is_onstate) {
				new_left = (is_onstate) ? rightside : 0,
				bgleft = (is_onstate) ? 34 : 0;

				handlebg.hide();
				handle.animate({ left: new_left }, 100, function() {
					handlebg.css({ left: bgleft }).show();
				});

				if (is_onstate) {
					offlabel.animate({ opacity: 0 }, 200);
					onlabel.animate({ opacity: 1 }, 200);
				} else {
					offlabel.animate({ opacity: 1 }, 200);
					onlabel.animate({ opacity: 0 }, 200);
				}

				elem.attr('checked', is_onstate);
				return false;
			});

			// initial load
			if (elem.is(':checked')) {
				offlabel.css({ opacity: 0 });
				onlabel.css({ opacity: 1 });
				handle.css({ left: rightside });
				handlebg.css({ left: 34 });
			}
		});
	};
})(jQuery);