/**********************************
Mahalo Answers JS Version 1
Sean Jackson
Mahalo.com Inc. 2008
***********************************/

function textCounter(field, cntfield, maxlimit, justCount) {
    if (justCount) {
        cntfield.innerHTML = field.value.length;
    }
    else {
    	if (field.value.length > maxlimit) {
            field.value = field.value.substring(0, maxlimit);
        }
    	else {
    	    var total = maxlimit - field.value.length;
    	    cntfield.innerHTML = total;
    	}
    }
}

function fuzzyTime() {
	var now = new Date();
	var now_ms = now.getTime();
	var offset = now.getTimezoneOffset();
	offset = offset * 60 * 1000;
	
	$(".fuzzy").each(function () {
		var timeString = $(this).attr("timestamp");
		
		if (!timeString) {
			return;
		}
		
		var year = timeString.substring(0,4);
		var month = timeString.substring(4,6);
		var day = timeString.substring(6,8);
		var hour = timeString.substring(8,10);
		var minute = timeString.substring(10,12);
		var second = timeString.substring(12,14);
		
		var newDate = new Date();
		newDate.setFullYear(year);
		newDate.setMonth(month - 1, day);
		newDate.setHours(hour);
		newDate.setMinutes(minute);
		newDate.setSeconds(second);
		
		var ms = newDate.getTime();
		ms -= offset;
		newDate.setTime(ms);
		
		var difference = now_ms - newDate.getTime();
		var dateString = "";
		
		if (difference >= (1000 * 60 * 60 * 24 * 60)) {
			dateString = newDate.toDateString()
		}
		else if (difference >= (1000 * 60 * 60 * 24)) {
			var days = Math.floor(difference / (1000 * 60 * 60 * 24));
			dateString = days + " day";
			if (days != 1) dateString += "s"
			dateString += " ago";
		}
		else if (difference >= (1000 * 60 * 60)) {
			var hours = Math.floor(difference / (1000 * 60 * 60));
			dateString = hours + " hour";
			if (hours != 1) dateString += "s";
			dateString += " ago";
		}
/*		else if (difference < 0) {
			dateString = "In the future.";
		}
*/		else {
			var minutes = Math.floor(difference / (1000 * 60));
			
			if (minutes < 1) {
				dateString = "Less than a minute ago";
			}
			else {
				dateString = minutes + " minute";
				if (minutes != 1) dateString += "s";
				dateString += " ago";
			}
		}
		
		$(this).html(dateString);
	});
}

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;
    }
};

function confirmation(msg, container, width) {
	$(".msgbox").hide();
	
	if (typeof msg != 'undefined') {
		if (typeof container != 'undefined') {
			var containers = [container];
		}
		else {
			var containers = ["message-container","content-left", "content"];
		}
		
		for (var i = 0; i < containers.length; i++) {
			if ($("#"+containers[i])) {
				var offset = $("#"+containers[i]).offset().top - 10;
				
				if (typeof width == 'undefined') {
					var width = 528;
				}
				
				$('<div class="msgbox"><div class="orange-top-container" style="width:' + (width) + 'px;"> <div class="orange-top-div"> <div class="orange-top-corners" style="width:' + (width) + 'px;"> <div class="orange-tl"></div> <div class="orange-tr"></div> </div> <div class="orange-top"> <div class="orange-top-middle">&nbsp;</div> </div> </div> <div class="orange-content" style="width:' + (width-34) + 'px;"><table cellpadding="0" cellspacing="0" class="message-table"><tr><td><img class="success_sprite" src="'+CONTENT_URL+'/content/skins/mahalo/images/clear.gif" alt="" /></td><td class="message-cell">'+
				'<strong>'+msg+'</strong>'+
				'</td></tr></table></div><div class="orange-bottom-div"> <div class="orange-bottom-corners" style="width:' + (width) + 'px;"> <div class="orange-bl"></div> <div class="orange-br">&nbsp;</div> </div> <div class="orange-bottom"> <div class="orange-bottom-middle">&nbsp;</div> </div> </div></div><br /></div>')
				.prependTo("#"+containers[i]);
				
				$('html,body').animate({scrollTop: offset}, 1000);	
				break;
			}
		}
		
	}
}

function error(msg, container, width, dontScroll) {
	$(".msgbox").hide();
	
	if (typeof msg != 'undefined') {
		if (typeof container != 'undefined') {
			var containers = [container];
		}
		else {
			var containers = ["message-container","content-left", "content"];
		}
		
		for (var i = 0; i < containers.length; i++) {
			if (document.getElementById(containers[i])) {
				var container = $("#"+containers[i]);
				
				var offset = container.offset().top - 10;
				
				if (typeof width == 'undefined') {
					var width = 528;
				}
				
			    var html = "<div class='msgbox'>";
			    html += '<div class="orange-top-container" style="width:' + (width) + 'px; margin-left: auto; margin-right: auto;"> ';
			    html += '<div class="orange-top-div"> ';
			    html += '<div class="orange-top-corners" style="width:'+(width)+'px;"> ';
			    html += '<div class="orange-tl"></div> ';
			    html += '<div class="orange-tr"></div> ';
			    html += '</div> ';
			    html += '<div class="orange-top"> ';
			    html += '<div class="orange-top-middle">&nbsp;</div> ';
			    html += '</div> ';
			    html += '</div> ';
			    html += '<div class="orange-content" style="width:'+(width-34)+'px;"> ';
			    html += '<table cellpadding="0" cellspacing="0" style="width:'+(width-34)+'px;"><tr><td> ';
			    html += '<img class="large_warning_sprite" src="'+ CONTENT_URL +'/content/skins/mahalo/images/clear.gif" alt="" /> ';
			    html += '</td><td class="message-cell"> ';
			    html += '<strong> ';
			    html += msg;
			    html += '</strong> ';
			    html += '</td></tr></table> ';
			    html += '</div> ';
			    html += '<div class="orange-bottom-div"> ';
			    html += '<div class="orange-bottom-corners" style="width:'+(width)+'px;"> ';
			    html += '<div class="orange-bl"></div> ';
			    html += '<div class="orange-br">&nbsp;</div> ';
			    html += '</div> ';
			    html += '<div class="orange-bottom"> ';
			    html += '<div class="orange-bottom-middle">&nbsp;</div> ';
			    html += '</div> ';
			    html += '</div> ';
			    html += '</div><br /></div>';
				
				$(html).prependTo(container);
				
				if (!dontScroll) {
				    $('html,body').animate({scrollTop: offset}, 1000);	
				}
				
				break;
			}
		}
	}
}

function pageview(views) {
	var viewsToday = views - startOfDayViews;
	
	var viewString = " (" + views + " view";
	if (views != 1) viewString += "s";
	viewString += ")";
	
	// $("#pageviews").html(viewString);
	
	if (viewsToday <= 500 && viewsToday % 20 == 0) {
		if (viewsToday < 500) {
			confirmation("You just viewed your "+viewsToday+"th page today and earned 1 point.<br />You get 1 point for every 20 pages you view up to 500 pages in a day.");
		}
		else {
			confirmation("Wow, you just viewed your 500th page today and earned 1 point.");
		}
		
		$.post(API_URL+"/answers/award_points/?callback=?", 
			[
				{"name": "action", "value": "pageviews" }, 
				{"name": "meta_id", "value": viewsToday },
				{"name": "key_owner", "value": MAHALO_KEY_OWNER }, 
	            {"name": "access_key", "value": MAHALO_ACCESS_KEY }, 
	           	{"name": "public_key", "value": MAHALO_PUBLIC_KEY }, 
	            {"name": "app_key", "value": MAHALO_APP_KEY }
			], function(data){
		}, "json");
	}
}

