/*  TINY LINEUP Question JS
    Copyright 2009
*/

$(document).ready(function(){
	
	suggest();

	o = 2;  // counter that represents number of enabled options (doesn't inc. add row)
	
	$("#options_step ol").empty();
	
	btn_del = '<button type="button" class="delete"><span>Delete</span></button>';
	btn_add = '<button type="button" class="add"><span>Add</span></button>';

	option = '<li class="st"><input name="" type="text" class="text" />' + btn_del + '</li>';
	holder = '<li class="pl"></li>';
	addbar = '<li class="st add"><input type="text" class="text" />' + btn_add + '</li>';
	
	$("#options_step ol").append(option+option+addbar);
	
	shift = false;
	
	bindOptions();
	
	$("#the_question.text").focus();
	
	$("#options_step ol").sortable({
			placeholder: 'pl', helper: 'original', forcePlaceholderSize: true
		}).bind('sortupdate',function(){
			var addLoc = $("#options_step li").index($("li.add"));
			if (addLoc < ($("#options_step li").length-1)) {
				addOption($("#options_step li").eq(addLoc));
			}
		}).bind('sortstart',function(){
			$("#options_step li").css("list-style","inside url(/img/bullet.png)");
		}).bind('sortstop',function(){
			$("#options_step li").css("list-style","decimal inside");
		});
	
	$("#create_poll").bind('submit',function(){ submitOptions(); return false; });
	$("#finish button").bind('click',function(){ submitOptions(); return false; });
	
	$("#poll_settings_toggle").makeToggle('#poll_settings',
		function(){
			$("#poll_settings_account").fadeOut();
			$("#poll_settings_account_info .widget").fadeIn();
//			$("#poll_settings_account_info .widget").css({ height: 0, opacity: 0 }).show().animate({ height: "102px", opacity: 1 });
		}, function(){
			$("#poll_settings_account").fadeIn();
			$("#poll_settings_account_info .widget").fadeOut();
//			$("#poll_settings_account_info .widget").animate({ height: 0, opacity: 0, display: "none" });
		},'closed');
	
	$.preload("/img/screen.png");
	
	initColorChooser();
	
	$("#poll_settings_account_login").bind('click',function(){ showLittleLogin(); $('html,body').animate({scrollTop: 0}, 1000); return false; })
	$("#poll_settings_account_info_login").bind('click',function(){ showLittleLogin(); return false; })

});

function suggest(){
	
	var i = Math.floor(Math.random()*3);
	var q = ['What time can everyone make it to dinner tonight?',
				'What movie should we all go see on Friday?',
//				'When should this really unimportant meeting be scheduled?',
				'What should I name my brand-new, really cute puppy?'];
			
	var suggestion = 'For example, &#8220;' + q[i] + '&#8221;';
	$("#the_question").suggest(suggestion);
	
}

function initColorChooser(){
	
	$("#choose_colors a").bind('click',function(){ chooseColor(this); return false; });
	
	function chooseColor(color){
		
		var $chooser = $(color);
		var color = $chooser.attr("id").substring(7);
		
		$("body").attr("class","").addClass(color);
		$("#color").val(color);
		$("#choose_colors a").removeClass("checked");
		$chooser.addClass("checked");
		
	}
	
	// preload color images
	
	$.preload("/img/b-red.gif","/img/b-orange.gif","/img/b-green.gif","/img/b-blue.gif",
		"/img/b-purple.gif","/img/b-pink.gif","/img/b-black.gif","/img/b-gray.gif",
		"/img/userbox-red.gif","/img/userbox-orange.gif","/img/userbox-green.gif","/img/userbox-blue.gif",
		"/img/userbox-purple.gif","/img/userbox-pink.gif","/img/userbox-black.gif","/img/userbox-gray.gif");
	
}

function bindOptions(){
	
//	$("form").bind('submit',function(){ return false; })
	
	$("#options_step li").unbind();

	$("#options_step li input.text").unbind();
	
	$("#options_step li input.text").bind('focus',function(){
		
//			alert("focus")
//			$(this).css("background-color","#cee")
			
			$(this).select();
			focusOption($(this).parents("li"));

		}).bind('keydown',function(e){
		
			var k = e.charCode || e.keyCode || window.event.keyCode || 0;

			if (k == 16) { shift = true;

			} else if ((k == 9 && shift == false) || k == 40) {  // tab or down arrow
//				alert("first")
				addOption($(this).parents("li").next());
//				$(this).parents("li").next().find("input.text").focus();
				
			} else if ((k == 9 && shift == true) || k == 38) {  // shift-tab or up arrow
				addOption($(this).parents("li").prev());
				
			} else if (k >= 48 && k <= 90) {  // alphabetic letters
				
			} else if (k==8) {  // backspace
				
				if ($(this).val() == "") {
					delOption($(this).parents("li"));
					return false;
				}

			} else if (k == 46) {  // delete
				
				if ($(this).val() == "") {
					delOption($(this).parents("li"),'next');
					return false;
				}

			};
			
		}).bind('keyup',function(e){
		
			var k = e.charCode || e.keyCode || window.event.keyCode || 0;
			if (k == 16) { shift = false; }
			
		});
	
	$("#options_step li.add").bind('click',function(){ addOption($(this)); return false; });

	$("#options_step button.delete").unbind().bind('click',function(){ delOption($(this).parents("li")); return false; });
	
}

