var slidein=0;

function isset(varname){
  return( (typeof(window[varname])!='undefined' && typeof(window[varname])!='object') );
}

function cursor(type){
	if(type=="wait"){
		$('*').css('cursor','wait'); 
	}else{
		$('*').css('cursor','auto'); 
		$('a').css('cursor','pointer'); 
	}
}

$().ready(function(){  

	//get new huw count
	setInterval(function(){
		$.getJSON("/ajax/get_new_huw_count/", {url:window.location.href} ,function(data){
			if($('span#new_huw_count').length>0){
				var last=$('span#new_huw_count').html().replace("(","").replace(")","");
				if(last=="") last=0;
				var current=data.count.replace("(","").replace(")","");
				if(current=="") current=0;
				if( parseInt(current) > parseInt(last) ){
					if(!(isset("arg") && arg=="mine")){
						sound();
					}
				}
				$('span#new_huw_count').html(data.count);
			}
		});
	},10000);

	
	//bouncer
	setTimeout(bounce,500);
	var pos=0;
	var posdy=-5;
	function bounce(){
		pos+=posdy;
		posdy++;
		$('span#new_huw_count').css("position","relative").css("top",pos+"px");
		if(pos==0) posdy=-5;
		setTimeout(bounce,100);
	}
	

    $('span.timeago').timeago();
		
	// theme
	$('select#theme').change(function(){
		$.getJSON("/ajax/theme/" + $('select#theme option:selected').val() + "/", function(data){
			window.location.reload();
		})
	});
	
	//////////////
	/// invite ///
	//////////////
	
	$('select#invite').change(function(){
		var id=$('select#invite option:selected').val();
		$.getJSON("invite/" + id + "/", function(data){
			//alert(data.result);
			//var old=$('select#invite option[value=]').html();
			$('select#invite option[value='+id+']').html("...invited!   ");
			//$('select#invite').val("");
			//$('select#invite').blur();
			setTimeout(function(){
				$('select#invite option[value='+id+']').remove();
			},3000);
		})
	});

	//////////////
	/// avatar ///
	//////////////
	
	$('input#upload_avatar').click(function(){
		$("#dialog").html('<p>The image will be automatically resized for you.</p><form method="post" enctype="multipart/form-data" action="/ajax/avatar/"><input type="file" name="avatar" onChange="$(\'#dialog form\').submit();"></form>');
		$("#dialog").dialog({
			width: 500,
			minHeight: 100,
			autoOpen: true,
			modal: true,
			title: 'Select an image...',
			close: function(){
				$("#dialog").dialog("destroy");
			}
		});

		$("#dialog form").ajaxForm({dataType:"json", beforeSubmit:function(){
			cursor("wait");
	        $('#dialog form').hide();
	        $('#dialog p').html('Uploading, please wait....');
	    } , success:function(data){
			cursor("normal");
	        if(data.result!='ok'){
				alert(data.result);
			}
			window.location.reload();
	    } });

	});

	//audio chooser
	$("select#audio").change(function(){
		var fname=$("select#audio option:selected").val();
		if (fname && mySound!=null) {
			soundManager.destroySound('tmpSound');
			var tmpSound = soundManager.createSound({
				id: 'tmpSound',
				url: '/audio/' + fname
			});
			tmpSound.play();
		}
	});

	
	////////////////////////
	/// form submissions ///
 	////////////////////////
	
    //submit huw form data
	$('form#huw').ajaxForm({beforeSubmit:function(){
		if( $('form#huw input.q').val()=='who ' ) return false;
		cursor("wait");
		loading=true;
		$('form#huw input').attr('disabled','disabled');
	} , success:function(data){
		cursor("normal");
		if(data.result=='login'){
			login({
				action: "submit",
				value: "form#huw"
			},0);
		}else if(data.result=='ok'){
			window.location.href=data.url;
		}
	}, dataType:'json' });
	
    //submit post form data
    $('form#post').ajaxForm({beforeSubmit:function(){
		if( $('form#post textarea').val()=='') return false;
		cursor("wait");
		loading=true;
        $('form#post input').attr('disabled','disabled');
    } , success:function(data){
		cursor("normal");
        if(data=='login'){
            login( {
				action: "submit",
				value: "form#post"
			},0);
        }else{
			if(refresh){
				window.location.reload();
			}
			loading=false;
			clear=true;	
            loadNewPosts();
        }
    } });

	var front_textarea_clear=false;
    $("div#front textarea").focus(function() {
		if(front_textarea_clear==false){
			$("div#front input").removeAttr("disabled");
			$(this).val('').css("color","#333");
			front_textarea_clear=true;
		}
    });
	
	//prevent click when ... showing or empty
    $("form#search input[type=image]").click(function(e) {
        if( $("form#search input.q").val() =="") {
            e.preventDefault();
        }
    });
    $("div#front input[type=image]").click(function(e) {
        if( $("div#front textarea").val() =="") {
            e.preventDefault();
        }
    });
	
	/////////////
	/// LOGIN ///
	/////////////

	if(isset("members")){
		login( {
			action: "reload"
		},1 );	
	}

	/////////////
	/// debug ///
	/////////////
	
	/*if (isset("dev")) {
		setInterval(function(){
			$("#debug1").html("<strong>**DEV SITE**</strong> : "+ (isset("last_topic_updated")?last_topic_updated:'null') + " : " + (isset("last_post_id")?last_post_id:'null') +" : " +loading );
		}, 100);
	}*/

	/////////////////////
    // load new posts ///
    /////////////////////
	
	setInterval(function(){loadNewPosts();},3000);
   
	$.ajaxSetup({
        error:function(){
            loading=false;
			cursor("normal");
        }
    });

});