function google_ad_request_done(google_ads)
{
    /*
    * Verify that there are actually ads to display.
    */
    var google_num_ads = google_ads.length;
	if (google_num_ads <= 0)
	{
		if(document.getElementById("top_permaafs"))document.getElementById("top_permaafs").style.display = "none";
		if(document.getElementById("best_permaafs"))document.getElementById("best_permaafs").style.display = "none";
		if(document.getElementById("permaafs"))document.getElementById("permaafs").style.display = "none";
		if(document.getElementById("top_narrowafs"))document.getElementById("top_narrowafs").style.display = "none";
		if(document.getElementById("narrowafs"))document.getElementById("narrowafs").style.display = "none";
		return;
	}

  	var top_permaAds = "";   // permalink ad unit html text
  	var best_permaAds = "";   // permalink best answer ad unit html text
  	var top_narrowAds = "";   // narrow ad unit html text
  	var permaAds = "";   // permalink ad unit html text
  	var narrowAds = "";   // narrow ad unit html text

	for(i = 0; i < google_num_ads; i++){
	    
		if (google_ads[i].type=="text"){

   			if(document.getElementById("top_permaafs") && document.getElementById("top_permaafs").style.display != "block"){
       			top_permaAds+='<td style="width:50%;vertical-align:top"><div style="margin-top:0;margin-bottom:.3em;margin-right:1em;">' + 
       			           '<a class="ad-line1-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
       					   '<span class="ad_line1_narrow">' + google_ads[i].line1 + '</span></a><br />' +
       					   '<span class="ad_text_narrow" style="text-decoration:none;">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br />' +
       			           '<a class="ad-url-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
       					   '<span class="ad_url_narrow" style="text-decoration:none;">' + google_ads[i].visible_url + '</span></a></div></td>';

  			} else if(document.getElementById("best_permaafs") && document.getElementById("best_permaafs").style.display != "block"){
      			best_permaAds+='<td style="width:50%;vertical-align:top"><div style="margin-top:0;margin-bottom:.3em;margin-right:1em;">' + 
      			           '<a class="ad-line1-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
                      	   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
                      	   '<span class="ad_line1_narrow">' + google_ads[i].line1 + '</span></a><br />' +
                      	   '<span class="ad_text_narrow" style="text-decoration:none;">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br />' +
                      	   '<a class="ad-url-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
                      	   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
                      	   '<span class="ad_url_narrow" style="text-decoration:none;">' + google_ads[i].visible_url + '</span></a></div></td>';

   			} else if(document.getElementById("permaafs") && document.getElementById("permaafs").style.display != "block"){
       			permaAds+='<td style="width:50%;vertical-align:top;"><div style="margin-top:0;margin-bottom:.3em;margin-right:1em;">' + 
       			           '<a class="ad-line1-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
       					   '<span class="ad_line1_narrow">' + google_ads[i].line1 + '</span></a><br />' +
       					   '<span class="ad_text_narrow" style="text-decoration:none;">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br />' +
       			           '<a class="ad-url-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
       					   '<span class="ad_url_narrow" style="text-decoration:none;">' + google_ads[i].visible_url + '</span></a></div></td>';

  			} else if(document.getElementById("top_narrowafs") && document.getElementById("top_narrowafs").style.display != "block"){
    			top_narrowAds+='<div style="margin-top:0;margin-bottom:.3em;margin-right:1em;">'+
    			           '<a class="ad-line1-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
    					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
    					   '<span class="ad_line1_narrow">' + google_ads[i].line1 + '</span></a><br />' +
    					   '<span class="ad_text_narrow" style="text-decoration:none;">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br />' +
       			           '<a class="ad-url-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
    					   '<span class="ad_url_narrow" style="text-decoration:none;">' + google_ads[i].visible_url + '</span></a></div>';

            } else {
    			narrowAds+='<div style="margin-top:0;margin-bottom:.3em;margin-right:1em;">'+
    			           '<a class="ad-line1-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
    					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
    					   '<span class="ad_line1_narrow">' + google_ads[i].line1 + '</span></a><br />' +
    					   '<span class="ad_text_narrow" style="text-decoration:none;">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br />' +
       			           '<a class="ad-url-link" onmouseover="javascript:window.status=\'' + google_ads[i].url + '\';return true;" ' +
       					   'onmouseout="javascript:window.status=\'\';return true;" ' + 'href="' + google_ads[i].url + '">' +
    					   '<span class="ad_url_narrow" style="text-decoration:none;">' + google_ads[i].visible_url + '</span></a></div>';
            }
	    }
    }

    if (top_permaAds != ""){
        top_permaAds = '<h2 class="ad_heading" style="clear:both;margin-top:0;margin-bottom:2px;"><a class="google_headings" ' +
				  'href="'+ google_info.feedback_url +'">' +
				  'Ads by Google</a></h2><table cellspacing="0" cellpadding="0" style="margin-bottom:6px;">' + top_permaAds + '</tr></table>';
		if(document.getElementById("top_perma_ad_unit"))document.getElementById("top_perma_ad_unit").innerHTML = top_permaAds;
		if(document.getElementById("top_permaafs"))document.getElementById("top_permaafs").style.display = "block";
	}

    if (best_permaAds != ""){
        best_permaAds = '<h2 class="ad_heading" style="clear:both;margin-top:0;margin-bottom:2px;"><a class="google_headings" ' +
				  'href="'+ google_info.feedback_url +'">' +
				  'Ads by Google</a></h2><table cellspacing="0" cellpadding="0" style="margin-bottom:6px;">' + best_permaAds + '</tr></table>';
		if(document.getElementById("best_perma_ad_unit"))document.getElementById("best_perma_ad_unit").innerHTML = best_permaAds;
		if(document.getElementById("best_permaafs"))document.getElementById("best_permaafs").style.display = "block";
	}

    if (permaAds != ""){
          permaAds = '<h2 class="ad_heading" style="clear:both;margin-top:0;margin-bottom:2px;"><a class="google_headings" ' +
				  'href="'+ google_info.feedback_url +'">' +
				  'Ads by Google</a></h2><table cellspacing="0" cellpadding="0" style="margin-bottom:6px;">' + permaAds + '</tr></table>';
		if(document.getElementById("perma_ad_unit"))document.getElementById("perma_ad_unit").innerHTML = permaAds;
		if(document.getElementById("permaafs"))document.getElementById("permaafs").style.display = "block";
	}

    if (top_narrowAds != ""){
        top_narrowAds = '<h2 class="ad_heading" style="margin-bottom:2px;"><a class="google_headings" ' +
				  'href="'+ google_info.feedback_url +'">' +
				  'Ads by Google</a></h2>' + top_narrowAds;
		if(document.getElementById("top_narrow_ad_unit"))document.getElementById("top_narrow_ad_unit").innerHTML = top_narrowAds;
		if(document.getElementById("top_narrowafs"))document.getElementById("top_narrowafs").style.display = "block";
	}

    if (narrowAds != ""){
        narrowAds = '<h2 class="ad_heading" style="margin-bottom:2px;"><a class="google_headings" ' +
				  'href="'+ google_info.feedback_url +'">' +
				  'Ads by Google</a></h2>' + narrowAds;
		if(document.getElementById("narrow_ad_unit"))document.getElementById("narrow_ad_unit").innerHTML = narrowAds;
		if(document.getElementById("narrowafs"))document.getElementById("narrowafs").style.display = "block";
	}

}

function editComment(comment) {
	var commentBlock = $("#c" + comment.id );
	

	var commentText = commentBlock.find(".comment-text");
	
	var currentCommentHTML = commentText.html();
	
	commentText.html("abc");
	
	commentText.html(
		'<form method="get" id="edit-c'+comment.id+'">'+
		'<input type="hidden" name="comment_question_id" value="'+comment.question_id+'" />'+
		'<input type="hidden" name="comment_answer_id" value="'+comment.answer_id +'" />'+
		'<input type="hidden" name="comment_id" value="'+comment.id+'" />'+
		'<input type="hidden" name="comment_type" value="'+comment.type+'" />'+
		'<input type="hidden" name="key_owner" value="'+MAHALO_KEY_OWNER+'" />'+
        '<input type="hidden" name="access_key" value="'+MAHALO_ACCESS_KEY+'" />'+
        '<input type="hidden" name="public_key" value="'+MAHALO_PUBLIC_KEY+'" />'+
        '<input type="hidden" name="app_key" value="'+MAHALO_APP_KEY+'" />'+
		'<textarea name="comment" id="comment_edit_'+comment.id+'" rows="5" cols="40" style="width: 100%;">'+comment.comment_raw+'</textarea><br /><br />'+
		'<input type="submit" class="blue-button" value="Save Your Comment" id="edit-c'+comment.id+'-button" />'+
		' <a href="#" id="cancel-c'+comment.id+'-button">Cancel</a>'+
		'</form>'
	);
	
	$("#cancel-c"+comment.id+"-button").click(function (event) {
		event.preventDefault();
		
		commentText.html(currentCommentHTML);
	});
	
	$("#edit-c"+comment.id+"-button").click(function (event) {
		event.preventDefault();
		
		$.post(API_URL + "/answers/set_comment/", $("#edit-c"+comment.id).serializeArray(), function(data){
            if (data.status == false) {
				error(data.msg);
			}
			else {
				commentText.html(data[0].fields.comment.replace(/\n/g, "<br />") + "<br /><br />") ;
            }
        }, "json" );
	});
}

function setPopups() {
    $('.bubble-info').each(function () {
        var distance = 10;
        var time = 250;
        var hideDelay = 500;

        var hideDelayTimer = null;

        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', this);
        var info = $('.popup', this).css('opacity', 0);
        var close = $('.popup_close', this);
        
        $([close.get(0)]).click(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                info.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    info.css('display', 'none');
                });

            }, hideDelay);

            return false;
         })

        $([trigger.get(0), info.get(0)]).click(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            if (beingShown || shown) {
                // don't trigger the animation again
                return;
            } else {
                // reset position of info box
                beingShown = true;

                info.css({
                    top: -75,
                    left: -32,
                    display: 'block'
                }).animate({
                    top: '-=' + distance + 'px',
                    opacity: 1
                }, time, 'swing', function() {
                    beingShown = false;
                    shown = true;
                });
            }

            return false;
        }).blur(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                info.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    info.css('display', 'none');
                });

            }, hideDelay);

            return false;
        });
    });
}

var facebookReturnData = null;
    
function facebook_onlogin() {
    $("#facebook-loading").show();

    $.post(API_URL + "/facebook_login/", [], function(data) {
        if (data.status == false) {
            $("#facebook-loading").hide();
            
            error(data.msg);
        }
        else {
            if ("lguserid" in data.login) {
                login_callback(data);
            }
            else {
                facebookReturnData = data;
                
                // Link with Mahalo account?
                linkFacebookAndMahalo();
            }
        }
    }, "json");
}

function noMahaloAccount() {
    $.post(API_URL + "/facebook_login/", [ {"name": "no_mahalo_account", "value": true }], function (data) {
        if (data.status == false) {
            error(data.msg);
        }
        else {
            login_callback(data);
        }
    }, "json");
}