function focusOption(row){
		
//	var y = $("#options_step li").index(row) + 1;
	
	if ($(row).hasClass("add")) {  // tabbing to add row
		
		addOption($(row));		
		
	}
	
}

function addOption(row){
	
	if ($(row).hasClass("add")) {
	
		$(row).each(function(){
			$(this).find("button.add").remove();
			$(this).append(btn_del);
			$(this).removeClass("add");
		});
	
	}
	
	if ($("#options_step li.add").length == 0)
		$("#options_step ol").append(addbar).find("li.add").fadeIn();
	
	o = $("#options_step li").not(".add").length;

	bindOptions();
	
	setTimeout(function(){ $(row).find("input.text").focus(); },1);
		// we use a timeout to account for users who tab between inputs vs. those who tab between all page elements
	
}

function delOption(row,foc){
	
	o = $("#options_step li").not(".add").length;
	
	if (o > 2) {
	
		if (o == 3) o = 2;
    	
		$(row).slideUp(200,function(){
			
			if ($("#options_step li").index(row) == 0) {
				$("#options_step li:nth-child(2) input.text").focus();
			} else {
				if (foc == 'next' && !$(row).next().hasClass("add"))
					$(row).next().find("input.text").focus();
				else $(row).prev().find("input.text").focus();
			}
    	
			$(this).remove();
    	
		});
	
	} else {

		$(row).find("input.text").val("");
		$(row).effect("shake", { distance: 5, times: 2 }, 65, function(){
			$(row).find("input.text").focus(); });

	}
	
}

function submitOptions(){
	
	var i = 0;
	
	$("#options_step input.text").each(function(){
		if ($(this).val() != '') {
			$(this).attr("name","o["+i+"]");
			i += 1;
		}
	})
	
	$("#finish p.sm").hide();
	$("#finish button").after('<div class="loading"></div>');
	
	if (!errors()) {

		$("#message.error").slideUp(200);
		
		var p = [];
		
		$("#options_step input.text").each(function(){
			if ($(this).val() != '') p[p.length] = $(this).val();
		})

//		$("form input").attr("disabled","disabled");
		$("form input:focus").blur();

		loadOverlay('newpoll', '/ajax/newpoll.php', { q: $("#the_question").val(), 'o[]': p, color: $("#color").val(), notifications: $("#notifications").val() } );
	
	}
	
}

function errors(){
	
	// reset
	var e = false;
	var d = 200;

	$(".error").not("#message").removeClass("error");
	$(".error-marker").fadeOut();
	$("#message").animate({ opacity: 0 },d);
	
	var q = false; var f = 0;

	if ($("#the_question").val() == '') {
		$("#question_step .step").after('<div class="error-marker"></div>');
		setTimeout(function(){ $("#question_step .error-marker").fadeIn(); },(d*2));
		e = true; q = true;
	}

	$("#options_step input.text").not("#options_step input.text:last").each(function(){
		if ($(this).val() != '') {
			f += 1;
		} else {
			$(this).parents("li").addClass("error");
		}
	})
	
	if (f < 2) {
		$("#options_step .step").after('<div class="error-marker"></div>');
		setTimeout(function(){ $("#options_step .error-marker").css("top",($("#options_step li.error:first").offset().top-42)); },(d*2));
		setTimeout(function(){ $("#options_step .error-marker").fadeIn( /* function(){ $(this).stop(); throb(this); } */ ); },(d*2));
		e = true;
	}

	if (e == true) {

		var text = 'We can&#8217;t create your poll without ';
		
		setTimeout(function(){

		if (q == true) {
			$("#the_question").focus();
			text += '<strong><a href="#" class="q">the question</a></strong>';
			if (f < 2) { text += ' and <strong>at least <a href="#" class="o">two options</a></strong>.'; }  // <br /> Add these and we&#8217;re in business.
			else { text += '.'; }; // <br /> Add the question and we&#8217;re in business.

		} else {
			$("#options_step li.error:first input.text").focus();
			text += ' <strong>at least <a href="#" class="o">two options</a></strong>.'; // <br /> Add some options and we&#8217;re all set.
		}
		
		$("#message").addClass('error').find("p").html(text);
		$("#message.error").css("opacity",0).slideDown(d).animate({ opacity: 1 },100,function(){
			$(".loading").fadeOut(function(){ $(this).remove(); });
		});
		
		$("#message.error a.q").bind('click',function(){ $("#the_question").focus(); return false; });
		$("#message.error a.o").bind('click',function(){ $("#options_step li.error:first input.text").focus(); return false; });
		
		},d);		

	}

	return e;

}
	
/* function throb(em){

	$(em).css("opacity",.2).animate({ opacity: .2 },600).animate({ opacity: 1 },800, function(){ throb(em) } );

} */





