//  TINY LINEUP aka OPTIONIZE
//  Window JS
//  Copyright 2009


$(document).ready(function(){
	
	_window = {};
	_window.body = $("body").attr("id");

	$.preload("/img/logo-beta.png");

	$("#footer a[href='/feedback/']").click(function(){ if (GSFN) feedback_widget.show(); return false; });
	$("a[rel='tinyprop']").click(function(){ window.open(this.href); return false; });
	
//	ZeroClipboard.setMoviePath('/flash/ZeroClipboard.swf');
	
	initOverlay();
	
	initLittleLogin();
	
	checkAlert();
    
    initCheckboxes();
	
});

function initLittleLogin(){
	
	var $form = $("#little_login");
	var $email = $("#little_email");
	var $pass = $("#little_password");
	var $msg = $("#little_login div.message");
	
	$email.suggest('Email'); $pass.suggest('Password');
	
	$form.find(":input").attr("tabindex","-1");
	
	$("#load_little_login").bind('click',function(){
		showLittleLogin(); return false;
	})
	
	$("#little_close").click(function(){
		hide(); return false;
	})
	
	$form.submit(function(){
		hideMessage();
		$.post('/ajax/login.php',
			{ email: $email.val(), password: $pass.val() },
            function(ret){
                if (ret == "true") {
                    hideMessage();
					loadLoggedIn();
                }
                else if (ret == "nouser") {
                    showMessage();
                }
                else if (ret == "nopass") {
                    showMessage();
                }
                else if (ret == "invalid") {
                    showMessage();
                }
                else {
					showMessage();
				}
			})
		return false;
	})

	function hide(){ $form.css({ bottom: "80px" }); $form.find(":input").attr("tabindex","-1"); resetMessage(); }
	
	function showMessage(){ $msg.fadeIn(200); $msg.animate({ top: "-36px" },200); $msg.find("a").fadeIn(200); }
	function hideMessage(){ $msg.fadeOut(100); $msg.find("a").fadeOut(100); }
	function resetMessage(){ $msg.css({ top: "-72px" },200); $msg.find("a").hide(); }
	
}

function showLittleLogin(){

	var $form = $("#little_login");
	var $email = $("#little_email");
	var $password = $("#little_password");

	if ($email.val() == "") $email.focus();
	else $password.select();

	$form.css({ bottom: "0px" });
	$form.find(":input").attr("tabindex","0");
	
	$('html,body').animate({scrollTop: 0}, 250);

	
}

function initOverlay(){
	
	$("body").prepend('<div id="shade"><div id="oframe"></div></div>');
	$("#oframe").append('<div id="otop"></div><div id="omid"><div id="overlay"></div></div><div id="obtm"></div>');
	
	$.preload("/img/o/otop.png","/img/o/obtm.png","/img/o/ob.png","/img/o/oclose.gif","/img/loading.gif");
	
	/* Close button */
	$("#otop").append('<a id="oclose" href="#"></a>');
	$("#oclose").bind('click',function(){ hideOverlay(); });
	$(document).bind('keydown',function(e){
		var k = e.charCode || e.keyCode || window.event.keyCode || 0;
		if (k == 27 && $("#overlay").is(":visible")) hideOverlay();
	});
	
}

function initCheckboxes() {

    $("input:checkbox").each(function(){
        if ($(this).val() == 1) this.checked = true;
        else this.checked = false;
    });
    
    $("input:checkbox").bind("click", function(){
        if ($(this).val() == 1) $(this).val("0");
        else $(this).val("1");
    });
    
}

function checkAlert(){
	
	$.post('/ajax/alerts.php',function(ret){
//		alert(ret)
		if (ret != 'false' && ret != '') {
			var ins = '<div class="alert">' + ret + '<button id="hide_alert" type="button" class="hide"><div>Hide</div></button></div>';
			$("#header").after(ins);
			displayAlert();
		}
	},"text")
	
}

function displayAlert(){
	$("div.alert").show();
	$("#hide_alert").bind('click',function(){
		$.post('/ajax/alerts-clear.php',function(){
			$(".alert").slideUp(400, function(){ $(this).remove(); }); });
		return false;
	})
}