function checkMahaloAccount() {
    var username = $("#fb-m-username").val();
    var password = $("#fb-m-password").val();
    
    $.post(API_URL + "/facebook_login/", [ {"name": "mahalo-username", "value": username }, {"name": "mahalo-password", "value": password }], function (data) {
        if (data.status == false) {
            error(data.msg, "fb-m-msg", 400, true);
        }
        else {
            login_callback(data);
        }
    }, "json");
}

function linkFacebookAndMahalo(data) {
    var html = '<div class="modal-dialog" style="padding: 30px 50px 30px 50px; border: 1px solid #666; background: #fff; width: 400px;"><h1>Just one more thing...</h2><br /><div id="fb-m-msg"></div><p>Do you already have a Mahalo account?</p><input type="submit" class="blue-button" value="No, just log me in with my Facebook account" onclick="$.modal.close(); noMahaloAccount();" />';
    html += '<div class="half-column"><small id="login-first-label">Username:</small><br /><input class="textedit" type="text" id="fb-m-username" name="uname" value="" style="width: 175px;" /></div>';
    html += '<div class="half-column"><small id="login-second-label">Password:</small><br /><input class="textedit" type="password" id="fb-m-password" name="login-password" value="" style="width: 175px;" /></div>';
    html += '<input type="submit" class="blue-button" value="Yes, link my Facebook account to this Mahalo account" onclick="checkMahaloAccount();" /></div>';
    
    $(html).appendTo($("body")).modal();
}

function init_actionbar() {
    var path = document.location.href.split("//")[1];
    
    var path = path.substring(path.indexOf("/"));
    
    $("a.nextpage").each(function () {
        var new_href = $(this).attr("href") + "?next=" + path;
        
        $(this).attr("href", new_href);
    });
}

function twitter_getAuthUrl(next) {
    $.post(API_URL + "/twitter_getAuthUrl/", [{"name": "next", "value": next }], function(data) {
        if (data.status == false) {
            error(data.msg, "message-container");
        }else {
            document.location.href = data.auth_url;
        }}, "json");
}

function toggleButtonBusy(button_elm, busy_elm, disabled_text, enabled_text){
    if( $(button_elm).attr("disabled") ){
        $(button_elm).removeAttr("disabled").removeClass("gray-button").addClass("blue-button").val(enabled_text);
        $(busy_elm).hide();
    } else {
        $(button_elm).attr("disabled", "disabled").removeClass("blue-button").addClass("gray-button").val(disabled_text);
        $("#submit-busy").show();
    }
}

function on_ajax_request_error(msg){
    var error_msg_suffix = "<br />Please try again or <a href='mailto:contact@mahalo.com' >contact us</a> if you continue to see this message.";
    msg += error_msg_suffix;
    
    error(msg, "content", "550", false);
}

// Initial load
$(document).ready(function () {
    
    // Set global options for all ajax requests
    // These can be overridden in each request if needed
    $.ajaxSetup({
        type: "POST",
        dataType: "json",
        timeout: 15000,
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong completing your request. (" + msg + " : " + xhr.status + ")");
        }
    });
    
	fuzzyTime();
	setInterval(fuzzyTime, 1000 * 60);
	init_actionbar();
});


var videoCount = 0;
var photoCount = 0;
var audioCount = 0;
var locationCount = 0;

function addVideo(event, url) {
    if (event) {
        event.preventDefault();
    }
    
    var videoForm = "";
    if(videoCount == 0){
        videoForm += '<div class="clear"></div><div class="form-section" id="video-header"><h2>Embed a Video</h2>';
        videoForm += '<div style="line-height:1.1em;margin-top:6px;"><small>Enter the URL of a video e.g. http://www.youtube.com/watch?v=oHg5SJYRHA0</small>';
        videoForm += '<br />On Youtube, Hulu, etc.</small></div></div>';
    }
    videoForm += '<div id="video-form'+ videoCount +'" class="media-form"><div class="form-section">';
    videoForm += '<input class="textedit-blue" type="text" name="embedvideo'+ videoCount + '" id="embedvideo' + videoCount + '" value="';
    if (url) {
        videoForm += url;
    }
    
    videoForm += '" style="width:460px;" />';
    videoForm += '&nbsp;<a href="javascript:void(0);" count="' + videoCount + '" id="cancel-video-form'+ videoCount + '">Cancel</a>';
    videoForm += '</div>';
    videoForm += '</div>';
    
    $("#videos").append(videoForm);
    $("#videos").find('#video-form' + videoCount).fadeIn(500);
    
    $('#cancel-video-form' + videoCount).click(function(event){
        event.preventDefault;
        $("#videos").find('#video-form' + $(this).attr('count')).remove();
        videoCount--;
        if(videoCount == 0){
            $("#video-header").remove();
        }
    });
    videoCount++;
}

function addPhoto(event, url) {
    if (event) {
        event.preventDefault();
    }
    
    var photoForm = "";
    if(photoCount == 0){
        photoForm += '<div class="clear"></div><div class="form-section" id="photo-header"><h2>Embed a Photo</h2>';
        photoForm += '<div style="line-height:1.1em;margin-top:6px;"><small>Enter the URL of a .jpg, .gif, or.png file</small>';
        photoForm += '<br />Or the URL of a photo on Flickr</small></div></div>';
    }
    photoForm += '<div id="photo-form'+ photoCount +'" class="media-form"><div class="form-section">';
    photoForm += '<input class="textedit-blue" type="text" name="embedphoto' + photoCount + '" id="embedphoto' + photoCount + '" value="';
    if (url) {
        photoForm += url;
    }
    
    photoForm += '" style="width:460px;" />';
    photoForm += '&nbsp;<a href="javascript:void(0);" count="' + photoCount + '" id="cancel-photo-form'+ photoCount + '">Cancel</a>';
    photoForm += '</div>';
    photoForm += '</div>';
    
    $("#photos").append(photoForm);
    $("#photos").find('#photo-form' + photoCount).fadeIn(500);
    
    $('#cancel-photo-form' + photoCount).click(function(event){
        event.preventDefault;
        $("#photos").find('#photo-form' + $(this).attr('count')).remove();
        photoCount--;
        if(photoCount == 0){
            $("#photo-header").remove();
        }
    });
    photoCount++;
}

function addLocation(event, location) {
    if (event) {
        event.preventDefault();
    }
    
    var locationForm = "";
    if(locationCount == 0){
        locationForm += '<div class="clear"></div><div class="form-section" id="location-header"><h2>Add a Location</h2>';
        locationForm += '<div style="line-height:1.1em;margin-top:6px;"><small>Enter an address or a latitude/longitude pair.</small>';
        locationForm += '<br />The location will be displayed as an embedded map.</small></div></div>';
    }
    locationForm += '<div id="location-form'+ locationCount +'" class="media-form"><div class="form-section">';
    locationForm += '<input class="textedit-blue" type="text" name="geodata' + locationCount + '" id="embedlocation' + locationCount + '" value="';
    if (location) {
        locationForm += location;
    }
    
    locationForm += '" style="width:460px;" />';
    locationForm += '&nbsp;<a href="javascript:void(0);" count="' + locationCount + '" id="cancel-location-form'+ locationCount + '">Cancel</a>';
    locationForm += '</div>';
    locationForm += '</div>';
    
    $("#locations").append(locationForm);
    $("#locations").find('#location-form' + locationCount).fadeIn(500);
    
    $('#cancel-location-form' + locationCount).click(function(event){
        event.preventDefault;
        $("#locations").find('#location-form' + $(this).attr('count')).remove();
        locationCount--;
        if(locationCount == 0){
            $("#location-header").remove();
        }
    });
    locationCount++;
}

function addAudio(event, url) {
    if (event) {
        event.preventDefault();
    }
    
    var audioForm = "";
    if(audioCount == 0){
        audioForm += '<div class="clear"></div><div class="form-section" id="audio-header"><h2>Embed an MP3</h2>';
        audioForm += '<div style="line-height:1.1em;margin-top:6px;"><small>Enter the URL of a .mp3 file</small></div></div>';
    }
    audioForm += '<div id="audio-form'+ audioCount +'" class="media-form"><div class="form-section">';
    audioForm += '<input class="textedit-blue" type="text" name="embedaudio' + audioCount + '" id="embedaudio' + audioCount + '" value="';
    if (url) {
        audioForm += url;
    }
    audioForm += '" style="width:460px;" />';
    audioForm += '&nbsp;<a href="javascript:void(0);" count="' + audioCount + '" id="cancel-audio-form'+ audioCount + '">Cancel</a>';
    audioForm += '</div>';
    audioForm += '</div>';
    
    $("#audio").append(audioForm);
    $("#audio").find('#audio-form' + audioCount).fadeIn(500);
    
    $('#cancel-audio-form' + audioCount).click(function(event){
        event.preventDefault;
        $("#audio").find('#audio-form' + $(this).attr('count')).remove();
        audioCount--;
        if(audioCount == 0){
            $("#audio-header").remove();
        }
    });
    audioCount++;
}


function sort_answers(sort_order){
    try {
        if(sort_order == "helpful"){
            $("#answer-list>div.sorter").tsort("",{attr:"sorthelpful",order:"desc"});
        }else{
            $("#answer-list>div.sorter").tsort("",{attr:"sortdate",order:sort_order});
        }
    } catch (e) { }
}