///////////////////
/// PM function ///
///////////////////

function pm(nick){
	$.getJSON("/ajax/user_id/",function(data){
	    if(data.result=='login'){
       		login( {
				action: "pm",
				value: nick
			},0 );				
		}else{
			$("#dialog").html('<form action="/ajax/pm/'+nick+'/" method="get"><input type="text" style="width:99%;margin:20px 0" name="subject"/><input style="float:right;" type="submit" value="OK"/><div style="clear:both"></form>');
			$("#dialog").dialog({
				width: 500,
				maxHeight: 800,
				autoOpen: true,
				modal: true,
				title: 'Enter subject of chat:',
				close: function(){
					$("#dialog").dialog("destroy");
				}
			});
			$("#dialog form").ajaxForm({dataType:"json", beforeSubmit:function(){
				if($("#dialog form input[type=text]").val()=="")
					return false;
				cursor("wait");
				$('#dialog form').hide();
				$('#dialog').html('<p>Loading, please wait....</p>');
			} , success:function(data){
				cursor("normal");
				if(data.result!='ok'){
					alert(data.result);
				}else{
					window.location.href=data.url;
				}
			} });
		}
	});
}


/////////////
/// LOGIN ///
/////////////

function signin(){
	login( {
		action: "reload"
	},1 );	
}

var after_login="";
function do_after_login(){
	if(after_login){
		refresh=true;
		if (after_login.action == "submit") {
			$(after_login.value).submit();
		}else if (after_login.action == "click") {
			$(after_login.value).click();
		}else if (after_login.action == "reload") {
			window.location.reload();							
		}else if (after_login.action == "location") {
			window.location.href=after_login.value;	
		}else if (after_login.action == "pm") {
			pm(after_login.value);					
		}else if (after_login.action == "handsup") {
			handsup(after_login.value);					
		}
	}
}

function login(retry,tab){
	cursor("wait");
	after_login=retry;
	
    $('form#post input').removeAttr('disabled');
    $('form#huw input').removeAttr('disabled');
    $("#dialog").load("/account/signin/",function(){
		$("#dialog").dialog({
			width: 600,
			maxHeight: 800,
			minHeight: 200,
			autoOpen: true,
			modal: true,
			title: 'Choose a name or sign in...',
			close: function(){
				$("#dialog").dialog("destroy");
			}
		});
		cursor("normal");

		$("#dialog #reset").hide();
		if(tab==0){
			$("#dialog #signin").hide();	
		}else{
			$("#dialog #signup").hide();
		}
		
		$("#dialog a.signin").click(function(e){
			e.preventDefault();
			$("#dialog #signin").show();
			$("#dialog #signup").hide();
		});
		$("#dialog a.signup").click(function(e){
			e.preventDefault();
			$("#dialog #signin").hide();
			$("#dialog #signup").show();
		});
		$("#dialog a.reset").click(function(e){
			e.preventDefault();
			$("#dialog #signin").hide();
			$("#dialog #signup").hide();
			$("#dialog #reset").show();
		});
		
	    //name avilability checker
	    $("#dialog input#name").keyup(function(){
			$("input#name").val($("input#name").val().replace(" ","_"));
	        $.getJSON("/account/name/check/",{name:$("input#name").val()},function(data){
	            $("#status").html(data.text);
	            if(data.ok){
					$("#status").css("color","#000");
	                $("form.signup input[type=submit]").show().removeAttr('disabled');
	            }else{
					$("#status").css("color","#f00");
	                $("form.signup input[type=submit]").hide().attr('disabled','disabled');
	            }
	        });
	    });

	    //name selecion ok button
	    $("#dialog form.signup").ajaxForm({success:function(data){
			if (data.ok) {
		        $("#dialog").dialog('close');
				do_after_login();
			}else {
				$("#status").html(data.text);
			 	$("div#dialog input[type=submit]").hide().attr('disabled', 'disabled');
			}
		} , dataType: 'json' });	
		
	    //signin button		
	    $("#dialog form.signin").ajaxForm({success:function(data){
			if (data.ok) {
		        $("#dialog").dialog('close');
				do_after_login();
			}else {
				$("#login_error").html(data.text).slideDown(300,function(){
					setTimeout( function(){ $("#login_error").slideUp(300); } , 2000);
				});
			}
		} , dataType: 'json' });

	    //reset button		
	    $("#dialog form.reset").ajaxForm({success:function(data){
	      if (data.ok) {
		$("#reset_ok").html(data.text).slideDown(300,function(){
		  setTimeout( function(){ $("#reset_ok").slideUp(300);$("#dialog").dialog('close'); } , 2000);
		});
	      }else{
		$("#reset_error").html(data.text).slideDown(300,function(){
		  setTimeout( function(){ $("#reset_error").slideUp(300); } , 2000);
		});
	      }
	    } , dataType: 'json' });			
	});	
}


