/*Switcharoo: style switcher with a fancy button, cookie and link support
  Josh Rehman, hello@javajosh.com © 2011
  Dependancies: jquery, iphone-style-checkbox, jquery cookie
  Description: put a checkbox in your markup like <input type="checkbox" id="mode" />, then load this module's
  dependancies then this module, and call init(). 
  Comments: It can be difficult to position the marked up checkbox directly. Instead, position a parent container.
  It might be nice to support pass-through configuration of the iphone checkbox. Note that this is designed to work
  with only one switch - I suppose it could be used with multiples, in which case I would treat the hash as the 
  model in an MVC setup.
*/

;var Switcharoo = function(){
	var loaded = false;
  	function onTag(){
  		return 'on';
  	}
  	function offTag(){
  		return 'off';
  	}
  	function modeTag(){
  		return 'mode';
  	}
  	
  	function beforeSwitch(on){} //user should override this
  	function afterSwitch(on){} //user should override this
  	function getAnimation(on){return "slow";}
  	
  	function getToggle(){
  		return $('#' + modeTag() + ':checkbox');
  	}
  	function isToggleOn(){
  		return getToggle().is(":checked");
  	}
  	
  	function isCookieOn(){
  		return $.cookie(modeTag()) == onTag();
  	}
  	
  	function isHashOn(){
  		return window.location.hash == '#' + onTag();
  	}
	
	//Hash takes precedence because it's editable by a user, and linkable.
	function userChoiceOnLoad(){
		if (window.location.hash) 
			return isHashOn();
		if ($.cookie(modeTag())) 
			return isCookieOn();
		return false;
	}
	
	function makeDOMConsistentWithToggle(speed){
		var on = isToggleOn();
		var active = on ? onTag() : offTag();
		var inactive = !on ? onTag() : offTag();
		
		$('.' + inactive).fadeOut(speed, function(){
			$('body').toggleClass(onTag(), on).toggleClass(offTag(), !on);
			$('.' + active).fadeIn(speed);
		});
		
		$.cookie(modeTag(), active, {
			expires: 365
		});
		window.location.hash = active;
		
	}
	function init(config){
		if (config){
			onTag = config.onTag ? config.onTag : onTag;
			offTag = config.offTag ? config.offTag : offTag;
			modeTag = config.modeTag ? config.modeTag : modeTag;
			getToggle = config.getToggle ? config.getToggle : getToggle;
			beforeSwitch = config.beforeSwitch ? config.beforeSwitch : beforeSwitch;
			afterSwitch = config.afterSwitch ? config.afterSwitch : afterSwitch;
			getAnimation = config.getAnimation ? config.getAnimation : getAnimation;
		}
		$(function main(){
			getToggle().attr('checked', userChoiceOnLoad()).iphoneStyle({
				checkedLabel: 'on',
				uncheckedLabel: 'off'
			}).change(function(){
				var on = isToggleOn();
				beforeSwitch(on);
				makeDOMConsistentWithToggle(!loaded ? 0 : getAnimation());
				afterSwitch(on);
				loaded = true;
				}).change();
			});
		}
		
		
		return {
			init:init
		}
}();