function set_inline_login(){
    $("#join-button").click(function(event){
        $("#inline-login").hide();
        $("#inline-join").show();
        $("#confirm-message").show();
    });

	$("#login-button").click(function(event){
        $("#inline-join").hide();
        $("#inline-login").show();
        $("#confirm-message").hide();
    });
}

function addTeamTip(){
    var bounty;
    switch ($("input[@team-tip='option_layout']:checked").val()){
        case "2":
            bounty=0.10;
            break;
        case "3":
            bounty=0.25;
            break;
        case "4":
            bounty=0.50;
            break;
        case "5":
            bounty=1.00;
            break;
        case "6":
            bounty=($("input[id='other_team_tip_bounty']").val())
            break;
        default:
            bounty=0.05;
    }

    var args =  [ { "name": "question_id", "value": $("#yes_rate_question").attr("question_id") }, { "name": "score", "value": $("#yes_rate_question").attr("score") }, { "name": "bounty", "value": bounty } ];
    args = args.concat(API_KEYS);

    $.ajax({
        url: API_URL + "/answers/rate_question/",
        data: args,
        success: function(data){
            if (data.status == true) {
                $("#down_votes_" + $("#yes_rate_question").attr("question_id")).html(data.down_votes.toString());
                $("#up_votes_" + $("#yes_rate_question").attr("question_id")).html(data.up_votes.toString());
                location.reload(true);
            } else {
			    error(data.msg);
            }
            $(".popup").remove();
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong adding a tip and voting as interesting. (" + msg + " : " + xhr.status + ")");
            $(".popup").remove();
        }
    });
}

var currentReplyButton;
var currentCancelButton;

function reply(answer_id){
    var replyButton = '#replyButton_' + answer_id;
    var cancelButton = '#cancelButton_' + answer_id;
    var replyFormDiv = '#replyFormDiv_' + answer_id;

    if (document.getElementById("comment")) {
        document.getElementById('comment').value = '';
        document.getElementById('comment_answer_id').value = answer_id;
    }

    if($("#comment-form").css('display') == 'block'){
        currentCancelButton.hide();
        currentReplyButton.show();
    }

    if(replyButton && cancelButton && replyFormDiv){
        currentReplyButton = $(replyButton);
        currentCancelButton = $(cancelButton);
        $(cancelButton).show();
        $(replyButton).hide();

        $("#comment-form").appendTo($(replyFormDiv));
        $("#comment-form").fadeIn(500);

        if (document.getElementById("comment")) {
            $("#comment_type_select").attr("selectedIndex", 0);
            document.getElementById('comment').focus();
        }
    }
}

function cancel(answer_id){
    $("#comment-form").hide();
    $("#comment-form").appendTo($("body"));

    var replyButton = '#replyButton_' + answer_id;
    var cancelButton = '#cancelButton_' + answer_id;
    var replyFormDiv = '#replyFormDiv_' + answer_id;

    if (document.getElementById("comment")) {
        document.getElementById('comment').value = '';
        document.getElementById('comment_answer_id').value = '';
    }
    if(replyButton && cancelButton && replyFormDiv){
        $(replyButton).show();
        $(cancelButton).hide();
    }
}

/* The following functions replace the inline javascript for each
Django template, moving this to the CDN will speed page load

Format = init_<template-name>()
*/

/*  Template: mahalo/answers/accept_answer.html
    Initialize submit, cancel buttons for accepting an answer, setup rating star plugin
*/
function init_accept_answer(){
    $("#feedback").focus();
    
    $("#cancel-button").click(function (event) {
        event.preventDefault();
        return_url = $(this).attr("return_url");
        document.location.href = return_url;
    });
    
    $("#submit-button").click(function (event) {
        event.preventDefault();
        var return_url = $(this).attr("return_url");

        toggleButtonBusy("#submit-button", "#submit-busy", "Submitting", "Submit");

        var args = $("#accept_form").serializeArray()
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/accept_answer/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                    toggleButtonBusy("#submit-button", "#submit-busy", "Submitting", "Submit");
                }
                else {
                    document.location.href = return_url;
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong while accepting this best answer. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#submit-button", "#submit-busy", "Submitting", "Submit");
            }
        });
    });
    
    var currentRating;
    $(function(){
        $('.hover-star').rating({
            focus: function(value, link){
                currentRating = $("#rating-text").html();
                var tip = $('#rating-text');
                tip[0].data = tip[0].data || tip.html();
                tip.html(link.title || 'value: '+ value);
            },
            blur: function(value, link){
                var tip = $('#rating-text');
                $('#rating-text').html(currentRating);
            },
            callback: function(value, link){
                currentRating = link.title;
                $('#rating-text').html(currentRating);
            }
        });
    });
}

/*  Template: mahalo/answers/activate_account.html
    Initialize submit button for activating an account (or twitter account)
*/
function init_activate_account(){
	$("#resend-button").click(function (event) {
		event.preventDefault();
	
        toggleButtonBusy("#resend-button", "#resend-busy", "Sending Email", "Resend Email");
    
        var args = $("#send-activation-form").serializeArray();
        args = args.concat(API_KEYS);
    
        $.ajax({
            url: API_URL + "/messaging/resend_activation/",
            data: args,
            success: function(data){
                if (data.status == false) {
    				error(data.msg);
                    toggleButtonBusy("#resend-button", "#resend-busy", "Sending Email", "Resend Email");
                 } else {
    				confirmation("Check your inbox for the activation email.", "content-left", 616);
                    $("#resend-button").val("Email Sent");
                    $("#resend-busy").hide();
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong resending your activation email. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#resend-button", "#resend-busy", "Sending Email", "Resend Email");
            }
        });
	});
}

/*  Template: mahalo/answers/answer.html
    Initialize submit,cancel button for answer question, inline login, adding media and declining a question
*/
function init_answer(){
    $("#answer").focus();
    
    function login_callback(data) {
        if (data.login && "lguserid" in data.login) {
            submit_answer();
        } else {
            error(data.msg);
            toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
        }
    }
    
    function submit_answer(){
        var return_url = $("#submit-answer").attr("return_url")
        
        var args = $("#answer_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/set_answer/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                    toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
                }
                else if (data["invalid-field"]) {
                    switch (data["invalid-field"]) {
                        case 'tags':
                            $("#tags").focus();
                        break;
                    }
                } else {
                    document.location.href = return_url;
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong saving your answer. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
            }
        });
    }
    
    $("#add-video").click(function(event){
        addVideo(event);
    });
    $("#add-photo").click(function(event){
        addPhoto(event);
    });
    $("#add-location").click(function(event) {
        addLocation(event);
    });
    $("#add-audio").click(function(event){
        addAudio(event);
    });
    
    $("#decline-button").click(function(event) {
        event.preventDefault();

        var return_url = $(this).attr("return_url");
        
        var args = $("#decline_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/decline_question/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                } else {
                    document.location.href = return_url;
                }
            },
            error: function(xhr, msg, thrownError){
                msg = "Something went wrong declining this question. (" + msg + " : " + xhr.status + ")" + error_msg_suffix;
                error(msg, "content", "500", false);
            }
        });
    });
    
    $("#submit-answer").click(function(event) {
        event.preventDefault();

        toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
        
        if(isLoggedIn){
            submit_answer();
        } else {
            //check for login or join
            var args = $("#answer_form").serializeArray();
            args = args.concat(API_KEYS);

            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
                        login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
                        login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong logging in to submit this answer. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-answer", "#submit-busy", "Submitting Answer", "Submit Your Answer");
                    }
                });
            }
        }
    });
    
    //Login form setup and post
    $("#join-button").click(function(event){
        $("#inline-login").hide();
        $("#inline-join").show();
        $("#confirm-message").show();
    });

    $("#login-button").click(function(event){
        $("#inline-join").hide();
        $("#inline-login").show();
        $("#confirm-message").hide();
    });
    
    setPopups();
    
    /**** for tag suggest ****/

    // build istubs array from stubs object {index: tags}
    var istubs = [];
    $.each(stubs, function(i, val) {
        istubs[i] = val;
    });

    // reset stubs to be an array instead of object
    stubs = [];

    // initialize tag suggester
    $('#tags').mtagSuggest({
        stubPath: CONTENT_URL + '/content/scripts/tagstubs',
        tags: [],
        tagContainer: 'div',
        tagWrap: 'div',
        matchClass: 'tagsuggest'
    });
}