function loadLoggedIn(){
	
	$("#nav").remove();
	$("#little_login").after('<div id="user_wrap"></div>').fadeOut(function(){ $(this).remove(); });
	$("#user_wrap").css("height",0).load('/ajax/userbox.php',function(){ $(this).animate({ height: "100%", opacity: 1 },800); })
	
	if ($("body").attr("id") == "question") {
		$("#poll_settings_account").fadeOut(function(){ $(this).remove(); });
		$("#poll_settings_account_info").fadeOut(function(){ $(this).remove(); });
		$("#poll_settings_shade").fadeOut(function(){ $(this).remove(); });
		$("#main p:first").html($("#main p:first").html().substring(0,$("#main p:first").html().length-45)+".");
	} else if ($("body").attr("id") == "response") {
		window.location.reload();
	}
	
}

function loadOverlay(t,u,v){
	
	$.post(u,v,function(r){
		
		$("#overlay").append(r);
		
			$("#shade").fadeIn(200,function(){
				$("#oframe").fadeIn(200); });
			
			// remove loading indicator, whereever it is
			$(".loading").fadeOut(function(){ $(this).remove(); });
			
			if (t == 'newpoll') {
				$(document).unbind('keydown');
				bindOverlayButtons(t);
			}
		
	})	

}

function hideOverlay(){
	
	$("#shade").fadeOut(400,function(){
		$("#overlay").empty();
	});
	
}

function bindOverlayButtons(t) {
	
	if (t == 'newpoll') {
		
		pollurl = $("#overlay .poll a").text();
        //alert(pollurl);
		
		$("#overlay button.rarr").bind('click',function(){
			location.href = pollurl;
		})
		
		$("#close_overlay").bind('click',function(){
			hideOverlay(); return false;
		})
		
		// Above this line is working, below this line should be working...
		
/*		var clip = new ZeroClipboard.Client();
	
		var text = "";
    	
    	clip.addEventListener( 'mouseDown', function(){
			clip.setText( $('#polllink').text() ); });
    	
    	clip.glue( 'polllink-btn' ); */
		
	}
	
}

jQuery.fn.suggest = function(label) {
	return this.each(function(){

		var $ipt = $(this);
		$ipt.parent().prepend('<div class="suggest">'+label+'</div>');

		var $sug = $ipt.parent().find("div.suggest");
		$sug.css("opacity",0).bind('click',function(){ $ipt.focus(); })
		
		setTimeout(function(){ if ($ipt.val() != '') $sug.hide(); else $sug.animate({ opacity: 1 },200) },150);
		setTimeout(function(){ if ($ipt.val() != '') $sug.hide(); },300);
		
		$ipt.bind('keydown',function(e){
				var k = e.charCode || e.keyCode || window.event.keyCode || 0;
				if ((k >= 48 && k <= 90) || (k >= 96 && k <= 111) || k == 8 || k == 27) $sug.hide(); })
			.bind('keyup',function(e){
				var k = e.charCode || e.keyCode || window.event.keyCode || 0;
				if ($(this).val() == '' && k != 8 && k != 27) $sug.fadeIn(200); })
			.bind('blur',function(){ if ($(this).val() == '') $sug.fadeIn(200); });
		
	});
};

jQuery.fn.makeToggle = function(drawer,open_callback,shut_callback,init_state) {

	var $pull = this;
	var $drawer = $(drawer);
	
	if (init_state == null) init_state = "closed";
	
	if (init_state == "open") {
		$drawer.show();
	} else {
		$drawer.hide();
	}
	
	$pull.addClass("toggle");

	this.each(function(){
		
		if ($drawer.is(":hidden")) $pull.addClass('closed');
		else $pull.addClass('open');
		
		$pull.bind('click',function(){
//			alert($pull.attr("class"));
			if ($pull.hasClass("closed")) openDrawer();
			else shutDrawer();
			return false;
		})
		
	});
		
	function openDrawer(){
		if (open_callback) open_callback();
		$drawer.slideDown(400);
		$pull.addClass("open").removeClass("closed");
	}
		
	function shutDrawer(){
		if (shut_callback) shut_callback();
		$drawer.slideUp(400);
		$pull.addClass("closed").removeClass("open");
	}

};

jQuery.preload = function(){
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};