/////////////
/// audio ///
/////////////

//init sound manager
soundManager.url = '/audio/';
soundManager.debugMode = false;
var mySound;
soundManager.onload = function() {
	mySound = soundManager.createSound({
	    id: 'mySound',
	    url: '/audio/'+audio
	  });
}

function sound(){
	if (audio && mySound!=null) {
		mySound.play();
	}
}

/////////////////////
// load new posts ///
/////////////////////

setInterval(function(){loadNewPosts();},3000);
var loading=false;
var clear=false;
var refresh=false;
function loadNewPosts(){
    if(loading) return;
    loading=true;
    if(isset("last_post_id")){
        $.getJSON("new_posts/?last_id="+last_post_id,function(data){
            last_post_id=data.id;
            $("div.posts").prepend("<div style='display:none' id='slidein"+slidein+"'>"+data.html+"</div>");
            $("#slidein"+slidein+" span.timeago").timeago();
			if (!clear) {
				sound();
			}
            $("#slidein"+slidein).slideDown(400,function(){
                if(clear){
                    $('form#post textarea').val("");
                    $('form#post input').removeAttr('disabled');
					clear=false;
                }
            });
            slidein++;
            loading=false;
            loadNewPosts();
        });
    }
    if(isset("last_topic_updated")){
        $.getJSON("/new_topics/?last_updated="+last_topic_updated+(isset("arg")?"&arg="+arg:"")+(isset("private")?"&private":""),function(data){
            last_topic_updated=data.updated;
			$("#topic"+data.id).attr("id","slideout");
			$("#slideout").slideUp(400,function(){
				$("#slideout").remove();
			});
            $("div.topics").prepend("<div style='display:none' id='slidein"+slidein+"'>"+data.html+"</div>");
            $("#slidein"+slidein+" span.timeago").timeago();
			$("#slidein"+slidein+" a.unwatch").click(function(e){unwatch(e,this);});
			$("#slidein"+slidein+" a.handsup").click(function(e){handsup(e,this);});
			$("#slidein"+slidein+" a.watch").click(function(e){watch(e,this);});
			if (!clear) {
				sound();
			}
            $("#slidein"+slidein).slideDown(400,function(){
                if(clear){
                    $('form#huw input').removeAttr('disabled');
                    $('form#huw input.who').val("");
					clear=false;
                }
            });
            slidein++;
            loading=false;
            loadNewPosts();
        });
    }
}

//////////////////////////////
/// watch/stop watch links ///
//////////////////////////////

//stop watching
function unwatch(id){
	$.getJSON("/ajax/unwatch/" + id + "/", function(data){
		if (isset("arg") && arg=="mine") {
			$("#topic" + id).slideUp(400, function(){
				$("#topic" + id).remove();
			});
		}else{
		$("#topic"+id+" .unwatch").fadeOut(function(){
			$("#topic"+id+" .watch").fadeIn();				
		});
		}
	})
}

//watch
function watch(id){
	$.getJSON("/ajax/watch/" + id + "/", function(data){
		$("#topic"+id+" .watch").fadeOut(function(){
			$("#topic"+id+" .unwatch").fadeIn();				
		});
	})
}

//handsup
function handsup(id){
	$.getJSON("/ajax/handsup/" + id + "/", function(data){
		if(refresh)
			window.location.reload();
		if (data.result == 'ok') {
			$("#topic" + id + " .handsdown").fadeOut(300, function(){
				$("#topic" + id + " .handsup").fadeIn();
				var spos = $("#topic" + id + " .hand_count").html().indexOf(" ");
				var count = $("#topic" + id + " .hand_count").html().substr(0, spos);
				count++;
				$("#topic" + id + " .hand_count").html(count + " hand" + (count == 1 ? '' : 's') + " up");
			});
		}else if(data.result=='login'){
       		login( {
				action: "handsup",
				value: id
			},0 );				
		}
	})
}

//handsdown
function handsdown(id){
	$.getJSON("/ajax/handsdown/" + id + "/", function(data){
		$("#topic"+id+" .handsup").fadeOut(300,function(){
			$("#topic"+id+" .handsdown").css("display","block").fadeIn();
			var spos=$("#topic"+id+" .hand_count").html().indexOf(" ");
			var count=$("#topic"+id+" .hand_count").html().substr(0,spos);
			count--;
			$("#topic"+id+" .hand_count").html(count+" hand"+(count==1?'':'s')+" up");
		});
	})
}

//add crowd
function crowd(id){
	$.getJSON("/ajax/add_crowd/" + id + "/", function(data){
		$("span.addcrowd-"+id).fadeOut(300);
	})
}

//del crowd
function dcrowd(id){
	$.getJSON("/ajax/del_crowd/" + id + "/", function(data){
		$("#crowd"+id).slideUp(300);
	})
}