/*  Template: mahalo/answers/ask.html
    Initialize submit,cancel button for submitting a question, inline login, adding media and category selection
*/
function init_ask(){
    var question_pk = "";
    var lastHash = "";
    
    function step1Finish(event, isManual) {
        if (event) {
            event.preventDefault();
        }
        $("#submit-busy").show();
        
        if($("#question").val() == ""){
            error("Please ask a question.");
            $("#question").focus();
            $("#submit-busy").hide();
            return false;
        }

        if (document.getElementById("question_bounty")) {
            if ($("#question_bounty").val().match(/[^0-9]/)) {
                error("Tips must be whole dollar amounts");
                $("#question_bounty").focus();
                $("#submit-busy").hide();
                return false;
            }
        }

        
        var tip_bool = true;
        var tip_amount;
        tip_amount = $("#question_bounty").val();
        if (tip_amount) { //if not editing a question
            $.ajax({
                type: "GET",
                url: API_URL + "/answers/check_tip_amount",
                data: { "tip-amount": tip_amount },
                async: false,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg);
                        tip_bool = false;
                    }
                    else {
                        tip_bool = true;
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong checking the tip balance for this question. (" + msg + " : " + xhr.status + ")");
                    $("#submit-busy").hide();
                }
            });
        }

        if (tip_bool == false) {
            $("#submit-busy").hide();
            return false;
        }

        if (!isManual) {
            lastHash = "#step2";
            document.location.hash = "step2";
        }
        
        $(".step1").hide();
        $("#counter").hide();
        $(".edit-question").show();
        $("#edit-question-button").hide();
        $(".step2").show();

        if(document.getElementById("question_bounty") && $("#question_bounty").val() > 0){
            $("#step2-tip-notice").show();
            $("#tip-text").html("M$" + $("#question_bounty").val());
            $("#tip-left").html("" + $("#question_bounty").val());
        } else {
            $("#step2-tip-notice").hide();
        }
        
        $("#question-bubble").removeClass("question-content").addClass("question-content-gradient");
        $(".question-detail-text").html( "Loading preview...");
        $(".question-detail-text").show();
        
        $("#question").hide();
        $(".question-text").html($("#question").val().replace(/</g, "&lt;").replace(/\n/g, "<br />"));
        $(".question-text").show();
        
        $("#question-bottom-sprite-left").removeClass("question-bl-sprite").addClass("question-bl-sprite-white");
        $("#question-bottom").addClass("question-bottom-white").removeClass("question-bottom");
        $("#question-bottom-sprite-right").removeClass("question-br-sprite").addClass("question-br-sprite-white");

        args = $("#ask_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            type: "GET",
            url: API_URL + "/answers/render_preview/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                 } else {
                    confirmation();
                    $(".question-detail-text").html(data.preview);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong rendering the preview for this question. (" + msg + " : " + xhr.status + ")");
            }
        });
        
        getExistingAnswers($("#question").val());

        if (!isManual) {
            classify($("#question").val());
        }
        else {
            // We'll have to fix this once the classifier is turned back on
            classify($("#question").val());
        }
        $("#submit-busy").hide();
    }
    
    function step2Finish(event, isManual) {
        if (event) {
            event.preventDefault();
        }
        
        submit_question();
    }

    function login_callback(data) {
        if ("lguserid" in data.login) {
            submit_question();
        }
        else {
            error(data.msg, "answers-login-form");
            toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
        }
    }
    
    function submit_question(){
        var args = $("#ask_form").serializeArray()
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/set_question/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                    toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");

                    if (data["missing-field"]) {
                        switch (data["missing-field"]) {
                            case 'category':
                                $("#categories-container").show();
                            break;
                            case 'question':
                                editQuestion();
                            break;
                        }
                    }
                    else if (data["invalid-field"]) {
                        switch (data["invalid-field"]) {
                            case 'tags':
                                $("#tags").focus();
                            break;
                        }
                    }
                }
                else {
		  document.location.href = '/answers/all/' + data[0].pk;
                }
            },
	    error: function(xhr, msg, thrownError){
	      on_ajax_request_error("Something went wrong saving your question. (" + msg + " : " + xhr.status + ")");
	      toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
	    }
        });
    }

    function editQuestion() {
        $("#question").attr("disabled", false);
        $(".edit-question").hide();
        $("#question-bubble").removeClass("question-content-gradient").addClass("question-content");
        $("#question-bottom-sprite-left").addClass("question-bl-sprite").removeClass("question-bl-sprite-white");
        $("#question-bottom").removeClass("question-bottom-white").addClass("question-bottom");
        $("#question-bottom-sprite-right").addClass("question-br-sprite").removeClass("question-br-sprite-white");
        
        $(".question-detail-text").hide();
        $("#question").show();
        $(".question-text").hide();
        $("#question").focus();
    }

    function editQuestionClick(event, isManual) {
        if (event) {
            event.preventDefault();
        }
        
        if (!isManual) {
            lastHash = "#step1";
            document.location.hash = "step1";
        }
        
        $(".step1").show();
        $(".step2").hide();
        $("#counter").show();
        
        editQuestion();
    }

    function categoryChange(e) {
        // Hide any other category sub-levels
        $(this).parent().parent().find(".select-categories").hide();
        var container = $(this).parent();
        var ul = container.find("> ul").get();
    
        if (ul.length > 0) {
            container.find("> .select-categories").show();
        }
        else {
            // Retrieve the sub-categories for this level.
            args = [ {"name": "parent_id", "value": $(this).val() } ];

            $.ajax({
                type: "GET",
                url: API_URL + "/get_categories/",
                data: args,
                success: function(data){
                    // Create the sub-tree
                    var ul = $("<ul></ul>");
                    ul.addClass("select-categories");
                    ul.css("padding-left", "3ex");
                    ul.hide();

                    container.append(ul);

                    if (data.categories.length > 0) {
                        for (var i = 0; i < data.categories.length; i++) {
                            var newLI = $("<li></li>");
                            newLI.addClass("green-text");
                            newLI.addClass("category");

                            var input = $('<input type="radio"/>');
                            input.attr("name","question_category_id");
                            input.addClass("category-radio");
                            input.attr("label", data.categories[i].name);
                            input.val(data.categories[i].id);
                            newLI.append(input);
                            newLI.append(" " + data.categories[i].name);

                            ul.append(newLI);
                        }

                        ul.show();

                        container.find("> .select-categories").show();

                        unbindCategoryChange();
                        bindCategoryChange();

                        if (pending_categories.length > 0) {
                            // Push off this first category.
                            category_id = pending_categories.shift();

                            $("input.category-radio[value='"+category_id+"']").attr("checked","checked").change();
                        }
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong getting categories. (" + msg + " : " + xhr.status + ")");
                    error(msg, "content", "500", false);
                }
            });
        }
    }

    function bindCategoryChange() {
        $(".category-radio").change(categoryChange);
    }
    
    function unbindCategoryChange() {
        $(".category-radio").unbind("change", categoryChange);
    }

    function checkForHash() {
        var hash = document.location.hash;
        
        if (hash != lastHash) {
            switch (hash) {
                case '#step1':
                case "":
                    editQuestionClick(null, true);
                break;
                case '#step2':
                    step1Finish(null, true);
                break;
            }
            
            lastHash = hash;
        }
    }

    function getExistingAnswers(question) {
        $("#existing-answers-container").hide();

        var args = [{ "name": "q", "value": question }];

        $.ajax({
            type: "GET",
            url: API_URL + "/search/answers/",
            data: args,
            success: function(data){
                if (data.results.response.numFound > 0) {
                    var answers = data.results.response.docs;

                    $("#existing-answers").html("");

                    for (var i = 0; i < answers.length && i < 5; i++) {
                        if (answers[i].id != $("#question-top").attr("question_id")) {
                            $("#existing-answers").append('<li><a href="{% url root %}/all/'+answers[i].id+'" target="_blank">'+answers[i].question+'</a></li>');
                        }
                    }

                    $("#existing-answers-container").show();
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong retrieving answers for this question. (" + msg + " : " + xhr.status + ")");
                error(msg, "content", "500", false);
            }
        });
    }
    
    function classify(question) {
        $(".loading-categories").hide();
        $("#suggested-categories-header").hide();
        $(".category").show();
        $("#view-all-categories").hide();
    }
    
    $("#question").focus();
    
    //$(".category").hide(); commented out on 10/9/09 delete after 12/01/09

    $("#step1").click(function(event){
        step1Finish(event);
    });
    
    $("#broadcast-twitter").click(function (event) {
        event.preventDefault();
        
        $(".broadcast-details").hide();
        $(".broadcast-link").css("font-weight","normal");
        $(this).css("font-weight", "bold");
        $("#twitter-details").show();
    });

    $("#broadcast-facebook").click(function (event) {
        event.preventDefault();
        
        $(".broadcast-details").hide();
        $(".broadcast-link").css("font-weight","normal");
        $(this).css("font-weight", "bold");
        $("#facebook-details").show();
    });
    
    $("#add-video").click(function(event){
        addVideo(event);
    });
    $("#add-photo").click(function(event){
        addPhoto(event);
    });
    $("#add-location").click(function(event) {
        addLocation(event);
    });
    $("#add-audio").click(function(event){
        addAudio(event);
    });
    
    $(".edit-question").click(function(event) {
        editQuestionClick(event);
    });
    
    $("#submit-question").click(function(event) {
        event.preventDefault();
        toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
        
        // Let's store <br/> as a newline in the DB for cleanliness.  Plus all the old details are stored this way.
        $("#detail").val($("#detail").val().replace(/<br\s*\/?>/g, "\n"));
        
        if(isLoggedIn){
            submit_question();
        } else {
            //check for login or join
            args = $("#ask_form").serializeArray()
            args = args.concat(API_KEYS);

            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
                        if (data.status == false) {
                            error(data.msg, "answers-login-form");
                            toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
                        }
                        else {
                            submit_question();
                        }
                    },
                    error: function(xhr, msg, thrownError){
                        msg = "Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")";
                        msg += "<br />Please try again or <a href='mailto:contact@mahalo.com' ";
                        msg += "rel='nofollow'>contact us</a> if you continue to see this message.";
                        error(msg, "content", "500", false);
                        toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
                        login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        msg = "Something went wrong logging into Mahalo. (" + msg + " : " + xhr.status + ")";
                        msg += "<br />Please try again or <a href='mailto:contact@mahalo.com' ";
                        msg += "rel='nofollow'>contact us</a> if you continue to see this message.";
                        error(msg, "content", "500", false);
                        toggleButtonBusy("#submit-question", "#submit-busy", "Submitting Question", "Submit Your Question");
                    }
                });
            }
        }
    });
    
    //Login form setup and post
    $("#join-button").click(function(event){
        $("#inline-login").hide();
        $("#inline-join").show();
        $("#confirm-message").show();
    });
    $("#login-button").click(function(event){
        $("#inline-join").hide();
        $("#inline-login").show();
        $("#confirm-message").hide();
    });
    
    $("#view-all-categories").click(function(event) {
        event.preventDefault();
        
        $(".category").show();
        $("#view-all-categories").hide();
        $("#suggested-categories-header").hide();
    });
    
    bindCategoryChange();

    setInterval(checkForHash, 500);
    
    /**** for tag suggest ****/

	// build istubs array from stubs object {index: tags}
	var istubs = [];
	$.each(stubs, function(i, val) {
		istubs[i] = val;
	});
	
	// reset stubs to be an array instead of object
	stubs = [];
	
	// initialize tag suggester
	$('#tags').mtagSuggest({
		stubPath: CONTENT_URL + '/content/scripts/tagstubs',
		tags: [],
		tagContainer: 'div',
		tagWrap: 'div',
		matchClass: 'tagsuggest'
	});
}

