/**
 * Usage:
 * <div class="z_switch">
 *     <a class="switch_on" href="http://www.example.com/path/to/switch/on">ON</a>
 *     <a class="switch_off" href="http://www.example.com/path/to/switch/off">OFF</a>
 * </div>
 * $('.z_switch').isSwitch();
 * $('.z_switch').isSwitch(function(jQueryElement this, boolean turnedOn){});
 */
(function($){
	$.fn.isSwitch = function(callback) {
		function applyCallback(_self, turnedOn) {
			return function(response) {
				if (!response || response.ret < 1) {
					return;
				}
				if (turnedOn) {
					_self.addClass('on');
					_self.find('.switch_indicator').attr('checked', 'checked');
				} else {
					_self.removeClass('on');
					_self.find('.switch_indicator').removeAttr('checked');
				}
				if (typeof(callback) == 'function') {
					callback(_self, turnedOn);
				}
			}
		}
		function complete(_self) {
			return function() {
				_self.removeClass('loading');
			}
		}
		function onClick(event) {
			var _self = $(this);
			if (_self.hasClass('loading')) {
				return false;
			}
			_self.addClass('loading');
			var turningOn = (!_self.hasClass('on'));
			var url = turningOn
				? _self.find('.switch_on').attr('href')
				: _self.find('.switch_off').attr('href');

			$.post(url, applyCallback(_self, turningOn));
			$.ajax({type: 'POST', url: url, success: applyCallback(_self, turningOn),
				complete: complete(_self), dataType:'json' });
			try{ event.preventDefault(); }catch(e) {}
			return false;
		}
		$(this).click(onClick);
		$(this).addClass('ajaxified');
	};
})(jQuery);
