/*
 * 2011-11-27 $ -> $j (Indoc SC)
 * 2011-11-28 <button type="button", tagit bort CSS i default.css
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 3.2
 * Last Modified: 10/31/2011
 * 
 * Copyright 2011 Trent Richardson
 * Dual licensed under the MIT and GPL licenses.
 * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt
 * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt
 * 
 */
 
(function($j) {
	$j.prompt = function(message, options) {
		options = $j.extend({},$j.prompt.defaults,options);
		$j.prompt.currentPrefix = options.prefix;

		var ie6		= ($j.browser.msie && $j.browser.version < 7);
		var $jbody	= $j(document.body);
		var $jwindow	= $j(window);
		
		options.classes = $j.trim(options.classes);
		if(options.classes != '')
			options.classes = ' '+ options.classes;
			
		//build the box and fade
		var msgbox = '<div class="'+ options.prefix +'box'+ options.classes +'" id="'+ options.prefix +'box">';
		if(options.useiframe && (($j('object, applet').length > 0) || ie6)) {
			msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></iframe>';
		} else {
			if(ie6) {
				$j('select').css('visibility','hidden');
			}
			msgbox +='<div class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></div>';
		}
		msgbox += '<div class="'+ options.prefix +'" id="'+ options.prefix +'"><div class="'+ options.prefix +'container"><div class="';
		msgbox += options.prefix +'close">X</div><div id="'+ options.prefix +'states"></div>';
		msgbox += '</div></div></div>';

		var $jjqib	= $j(msgbox).appendTo($jbody);
		var $jjqi	= $jjqib.children('#'+ options.prefix);
		var $jjqif	= $jjqib.children('#'+ options.prefix +'fade');

		//if a string was passed, convert to a single state
		if(message.constructor == String){
			message = {
				state0: {
					html: message,
				 	buttons: options.buttons,
				 	focus: options.focus,
				 	submit: options.submit
			 	}
		 	};
		}

		//build the states
		var states = "";

		$j.each(message,function(statename,stateobj){
			stateobj = $j.extend({},$j.prompt.defaults.state,stateobj);
			message[statename] = stateobj;

			states += '<div id="'+ options.prefix +'_state_'+ statename +'" class="'+ options.prefix + '_state" style="display:none;"><div class="'+ options.prefix +'message">' + stateobj.html +'</div><div class="'+ options.prefix +'buttons">';
			$j.each(stateobj.buttons, function(k, v){
				if(typeof v == 'object')
					states += '<button type="button" name="' + options.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" id="' + options.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" value="' + v.value + '">' + v.title + '</button>';
				else states += '<button type="button" name="' + options.prefix + '_' + statename + '_button' + k + '" id="' + options.prefix +	'_' + statename + '_button' + k + '" value="' + v + '">' + k + '</button>';
			});
			states += '</div></div>';
		});

		//insert the states...
		$jjqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block');
		$jjqi.find('.'+ options.prefix +'buttons:empty').css('display','none');
		
		//Events
		$j.each(message,function(statename,stateobj){
			var $jstate = $jjqi.find('#'+ options.prefix +'_state_'+ statename);

			$jstate.children('.'+ options.prefix +'buttons').children('button').click(function(){
				var msg = $jstate.children('.'+ options.prefix +'message');
				var clicked = stateobj.buttons[$j(this).text()];
				if(clicked == undefined){
					for(var i in stateobj.buttons)
						if(stateobj.buttons[i].title == $j(this).text())
							clicked = stateobj.buttons[i].value;
				}
				
				if(typeof clicked == 'object')
					clicked = clicked.value;
				var forminputs = {};

				//collect all form element values from all states
				$j.each($jjqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){
					if (forminputs[obj.name] === undefined) {
						forminputs[obj.name] = obj.value;
					} else if (typeof forminputs[obj.name] == Array || typeof forminputs[obj.name] == 'object') {
						forminputs[obj.name].push(obj.value);
					} else {
						forminputs[obj.name] = [forminputs[obj.name],obj.value];	
					} 
				});

				var close = stateobj.submit(clicked,msg,forminputs);
				if(close === undefined || close) {
					removePrompt(true,clicked,msg,forminputs);
				}
			});
			$jstate.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton');

		});

		var fadeClicked = function(){
			if(options.persistent){
				var offset = (options.top.toString().indexOf('%') >= 0? ($jwindow.height()*(parseInt(options.top,10)/100)) : parseInt(options.top,10)),
					top = parseInt($jjqi.css('top').replace('px',''),10) - offset;

				//$jwindow.scrollTop(top);
				$j('html,body').animate({ scrollTop: top }, 'fast', function(){
					var i = 0;
					$jjqib.addClass(options.prefix +'warning');
					var intervalid = setInterval(function(){
						$jjqib.toggleClass(options.prefix +'warning');
						if(i++ > 1){
							clearInterval(intervalid);
							$jjqib.removeClass(options.prefix +'warning');
						}
					}, 100);
				});
			}
			else {
				removePrompt();
			}
		};
		
		var keyPressEventHandler = function(e){
			var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox?
			
			//escape key closes
			if(key==27) {
				fadeClicked();	
			}
			
			//constrain tabs
			if (key == 9){
				var $jinputels = $j(':input:enabled:visible',$jjqib);
				var fwd = !e.shiftKey && e.target == $jinputels[$jinputels.length-1];
				var back = e.shiftKey && e.target == $jinputels[0];
				if (fwd || back) {
				setTimeout(function(){ 
					if (!$jinputels)
						return;
					var el = $jinputels[back===true ? $jinputels.length-1 : 0];

					if (el)
						el.focus();						
				},10);
				return false;
				}
			}
		};
		
		var positionPrompt = function(){
			var bodyHeight = $jbody.outerHeight(true),
				windowHeight = $jwindow.height(),
				documentHeight = $j(document).height(),
				height = bodyHeight > windowHeight ? bodyHeight : windowHeight,
				top = parseInt($jwindow.scrollTop(),10) + (options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt(options.top,10)/100)) : parseInt(options.top,10));
			height = height > documentHeight? height : documentHeight;
			
			$jjqib.css({
				position: "absolute",
				height: height,
				width: "100%",
				top: 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jjqif.css({
				position: "absolute",
				height: height,
				width: "100%",
				top: 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jjqi.css({
				position: "absolute",
				top: top,
				left: "50%",
				marginLeft: (($jjqi.outerWidth()/2)*-1)
			});
		};

		var stylePrompt = function(){
			$jjqif.css({
				zIndex: options.zIndex,
				display: "none",
				opacity: options.opacity
			});
			$jjqi.css({
				zIndex: options.zIndex+1,
				display: "none"
			});
			$jjqib.css({
				zIndex: options.zIndex
			});
		};

		var removePrompt = function(callCallback, clicked, msg, formvals){
			$jjqi.remove();
			$jwindow.unbind('resize',positionPrompt);
			$jjqif.fadeOut(options.overlayspeed,function(){
				$jjqif.unbind('click',fadeClicked);
				$jjqif.remove();
				if(callCallback) {
					options.callback(clicked,msg,formvals);
				}
				$jjqib.unbind('keypress',keyPressEventHandler);
				$jjqib.remove();
				if(ie6 && !options.useiframe) {
					$j('select').css('visibility','visible');
				}
			});
		};

		positionPrompt();
		stylePrompt();
		
		$jjqif.click(fadeClicked);
		$jwindow.resize(positionPrompt);
		$jjqib.bind("keydown keypress",keyPressEventHandler);
		$jjqi.find('.'+ options.prefix +'close').click(removePrompt);

		//Show it
		$jjqif.fadeIn(options.overlayspeed);
		$jjqi[options.show](options.promptspeed,options.loaded);
		$jjqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus();
		
		if(options.timeout > 0)
			setTimeout($j.prompt.close,options.timeout);

		return $jjqib;
	};
	
	$j.prompt.defaults = {
		prefix:'jqi',

		classes: '',
		buttons: {
			Ok: true
		},
	 	loaded: function(){

	 	},
	  	submit: function(){
	  		return true;
		},
	 	callback: function(){



	 	},
		opacity: 0.6,
	 	zIndex: 999,
	  	overlayspeed: 'slow',
	   	promptspeed: 'fast',
   		show: 'promptDropIn',
	   	focus: 0,
	   	useiframe: false,
	 	top: '15%',
	  	persistent: true,
	  	timeout: 0,
	  	state: {
			html: '',
		 	buttons: {
		 		Ok: true
		 	},
		  	focus: 0,
		   	submit: function(){
		   		return true;
		   }
	  	}
	};
	
	$j.prompt.currentPrefix = $j.prompt.defaults.prefix;

	$j.prompt.setDefaults = function(o) {
		$j.prompt.defaults = $j.extend({}, $j.prompt.defaults, o);
	};
	
	$j.prompt.setStateDefaults = function(o) {
		$j.prompt.defaults.state = $j.extend({}, $j.prompt.defaults.state, o);
	};
	
	$j.prompt.getStateContent = function(state) {
		return $j('#'+ $j.prompt.currentPrefix +'_state_'+ state);
	};
	
	$j.prompt.getCurrentState = function() {
		return $j('.'+ $j.prompt.currentPrefix +'_state:visible');
	};
	
	$j.prompt.getCurrentStateName = function() {
		var stateid = $j.prompt.getCurrentState().attr('id');
		
		return stateid.replace($j.prompt.currentPrefix +'_state_','');
	};
	
	$j.prompt.goToState = function(state, callback) {
		$j('.'+ $j.prompt.currentPrefix +'_state').slideUp('slow');
		$j('#'+ $j.prompt.currentPrefix +'_state_'+ state).slideDown('slow',function(){
			$j(this).find('.'+ $j.prompt.currentPrefix +'defaultbutton').focus();
			if (typeof callback == 'function')
				callback();
		});
	};
	
	$j.prompt.nextState = function(callback) {
		var $jnext = $j('.'+ $j.prompt.currentPrefix +'_state:visible').next();

		$j('.'+ $j.prompt.currentPrefix +'_state').slideUp('slow');
		
		$jnext.slideDown('slow',function(){
			$jnext.find('.'+ $j.prompt.currentPrefix +'defaultbutton').focus();
			if (typeof callback == 'function')
				callback();
		});
	};
	
	$j.prompt.prevState = function(callback) {
		var $jnext = $j('.'+ $j.prompt.currentPrefix +'_state:visible').prev();

		$j('.'+ $j.prompt.currentPrefix +'_state').slideUp('slow');
		
		$jnext.slideDown('slow',function(){
			$jnext.find('.'+ $j.prompt.currentPrefix +'defaultbutton').focus();
			if (typeof callback == 'function')
				callback();
		});
	};
	
	$j.prompt.close = function() {
		$j('#'+ $j.prompt.currentPrefix +'box').fadeOut('fast',function(){
        		$j(this).remove();
		});
	};
	
	$j.fn.extend({ 
		prompt: function(options){
			if(options == undefined) 
				options = {};
			if(options.withDataAndEvents == undefined)
				options.withDataAndEvents = false;
			
			$j.prompt($j(this).clone(options.withDataAndEvents).html(),options);
		},
		promptDropIn: function(speed, callback){ 
			var $jt = $j(this); 
			
			if($jt.css("display") == "none"){ 
				var eltop = $jt.css('top');
				$jt.css({ top: $j(window).scrollTop(), display: 'block' }).animate({ top: eltop },speed,'swing',callback); 
			}
		}
		
	});
	
})(jQuery);