/*  Template: mahalo/answers/categories.html
    Initialize category tree links in right column used across the site
*/
function init_categories(){
    function categoryClick(element, e) {
		e.preventDefault();
		
		var category_id  = $(element).attr("id");
		var parent_li = element.parent();
		
        var args = [{"name": "category_id", "value": category_id}];
        args = args.concat(API_KEYS);

        $.ajax({
            type: "GET",
            url: API_URL + "/answers/get_category_branch/",
            data: args,
            success: function(data){
                //process the return data
                if (data.status == false) {
                    error(data.msg);
                }
                else {
                    //append the html string
                    element.parent().append(data.html);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong retrieving a list of categories. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#report-button", "#submit-busy", "Submitting Report", "Report Abuse");
            }
        });

        //close other expanded elements
        var roots = element.parent(".root-node").siblings(".root-node");
        roots.removeClass("cat-selected");
        roots.find(".cat-selected").removeClass("cat-selected").removeClass("expanded");
        roots.find(".black_left_arrow_sprite").hide();
        roots.find("span.expanded").removeClass("expanded").addClass("expand");
        roots.find("ul").hide();
        roots.find("span").show();
        
        //set this element to expanded
        var parent_li = element.parent()
        parent_li.addClass("cat-selected");
        parent_li.addClass("expanded");
        element.siblings(".black_left_arrow_sprite").show()
        parent_li.find("ul").show();
        element.removeClass("expand-pull").addClass("expand");
        element.hide();
    }
    
    function expand(element, e) {
        //close other expanded elements
        var roots = element.parent(".root-node").siblings(".root-node");
        roots.removeClass("cat-selected");
        roots.find(".cat-selected").removeClass("cat-selected").removeClass("expanded");
        roots.find(".black_left_arrow_sprite").hide();
        roots.find("span.expanded").removeClass("expanded").addClass("expand");
        roots.find("ul").hide();
        roots.find("span").show();
    
        //set this element to expanded
        var parent_li = element.parent()
        parent_li.addClass("cat-selected");
        parent_li.removeClass("expanded");
        element.siblings(".black_left_arrow_sprite").show()
        element.siblings("ul").show();
        element.removeClass("expand-pull").addClass("expand");
        element.hide();
    }

    $("#category-list > li > .expand-pull").live("click", function (e) {
        categoryClick($(this), e);
	});

    $("#category-list").find(".expand").live("click", function (e) {
        expand($(this), e);
    });
}

/*  Template: mahalo/answers/category_warning.html
    Initialize certain legal and nsfw category warning messages
*/
function init_category_warning(hide_type){
    $("#"+hide_type).click(function (e) {
        e.preventDefault();
    
        if(isLoggedIn){
            var args = $("#check_hide_form").serializeArray();
            args = args.concat(API_KEYS);

            $.ajax({
                url: API_URL + "/answers/"+hide_type+"/",
                data: args,
                success: function(data){
        			if (data.status == false) {
        				error(data.msg);
        			} else {
        			    $.cookie("mhoanswers_"+hide_type, "1", { expires: 365, path: '/', secure: false });
        			    $(".category-warning").hide("slide");
        			}
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong saving your request. (" + msg + " : " + xhr.status + ")");
                }
            });
        } else {
    	    //otherwise save as cookie
    	    $.cookie("mhoanswers_"+hide_type, "1", { expires: 365, path: '/', secure: false });
    	    $(".category-warning").hide("slide");
        }
    });
}

/*  Template: mahalo/answers/claim_twitter.html
    event handlers for claiming a twitter account
*/
function init_claim_twitter(){
	$("#t_username").focus();
	
	$("#claim-button").click(function (event) {
		event.preventDefault();
		
		confirmation();
		$(".loading").html("Validating...");
		$(".loading").show();

        var args = $("#twitter_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/twitter_claim/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    			    $(".loading").hide();
    				error(data.msg, "message-container");
    			}
    			else {
                    document.location.href = data.next;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong linking your twitter account to your mahalo account. (" + msg + " : " + xhr.status + ")");
            }
        });
	});
}

/*  Template: mahalo/answers/coupon.html
    event handlers for coupon redemmtion page
*/
function init_coupon(){
    function login_callback(data) {
		if (data.status == false) {
			error(data.msg, "answers-login-form");
		}
		else {
		    submit_coupon();
		}
        toggleButtonBusy("#submit-coupon", "#submit-busy", "Submitting", "Submit");
	}
        
    function submit_coupon(){
        var args = $("#coupon_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/coupon/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    				error(data.msg);
            		$('#success').hide();
                    $('#message-container').show();
    			}
    			else {
                    $('#coupon-login').hide();
                    $('#message-container').hide();
    				$('#credited-message').html(data.msg);
            		$('#success').show();
    			}
                toggleButtonBusy("#submit-coupon", "#submit-busy", "Submitting", "Submit");
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong redeeming your coupon. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#submit-coupon", "#submit-busy", "Submitting", "Submit");
            }
        });
    }
    
    $("#code-input").focus();

	$("#submit-coupon").click(function (e) {
		e.preventDefault();

        $("#submit-coupon").attr("disabled", "disabled"); 
		$("#submit-coupon").removeClass("blue-button").addClass("gray-button");
        $("#submit-coupon").val("Submitting");
        $("#submit-busy").show();

        if(isLoggedIn){
		    submit_coupon();
	    } else {
            args = $("#coupon_form").serializeArray();
            args = args.concat(API_KEYS);
            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-coupon", "#submit-busy", "Submitting", "Submit");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong logging into Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-coupon", "#submit-busy", "Submitting", "Submit");
                    }
                });
            }
	    }
	});
	
    set_inline_login();
}

/*  Template: mahalo/answers/email_answers.html
    event handlers for emailing answers to a friend
*/
function init_email_answers(){
    function login_callback(data) {
		if (data.status == false) {
			error(data.msg, "answers-login-form");
            toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");
		} else {
			email_answers();
		}
	}
		
	function email_answers(){
		var return_url = $("#email-answers").attr("return_url");
		
        var args = $("#email_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/subscribe_answers/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    			    error("Unable to subscribe for answers at this time.");
                    toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");
    			}
    			else {
    			    confirmation();
    				document.location.href = return_url;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong subscribing to email for answers to this question. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");
            }
        });
	}

	$("#email-answers").click(function(event) {
		event.preventDefault();

        toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");

        if(isLoggedIn){
			email_answers();
	    } else {
            args = $("#email_form").serializeArray();
            args = args.concat(API_KEYS);
            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong logging into Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#email-answers", "#submit-busy", "Submitting", "Submit");
                    }
                });
            }
	    }
	});
	
    set_inline_login();    
    
    setPopups();
}

/*  Template: mahalo/answers/email_question.html
    event handlers for emailing a question to a friend
*/
function init_email_question(){
    function login_callback(data) {
		if (data.status == false) {
			error(data.msg, "answers-login-form");
            toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");
		}
		else {
			email_question();
		}
    }

	function email_question(){
        var return_url = $("#email-question").attr("return_url");

        var args = $("#email_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/email_question/",
            data: args,
            success: function(data){
    			if (data.status == false) {
        			error("Unable to send email at this time.");
                    toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");
    			}
    			else {
    			    confirmation();
    				document.location.href = return_url;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong sending this question via email. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");
            }
        });
	}

	$("#email-to").focus();

	$("#email-question").click(function(event) {
		event.preventDefault();

        toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");

        if(isLoggedIn){
			email_question();
	    } else {
            args = $("#email_form").serializeArray();
            args = args.concat(API_KEYS);
            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong logging into Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#email-question", "#submit-busy", "Sending Email", "Email Question");
                    }
                });
            }
	    }
	});
	
    set_inline_login();    
    
    setPopups();
}

