/*--------------------------------------------------

	Ehavior  Q&A System
	Author:  Shaun Shull (shaun at usweb)
	Company: USWeb (usweb.com)

----------------------------------------------------*/

/* cookie plugin */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* load core functions */
function ehaviorloadcss(cssfile) { var obj = document.createElement("link"); obj.setAttribute("rel", "stylesheet"); obj.setAttribute("type", "text/css"); obj.setAttribute("href", cssfile); document.getElementsByTagName("head")[0].appendChild(obj); }
ehaviorloadcss("/static/css/questions.css");

/* load after document */
$(document).ready(function(){
	
	// set container div
	var cont = "#ehavior";
	
	// settings
	var s = {
		dir   : "/lib/ehavior/",
		div   : cont,
		head  : cont+" .header",
		addb  : cont+" .header .buttons #addbutton",
		modb  : cont+" .header .buttons #modbutton",
		tool  : cont+" .tool",
		lwrap : cont+" #logwrap",
		wlog  : cont+" .login",
		comm  : cont+" .comments",
		iadb  : "/static/img/qaadd.gif",
		iadbo : "/static/img/qaadd2.gif",
		imod  : "/static/img/mod.gif",
		load  : "/static/img/loading.gif",
		fbdir : "/lib/facebook/",
		fblog : cont+" .tool .fblogin",
		iblog : false
	};
	
	// check for isblog
	if(typeof isblog != "undefined") {
		s.iblog = isblog;
		s.iadb  = "/static/img/rqaadd.gif";
		s.iadbo = "/static/img/rqaadd2.gif";
	}
	
	// set main div
	$(s.div).show();
	
	// check for cookie library
	//$.getScript("/lib/ehavior/cookie.js", function() {

		// add header
		$(s.head).html(cdiv('title',$(s.head).text()) + cdiv('buttons',' <img src="'+s.iadb+'" id="addbutton" alt="" />'));
		loadheader();
		
		// made add button clickable
		$(s.addb).click(loadlogin);
		
		// load questions
		$(s.comm).load(s.dir+"questions.view.php?url="+location.href, function(){
			loadreply();
			loadprofile();
		});
		
		// clear floats
		cfloat(s.head);
		
	// end cookie load function
	//});
	
	/* core functions */
	function cdiv(c,s) { var str = '<div class="'+c+'">'+s+'</div>'; return str; }
	function cfloat(id) { $(id).append('<div class="clear"></div>'); }
	
	/* tag functions */
	
	function loadeh() {
	
		$("#ehctab").click(function(){
			cleanTabs();
			$(this).parent().addClass('active');
			loadEhaviorComments();
		});
		
		$("#ehttab").click(function(){
			cleanTabs();
			$(this).parent().addClass('active');
			loadEhaviorTags();
		});
		
		loadEhaviorComments();
		loadTagForm();
		
	}
	
	function cleanTabs() {
		$('#ehnav li').removeClass('active');
	}
	
	function loadEhaviorComments() {
		$("#ehavior").show();
		$("#ehtags").hide();
	}
	
	function loadEhaviorTags() {
		$("#ehavior").hide();
		$("#ehtags").show();
	}
	
	loadeh();
	
	
	function loadTagForm() {
		if ($("#tagheader").html() == null || $("#tagheader").html() == "undefined" || $("#tagheader").html() == '') {
			$("#ehtags").html('<div id="tagheader" class="header"><input type="text" name="tagbox" id="tagbox" /> <input type="button" id="tagbut" value="Add Tag" /></div><div id="tagtext"><span style="display:block;padding:15px 10px;"></span></div>');
			$("#tagbut").click(function() {
				addTag();
			});
		}
	}
	
	function addTag() {
		if ($("#tagtext").html() != '') {
			$("#tagtext").html('');
		}
		if ($("#tagbox").val() != '') {
			$("#ehtags").append('<div class="comment"><a href="/tag/'+escape($("#tagbox").val())+'">'+$("#tagbox").val()+'</a></div>');
			$.ajax({
			  type: "POST",
			  url: s.dir+"tag.logic.php",
			  data: "url="+escape(location.href)+"&tag="+$("#tagbox").val(),
			  success: function(html){}
			});
		}
	}
	
	
	/* system function library */
	
	function loadheader() {
		if ($.cookie('admin') != null) {
			if (!$(s.modb).length) {
				$(s.head+" .buttons").prepend('<img src="'+s.imod+'" id="modbutton" alt="" />');
				loadmoderate();
			}
		} else {
			if ($(s.modb).length) $(s.modb).remove();
			if ($(".removebut").length) $(".removebut").remove();
		}
	}
	
	function loadprofile() {
		$(s.comm+" .profilebut").click(function(e){
			e.preventDefault();
			var id = $(this).attr("rel");
			profile(id);
		});
		loadfbalone();
	}
	
	function loadmoderate() {
		if ($.cookie('admin') != null) {
			$(s.modb).click(function(e){
				e.preventDefault();
				moderate();
			});
		}
	}
	
	function loadmodbuttons() {
		$(s.comm+" .removebut").click(function(e){
			e.preventDefault();
			var id = $(this).attr("rel");
			var isreply = false;
			if ($(this).parent().parent().attr("class") == "response") isreply = true;
			remove(id, isreply);
		});
		$(s.comm+" .approvebut").click(function(e){
			e.preventDefault();
			var id = $(this).attr("rel");
			approve(id);
		});
	}
	
	function loadlogin() {
		if ($.cookie('user') != null) {
			loadcomment();
		} else {
			$(s.tool).load(s.dir+"login.view.php", function(){
				cfloat(s.tool);
				if ($(s.tool).is(":hidden")) {
					$(s.addb).attr("src", s.iadbo);
					$(s.tool).slideDown(loadfacebook);
				} else {
					loadfacebook();
				}
				$(s.wlog+" #loginform").submit(login);
				$(s.wlog+" #signupbut").click(function(e){
					e.preventDefault();
					loadsignup();
				});
				$(s.addb).unbind();
				$(s.addb).click(closetool);
			});
		}
	}

	function loadfacebook() {
		$(s.fblog).animate({opacity: 1.0}, 2000).html('<iframe id="fbframe" src="'+s.fbdir+'login.htm" borderframe="0" frameborder="no" scrolling="no"></iframe>');
		$("#fbloggedin").click(function(){
			loadcomment();
		});
	}

	function loadcomment() {
		if ($.cookie('user') != null) {
			$(s.tool).load(s.dir+"comment.view.php", function(){
				logout();
				cfloat(s.tool);
				if ($(s.tool).is(":hidden")) {
					$(s.addb).attr("src", s.iadbo);
					$(s.tool).slideDown(function(){
						$(s.addb).unbind();
						$(s.addb).click(closetool);
						loadfbalone();
					});
				} else {
					loadfbalone();
				}
				$(s.tool+" #commentform").submit(comment);
				$(s.tool+" #commentphoto").click(loadupload);
				$(s.tool+" #url").val(location.href);
			});
		}
	}

	function loadsignup() {
		$(s.tool+" p").html('Please fill out the required fields below to create an account.');
		$(s.wlog).load(s.dir+"signup.view.php", function(){
			$(s.wlog+" #signupform").submit(signup);
			$(s.wlog+" #cancel").click(function(e){
				e.preventDefault();
				loadlogin();
			});
		});
	}
	
	function loadupload() {
		if ($(s.tool+" #upload").is(":visible")) {
			$(s.tool+" #upload").html('Closing upload form ...').slideUp();
		} else {
			$(s.tool+" #upload").html('Loading upload form ...').slideDown("slow", function(){
				$(s.tool+" #upload").html('<iframe src="'+s.dir+'upload.view.php" width="100%" height="50" scrolling="no" frameborder="0"></iframe>');
			});
		}
	}
	
	function loadreply() {
		$(s.comm+" .comment .replybut").click(function(e){
			e.preventDefault();
			if ($(this).text()=='reply') { $(this).text('close'); } else { $(this).text('reply') }
			var id = $(this).attr("rel");
			$("#reply"+id).load(s.dir+"reply.view.php", function(){
				$("#reply"+id).slideToggle();
				if ($.cookie('user') != null) {
					$("#reply"+id+" .replyform").submit(function(){
						reply(id);
						return false;
					});
				} else {
					$("#reply"+id).html('<p>We\'re sorry, you must be logged in to reply.</p>');
					setTimeout('$("#reply'+id+'").slideUp("slow")', 1500);
					$("#comm"+id+" .replybut").text('reply');
				}
			});
		});
		$(s.comm+" .comment .viewbut").click(function(e){
			e.preventDefault();
			if ($(this).text().indexOf("view") != -1) { $(this).text($(this).text().replace("view", "close")); } else { $(this).text($(this).text().replace("close", "view")); }
			var id = $(this).attr("rel");
			$("#replies"+id).load(s.dir+"replies.view.php?id="+id, function(){
				$("#replies"+id).slideToggle();
				loadprofile();
				$(s.comm+" .upbut").click(function(e){
					e.preventDefault();
					$(this).parent().html('Thanks!').fadeOut('slow');
				});
				$(s.comm+" .downbut").click(function(e){
					e.preventDefault();
					$(this).parent().html('Thanks!').fadeOut('slow');
				});
				if ($.cookie('admin') != null) {
					$(".response", $(this)).each(function(){
						if (!$(".removebut", $(this)).length) {
							$(".commoptions", $(this)).append('<a href="#" class="removebut" rel="'+$(this).attr("rel")+'">remove</a>');
							loadmodbuttons();
						}
					});
				}
			});
		});
		$(s.comm+" .upbut").click(function(e){
			e.preventDefault();
			$(this).parent().html('Thanks!').fadeOut('slow');
		});
		$(s.comm+" .downbut").click(function(e){
			e.preventDefault();
			$(this).parent().html('Thanks!').fadeOut('slow');
		});
		if ($.cookie('admin') != null) {
			$(".comment", s.comm).each(function(){
				if (!$(".removebut", $(this)).length) {
					$(".commoptions", $(this)).append('<a href="#" class="removebut" rel="'+$(this).attr("rel")+'">remove</a>');
					loadmodbuttons();
				}
			});
		}
	}

	function closetool() {
		if ($(s.fblog)) $(s.fblog).empty();
		if ($(s.tool).is(":visible")) {
			$(s.addb).attr("src", s.iadb);
			$(s.tool).slideUp("slow", function(){
				$(s.addb).click(loadlogin);
			});
		}
	}
	
	function signup() {
		$(s.tool+" p").html('<img src="'+s.load+'" alt="" />&nbsp;Creating new USWeb account ...');
		$.ajax({
		  type: "POST",
		  url: s.dir+"signup.logic.php",
		  data: "email="+$(s.tool+' #email').val()+"&password="+$(s.tool+' #password').val()+"&nick="+$(s.tool+' #nick').val(),
		  success: function(html){
		    switch(html) {
		    	case 'true':
						$(s.tool).load(s.dir+"comment.view.php", loadcomment);
		    	break;
		    	case 'false':
		    		$(s.tool+" p").html('A problem occured. All fields must be filled in and only one account is allowed per email. Please double check your fields and try again.');
		    	break;
		    }
		  }
		});
		return false;
	}

	function login() {
		$(s.tool+" p").html('<img src="'+s.load+'" alt="" />&nbsp;Logging into USWeb ...');
		$.ajax({
		  type: "POST",
		  url: s.dir+"login.logic.php",
		  data: "email="+$(s.tool+' #email').val()+"&password="+$(s.tool+' #password').val(),
		  success: function(html){
		    switch(html) {
		    	case 'true':
		    		loadheader();
						$(s.tool).load(s.dir+"comment.view.php", function(){
							loadcomment();
							if ($.cookie('admin') != null) {
								$(".comment", s.comm).each(function(){
									if (!$(".removebut", $(this)).length) {
										$(".commoptions", $(this)).append('<a href="#" class="removebut" rel="'+$(this).attr("rel")+'">remove</a>');
										loadmodbuttons();
									}
								});
							}
						});
		    	break;
		    	case 'false':
		    		$(s.tool+" p").html('We\'re sorry, this account was not found.');
		    	break;
		    }
		  }
		});
		cfloat(s.tool);
		return false;
	}

	function comment() {
		$(s.tool+" #status").html('<img src="'+s.load+'" alt="" />&nbsp;Submitting data to USWeb ...');
		var curl = $(s.tool+' #url').val();
		var cque = $(s.tool+' #comment').val();
		$.ajax({
		  type: "POST",
		  url: s.dir+"comment.logic.php",
		  data: "url="+curl+"&comment="+cque,
		  success: function(html){
		    switch(html) {
		    	case 'true':
		    		$(s.tool+' #comment').val('');
						$(s.tool+" #status").html('Thank you! We will review your submission soon.');
						if ($(s.tool+' #fbpop')) {
							loadfb(curl, cque);
		    		}
		    	break;
		    	case 'false':
		    		$(s.tool+" #status").html('A problem occured. All fields must be filled in. Please double check your fields and try again.');
		    	break;
		    }
		  }
		});
		return false;
	}
	
	function reply(id) {
		$("#reply"+id+" .status").html('<img src="'+s.load+'" alt="" />&nbsp;Submitting reply to USWeb ...');
		$.ajax({
		  type: "POST",
		  url: s.dir+"comment.logic.php",
		  data: "parent="+id+"&comment="+$("#reply"+id+" .replymessage").val(),
		  success: function(html){
		    switch(html) {
		    	case 'true':
						loadfb(location.href, $("#reply"+id+" .replymessage").val());
		    		$("#reply"+id+" .replymessage").val('');
						$("#reply"+id+" .status").html('Thank you! Your information has been received, it will be visible on the website after moderation.');
		    	break;
		    	case 'false':
		    		$("#reply"+id+" .status").html('A problem occured. All fields must be filled in. Please double check your fields and try again.');
		    	break;
		    }
		  }
		});
	}
	
	function profile(id) {
		$(s.comm).load(s.dir+"profile.view.php?id="+id, function(){
			loadreply();
			loadprofile();
			$(".reset", $(this)).click(function(e){
				e.preventDefault();
				$(s.comm).load(s.dir+"questions.view.php?url="+location.href, function(){
					loadreply();
					loadprofile();
				});
			});
		});
	}
	
	function moderate() {
		$(s.comm).load(s.dir+"moderate.view.php", function(){
			loadprofile();
			loadmodbuttons();
			$(".reset", $(this)).click(function(e){
				e.preventDefault();
				$(s.comm).load(s.dir+"questions.view.php?url="+location.href, function(){
					loadreply();
					loadprofile();
				});
			});
		});
	}

	function remove(id, isreply) {
		$.ajax({
		  type: "POST",
		  url: s.dir+"remove.logic.php",
		  data: "id="+id,
		  success: function(html){
		    switch(html) {
		    	case 'true':
		    		if (!isreply) {
		    			$("#comm"+id).slideUp("slow").empty();
		    			if ($("#reply"+id).length) $("#reply"+id).slideUp("slow").empty();
		    			if ($("#replies"+id).length) $("#replies"+id).slideUp("slow").empty();
		    		} else {
		    			if ($("#response"+id).length) $("#response"+id).slideUp("slow").empty();
		    		}
		    		loadmoderate();
		    	break;
		    }
		  }
		});
	}
	
	function approve(id) {
		$.ajax({
		  type: "POST",
		  url: s.dir+"approve.logic.php",
		  data: "id="+id,
		  success: function(html){
		    switch(html) {
		    	case 'true':
		    		$("#comm"+id).slideUp("slow").empty();
		    		loadmoderate();
		    	break;
		    }
		  }
		});
	}

	function logout() {
		$(s.tool+" #logout").unbind();
		$(s.tool+" #logout").click(function(e){
			e.preventDefault();
			$.ajax({
			  type: "GET",
			  url: s.dir+"logout.logic.php",
			  success: function(html){
					$.cookie('user', null);
					$.cookie('nick', null);
					$.cookie('photo', null);
					$.cookie('admin', null);
					$.cookie('fb', null);
					loadlogin();
					loadheader();
					$(".reply").each(function(){
						if ($(this).is(":visible")) {
							$(this).hide();
							$(".replybut").text('reply');
						}
					});
			  }
			});
		});
	}
	
	function loaddialog(url,question) {
		FB.ensureInit(function(){
			FB.Connect.ifUserConnected(function(){
				FB.Connect.showFeedDialog(75432667170, {"question":question, "qurl":url, "images":[{"src":"http://usw-img0.com/static/img/usweb.gif","href":"http://www.usweb.com"}]});
			});
		});
	}
	
	function loadfb(url,question) {
		if ($.cookie('fb') != null) {
			FB.init("c83bea704c8f79607f5f048c34111c10", "/lib/facebook/xd_receiver.htm", {"ifUserConnected":loaddialog(url,question)});
		}
	}
	
	function loadfbalone() {
		FB.init("c83bea704c8f79607f5f048c34111c10", "/lib/facebook/xd_receiver.htm");
	}
	

});

function fblogin() {
	$("#fbloggedin").click();
}