/*  Template: mahalo/answers/link_twitter.html
    Event handlers for linking to a twitter account
*/
function init_link_twitter(){
	var return_url  = $("#join-button").attr("return_url");
	
	$("#t_username").focus();
	
	$("#join-button").click(function (event) {
		event.preventDefault();
		
		confirmation();
		$(".loading").html("Validating...");
		$(".loading").show();
		
        var args = $("#twitter_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/twitter_profile/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    				error(data.msg, "message-container");
    			    $(".loading").hide();
    			}
    			else {
    			    $(".loading").hide();
    				document.location.href = return_url;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong linking your twitter account. (" + msg + " : " + xhr.status + ")");
			    $(".loading").hide();
            }
        });
	});
}

/*  Template: mahalo/answers/login_link_twitter.html
    Event handlers for linking to a twitter account from login
*/
function init_login_link_twitter(){
	var return_url  = $("#join-button").attr("return_url");
	
	$("#t_username").focus();
	
	$("#join-button").click(function (event) {
		event.preventDefault();
		
		confirmation();
		$(".loading").html("Validating...");
		$(".loading").show();
		
        var args = $("#twitter_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/twitter_profile/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    				error(data.msg, "message-container");
    			    $(".loading").hide();
    			}
    			else {
    			    $(".loading").hide();
    				document.location.href = return_url;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong linking your twitter account. (" + msg + " : " + xhr.status + ")");
			    $(".loading").hide();
            }
        });
	});
	
	function twitter_new_account(next) {
	    if(!$("#no-account-button").hasClass("gray-button")) {
	        $("#no-account-button").removeClass("blue-button").addClass("gray-button");
		    $("#no-account-busy").show();

            var args =  [{"name": "next", "value": next }];
            args = args.concat(API_KEYS);

            $.ajax({
                url: API_URL + "/create_account_twitter/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                    } else {
                        if (data.next == "") {
                            document.location.href = '/answers'
                        }else{
                            document.location.href = data.next;
                        }
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong linking your twitter account. (" + msg + " : " + xhr.status + ")");
        	        $("#no-account-button").removeClass("gray-button").addClass("blue-button");
        		    $("#no-account-busy").hide();
                    $(".loading").hide();
                }
            });
        }
    }
	
	$("#no-account-button").click(function (event) {
	    event.preventDefault();
	    twitter_new_account(return_url);
	});
}

/*  Template: mahalo/answers/permalink.html
    Event handlers for all actions on a permalink page
*/
function init_permalink(){
    function login_callback(data) {
        if (data.status == false) {
			error(data.msg);
            toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");
		}
		else {
			submit_comment();
		}
    }

    function submit_comment(){
        var args = $("#commentForm").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/set_comment/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    				error(data.msg);
                    toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");

    				if (data["missing-field"]) {
    					switch (data["missing-field"]) {
    						case 'comment_question_id':
    						break;
    						case 'comment_answer_id':
    						break;
    						case 'comment':
    						break;
    					}
    				}
    			}
    			else {
    				confirmation();

                    var commentblock = $("#comment_template").clone();                
                    commentblock.find("#comment_avatar").attr('src', '/answers/avatar/' + data[0].fields.user_name);
                    commentblock.find("#comment_avatar").attr('alt', data[0].fields.user_name);
                    commentblock.find("#comment_username").html(data[0].fields.user_name);
                    commentblock.find("#comment_username").attr("href", '/member/' + data[0].fields.user_name);

                    var timestamp = data[0].fields.created_date.replace(/[^0-9]/g, "");
                    commentblock.find("#comment_date").attr("timestamp", timestamp);

                    commentblock.find("#comment_text").html(data[0].fields.comment.replace(/\n/g, "<br />") + "<br /><br />");

                    if(data[0].fields.type == 1){
                        commentblock.find("#comment_type").html("-&nbsp;New Source");
                        commentblock.find("#comment_type").css("color", "#adadad");
    					confirmation("Thanks for adding a source. You earned one point.");
                    } else if(data[0].fields.type == 2){
                        commentblock.find("#comment_type").html("-&nbsp;Fact Refuted");
                        commentblock.find("#comment_type").css("color", "red");
    					confirmation("Thanks for refuting a fact. You earned one point.");
                    } else if(data[0].fields.type == 0){
                        commentblock.find("#comment_type").html("");
                    }

    				commentblock.find("#report-comment").attr("href", "/answers/report-comment/" + data[0].pk + "/");

                    cancel(data[0].fields.answer_id);

                    var offset = $("#answer_bottom_" + data[0].fields.answer_id).offset().top;

                    commentblock.appendTo($("#comments_"+data[0].fields.answer_id));
                    commentblock.show(500);

                    $('html,body').animate({scrollTop: offset}, 1000);

                    fuzzyTime();

                    toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong saving your comment. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");
            }
        });
    }

    function setUpCommentEditing() {
		$(".edit-comment").click(function (event) {
			event.preventDefault();
			
			var comment_id = $(this).attr("comment_id");

            var args = $("#commentForm").serializeArray().concat({"name": "comment_id", "value": comment_id});
            args = args.concat(API_KEYS);

            $.ajax({
                type: "GET",
                url: API_URL + "/answers/get_comment/",
                data: args,
                success: function(data){
    				if (data.status == false) {
    					error(data.msg);
    				}
    				else {
    					editComment(data.comment);
    				}
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong retrieving comment for editing. (" + msg + " : " + xhr.status + ")");
                }
            });
		});
	}
    
    $("#sort-by").change(function(event){
		event.preventDefault();
        var sort_order = $("#sort-by").val();
        sort_answers(sort_order);
    });

	setUpCommentEditing();

    $(function() {
        $('#answers-tabs').tabs(0, { fxFade: true, fxSpeed: 'fast' });
    });
	
	$("#submit-comment").click(function(event) {
		event.preventDefault();
        toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");

        if(isLoggedIn){
 			submit_comment();
	    } else {
            args = $("#commentForm").serializeArray();
            args = args.concat(API_KEYS);
            if($("#inline-login").css("display") == "none"){
                $.ajax({
                    url: API_URL + "/join/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong joining Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");
                    }
                });
            } else {
                $.ajax({
                    url: API_URL + "/login/",
                    data: args,
                    success: function(data){
        			    login_callback(data);
                    },
                    error: function(xhr, msg, thrownError){
                        on_ajax_request_error("Something went wrong logging into Mahalo. (" + msg + " : " + xhr.status + ")");
                        toggleButtonBusy("#submit-comment", "#submit-busy", "Submitting Comment", "Submit Your Comment");
                    }
                });
            }
	    }
    });

	$("#email-answers").click(function(event) {
		event.preventDefault();

        var return_url = $("#email-answers").attr("return_url");

        var args = $("#email_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/subscribe_answers/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    				error("Unable to subscribe for answers at this time.");
    			}
    			else {
    				confirmation();
    				document.location.href = return_url;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong subscribing to this question. (" + msg + " : " + xhr.status + ")");
            }
        });
    });

    set_inline_login();
    
    

    $(".rate_sprite").click(function (event) {
        event.preventDefault();
        
        var self = this;
        var args = [{ "name": "answer_id", "value": $(this).attr("answer_id") }, { "name": "score", "value": $(this).attr("score") }];
        args = args.concat(API_KEYS);
        
        $.ajax({
            url: API_URL + "/answers/rate_answer/",
            data: args,
            success: function(data){
                if (data.status == true) {
                    $("#down_votes_" + $(self).attr("answer_id")).html(data.down_votes.toString());
                    $("#up_votes_" + $(self).attr("answer_id")).html(data.up_votes.toString());
                } else {
    				error(data.msg);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong rating this answer. (" + msg + " : " + xhr.status + ")");
            }
        });
    });

    $(".question_rate_sprite").click(function (event) {
        event.preventDefault();
        var self = this;
        
        if ($(this).attr("score")==1){
            var html = '<div class="popup" style="width:350px"><div id="fb-m-msg"></div><p>Add a Tip in Order to Vote this Question Interesting<br />';
            html += '(A minimum tip of M$0.05 is required)</p><div class="team-tipping-box"><input id="team_tip5" type="radio" value="1" name="team_tip" checked>M$0.05<br />';
            html += '<input id="team_tip10" type="radio" value="2" name="team_tip">M$0.10<BR /><input id="team_tip25" type="radio" value="3" name="team_tip">M$0.25<br />';
            html += '<input id="team_tip50" type="radio" value="4" name="team_tip">M$0.50<BR /><input id="team_tip_dollar" type="radio" value="5" name="team_tip">M$1.00<br />';
            html += '<input id="team_tip_other" type="radio" value="6" name="team_tip"><span style="margin-right:3px">Other M$</span>';
            html += '<input type="text" class="editbox-small" maxlength="8" name="other_team_tip_bounty" id="other_team_tip_bounty" value="" /></div>';
            html += '<p>Note: This tip will be funded by your Mahalo Dollars Balance</p><div class="form-section-button">';
            html += '<input type="submit" class="blue-button" name="submit" id="submit-team-tip" value="Submit" onclick="addTeamTip(); $.modal.close()" style="height:32px"/>';
            html += '&nbsp;&nbsp;<input type="submit" class="gray-button" name="cancel" id="cancel-team-tip" style="height:32px" value="Cancel" onclick="$.modal.close();"/></div></div>';
            $(html).appendTo($("body")).modal();
        }else{
            var args = [ { "name": "question_id", "value": $(this).attr("question_id") }, { "name": "score", "value": $(this).attr("score") } ];
            args = args.concat(API_KEYS);
            
            $.ajax({
                url: API_URL + "/answers/rate_question/",
                data: args,
                success: function(data){
                    if (data.status == true) {
                        $("#down_votes_" + $(self).attr("question_id")).html(data.down_votes.toString());
                        $("#up_votes_" + $(self).attr("question_id")).html(data.up_votes.toString());
                        location.reload(true);
                    }
                    else {
    				    error(data.msg);
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong rating this question. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    });
    
    $(".vote-button").click(function (event) {
        event.preventDefault();
        var self = $(this);
        var return_url = $("#question-bubble").attr("return_url");
        
        var args = [{ "name": "answer_id", "value": self.attr("answer_id") }, { "name": "question_id", "value": $("#question-bubble").attr("meta_id") }];
        args = args.concat(API_KEYS);
        
        $.ajax({
            url: API_URL + "/answers/vote_answer/",
            data: args,
            success: function(data){
                if (data.status == true) {
                    window.location.href = return_url;
                } else {
    				error(data.msg);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong voting for this answer. (" + msg + " : " + xhr.status + ")");
            }
        });
    });      
    
    $(".asker-no-best-button").click(function (event) {
        event.preventDefault();
        var self = $(this);
        var return_url = $("#question-bubble").attr("return_url");

        if(confirm("Are you sure you want no best answer for this question?")){
            var args = [{ "name": "question_id", "value": $("#question-bubble").attr("meta_id") }];
            args = args.concat(API_KEYS);
            
            $.ajax({
                url: API_URL + "/answers/set_no_best_answer/",
                data: args,
                success: function(data){
                    if (data.status == true) {
                        window.location.href = return_url;
                    }  else {
    					error(data.msg);
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong setting no best answer. (" + msg + " : " + xhr.status + ")");
                }
            });
        }
    });
    
    $("#submit-answerer-feedback").click(function (event) {
        event.preventDefault();
        var return_url = $("#question-bubble").attr("return_url");

        var args =  $("#no-answer-feedback-form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/set_answerer_feedback/",
            data: args,
            success: function(data){
                if (data.status == true) {
                    window.location.href = return_url;
                }
                else {
    				error(data.msg);
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong setting your feedback. (" + msg + " : " + xhr.status + ")");
            }
        });
    });
    
    $("#add-video").click(function(event){
        addVideo(event);
    });
    $("#add-photo").click(function(event){
        addPhoto(event);
    });
    $("#add-location").click(function(event) {
        addLocation(event);
    });
    $("#add-audio").click(function(event){
        addAudio(event);
    });
    
    setPopups();
	
	// grab the latest view count for this question 	
	args = API_KEYS.concat([{"name": "question_id", "value": $("#question-bubble").attr("meta_id") }]);
    $.ajax({
        url: API_URL + "/answers/get_question_views/",
        data: args,
        success: function(data){
    	    if(data.views == 1)
    	        var view_txt = "View ";
    	    else
    	        var view_txt = "Views ";

    	    $("#total_views_" + $("#question-bubble").attr("meta_id")).html(data.views + " " + view_txt);
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong setting your feedback. (" + msg + " : " + xhr.status + ")");
        }
    });

    $("#bookmarking-link").click(function(e){
        e.preventDefault();
        $("#bookmarking").toggle();
    });

    var safe_url = window.location.href;
    safe_url = safe_url.replace(/(?:[#\?].*)/, "");


    //Posting to twitter
    $("#twitter-share").click(function (e) {
        e.preventDefault();
        $("#tweet-modal-container").modal({
            overlay: 10,
            overlayClose: true,
            minHeight: 177,
            minWidth: 350,
            overlayCss: {backgroundColor: "#000000"},
            onOpen:
                function (dialog) {
                    dialog.overlay.fadeIn('fast', function () {
                        dialog.container.slideDown('fast', function () {
                            dialog.data.fadeIn('fast');
                            });
                        });
                }
        });
    });

    var next = window.location.href;
    $("#twitter_login").click(function (event) {
        event.preventDefault();
        twitter_getAuthUrl(next);
    });

    $("#submit-tweet").click(function (e) {
        e.preventDefault();
        tweet();
    });

    $("#fb-share").attr("href", "http://www.facebook.com/sharer.php?u="+safe_url+"&t="+document.title);

    $("#bookmarking").bookmark({
        icons: CONTENT_URL + "/content/skins/mahalo/images/bookmarks.png",
        sites: ['aol', 'bloglines', 'delicious', 'digg', 'faves', 'friendfeed', 'google', 'linkedin', 'livejournal', 'myspace', 'netscape', 'netvibes', 'newsvine', 'propeller', 'reddit', 'slashdot', 'stumbleupon', 'technorati', 'thisnext', 'tumblr', 'windows', 'yahoobuzz', 'yahoo'],
        addEmail: true,
        compact: false
    });
}

/*  Template: mahalo/answers/report.html
    Initialize submit button of report form and handle in javascript
*/
function init_report(){
    $("#details").focus();
    
    $("#report-button").click(function (e) {
        e.preventDefault();
        data_url = $(this).attr("data_url");

        toggleButtonBusy("#report-button", "#submit-busy", "Submitting Report", "Report Abuse");

        var args = $("#report_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/report/",
            data: args,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);

                    toggleButtonBusy("#report-button", "#submit-busy", "Submitting Report", "Report Abuse");
                }
                else {
                    document.location.href = data_url;
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong saving your report. (" + msg + " : " + xhr.status + ")");
                toggleButtonBusy("#report-button", "#submit-busy", "Submitting Report", "Report Abuse");
            }
        });
    });
}

/*  Template: mahalo/answers/twitter_claim_login.html
    Event Handlers for claiming a twitter account
*/
function init_twitter_claim_login(){
	$("#t_username").focus();
	
	$("#claim-button").click(function (event) {
		event.preventDefault();
		
		confirmation();
		$(".loading").html("Validating...");
		$(".loading").show();
		
        var args = $("#twitter_form").serializeArray();
        args = args.concat(API_KEYS);

        $.ajax({
            url: API_URL + "/twitter_claim/",
            data: args,
            success: function(data){
    			if (data.status == false) {
    			    $(".loading").hide();
    				error(data.msg, "message-container");
    			}
    			else {
                    document.location.href = data.next;
    			}
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong claiming your twitter account. (" + msg + " : " + xhr.status + ")");
            }
        });
	});
	
	function linkMahaloTwitter() {
	    if(!$("#no-claim-button").hasClass("gray-button")) {
	        $("#no-claim-button").removeClass("blue-button").addClass("gray-button");
		    $("#no-claim-busy").show();
            document.location.href = '/answers/login_link_twitter';
        }
    }
	
	$("#no-claim-button").click(function (event) {
		event.preventDefault();
		linkMahaloTwitter();
	});
}

/*  Template: mahalo/answers/verify_details.html
    event handlers for verifify account details during twitter login
*/
function init_verify_details(){
	var next = $("#next_url").val();
	
	$("#t_username").focus();
	
	$("#verify-button").click(function (event) {
		event.preventDefault();

		if($("#email").val().length < 6) {
		    error("Invalid email.", "message-container");
		} else if($("#password").val().length < 5) {
		    error("Your password is too short. It must have at least 5 characters.", "message-container");
		} else {
		 	confirmation();
			$(".loading").html("Verifying...");
			$(".loading").show();

            var args = $("#verify_form").serializeArray();
            args = args.concat(API_KEYS);

            $.ajax({
                url: API_URL + "/verify_details/",
                data: args,
                success: function(data){
                    var args = data;
                    $.ajax({
                        url: API_URL + "/login/",
                        data: args,
                        success: function(data){
            				if ("user_token" in data.login) {
            					if ("points" in data.login && data.login.points) {
            						next += "?loggedin=1";
            					}

            					if ($("#next_url").val() != "") {
            						document.location.href = $("#next_url").val();
            					} else {
            						document.location.href = "/answers";
            					}
            				}
            				else {
            				    $(".loading").hide();
            					error(data.msg, "message-container");
            				}
                        },
                        error: function(xhr, msg, thrownError){
                            on_ajax_request_error("Something went wrong logging into your account. (" + msg + " : " + xhr.status + ")");
                        }
                    });
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong verifying your account details. (" + msg + " : " + xhr.status + ")");
                }
            });
		}
	});
}

/* Template: mahalo/answers/index.html
 *  Handler to direct anonymous question askers to the anonymous ask page.
 */
function index_ask_submit(){
    $("#main-page-ask2").submit(function(event) {
        if ($("#ask-anonymously2").is(":checked")) {
            $("#main-page-ask2").attr("action", "/answers/anonymous/ask/");
            $("#main-page-ask2").attr("method", "post");
            return true;
        }
        else {
            $("#main-page-ask2").attr("action", "/answers/ask/");
            $("#main-page-ask2").attr("method", "get");
            return true;
        }
    });
    $("#main-page-ask1").submit(function(event) {
        if ($("#ask-anonymously1").is(":checked")) {
            $("#main-page-ask1").attr("action", "/answers/anonymous/ask/");
            $("#main-page-ask1").attr("method", "post");
            return true;
        }
        else {
            $("#main-page-ask1").attr("action", "/answers/ask/");
            $("#main-page-ask1").attr("method", "get");
            return true;
        }
    });
}
