/**
 * mahalo3-serp-common.js
 *
 * Javascript common to all SeRPs
 *
 * Copyright (c) 2009 Mahalo.com, Inc
 *
 */

var elm_type = 'li';
var pin_key = 'pin_';
var toolbar_timers = [];
var mhoClockTimer = null;

function init_serp_user(){
    $("li:contains('YouTube:')").css("margin-top","12px");

    $("#content").live("click", function(e){
        var node = $(e.target);

        //click handler for user add other section links
        if(node.hasClass("user_add_section")){
            onclick_user_add_section(e, node);
        }

        //click handler for 'add a link' links
        else if(node.hasClass("add_link")){
            onclick_add_link(e, node);
        }

        //click handler for 'add photo' links 
        else if(node.hasClass("add-image")){
            onclick_add_photo(e, node);
        }

        //click handler for 'add video' links 
        else if(node.hasClass("add-video")){
            onclick_add_video(e, node);
        }

        //click handler for showing view-all links
        else if(node.hasClass("view-all")){
            onclick_view_all(e, node);
        }

        //click handler for show comment links
        else if(node.hasClass("submit-comment")){
            onclick_submit_comment(e, node);
        }
        
        //click handler for section previous links
        else if(node.hasClass("section-previous-link")){
            onclick_section_prev(e, node);
        }
        
        //click handler for section next links
        else if(node.hasClass("section-next-link")){
            onclick_section_next(e, node);
        }
        
        //click handler for section more links
        else if(node.hasClass("section-more-link")){
            onclick_section_more(e, node);
        }
        
        //click handler for section more links
        else if(node.hasClass("more-button-content")){
            onclick_section_more_content(e, node);
        }

        //click handler for section more links
        else if(node.hasClass("more-button-facts")){
            onclick_section_more_facts(e, node);
        }

        //click handler for section comments show link
        else if(node.hasClass("section-comments-remainder-show")){
            onclick_section_comments_remainder_show(e, node);
        }
        
        //click handler for section comments hide link
        else if(node.hasClass("section-comments-hide-link")){
            onclick_section_comments_hide(e, node);
        }
    });

    $("#section-add-box").css("height", "auto");

    $("#toggle-tools").click(function(e){
        e.preventDefault();
        if($("#section-add-box").css("height") == "auto"){
            $("#section-add-box").slideUp(400, function(e){
                $("#section-add-box").css("height", "2.2em");
                $("#section-add-box").slideDown(100);
                $("#toggle-tools").html("<span class='ui-icon ui-icon-triangle-1-s'></span>");
            });
        } else {
            $("#section-add-box").slideUp(100, function(e){
                $("#section-add-box").css("height", "auto");
                $("#section-add-box").slideDown(400);
                $("#toggle-tools").html("<span class='ui-icon ui-icon-triangle-1-n'></span>");
            });
        }
    });
    
    $("#toggle-legend").click(function(e){
           e.preventDefault();

           if($("#section-add-box-legend").is(":visible")){
               $("#section-add-box-legend").slideUp(500, function(e){
                   $("#section-add-box-legend").hide();
                   $("#add-box-legend-content").css("display", "none");
                   $("#toggle-legend").html("<span class='ui-icon ui-icon-triangle-1-s'></span>");
               });
           } else {
               $("#add-box-legend-content").css("display", "block");
               $("#section-add-box-legend").slideDown(500, function(e){
                   $("#section-add-box-legend").show();
                   $("#toggle-legend").html("<span class='ui-icon ui-icon-triangle-1-n'></span>");
               });
           }
       });

   	$(".fg-button:not(.ui-state-disabled)")
   	.hover(
   		function(){ 
   			$(this).addClass("ui-state-hover"); 
   		},
   		function(){ 
   			$(this).removeClass("ui-state-hover"); 
   		}
   	)
   	.mousedown(function(){
   			$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
   			if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
   			else { $(this).addClass("ui-state-active"); }	
   	})
   	.mouseup(function(){
   		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
   			$(this).removeClass("ui-state-active");
   		}
   	});
        
    //click handler for showing photo embeds
    $(".image-popup").live("click", function(e){
        onclick_photo_embed(e, this);
    });

    //click handler for showing video embeds
    $(".video-popup").live("click", function(e){
        onclick_video_embed(e, this);
    });
 
    init_media_hovers();
    
    $(".manage-button, #claim-page-manager-button").click(function (e) {
        e.preventDefault();
        
        $.ajax({
            url: API_URL + "/pages/manage/",
            data: API_KEYS,
            success: function(data){
                if (data.status == false) {
                    error(data.msg, undefined, undefined, true);
                }
                else {
                    document.location.reload();
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong becoming the manager of this page. (" + msg + " : " + xhr.status + ")");
            }
        });
    });

    $("#vertical-manage-button").click(function (e) {
        e.preventDefault();
        
        $.ajax({
            url: API_URL + "/pages/vertical_manage/",
            data: API_KEYS,
            success: function(data){
                if (data.status == false) {
                    error(data.msg);
                }
                else {
                    document.location.reload();
                }
            },
            error: function(xhr, msg, thrownError){
                on_ajax_request_error("Something went wrong becoming the manager of this page. (" + msg + " : " + xhr.status + ")");
            }
        });
    });

    // hides tutorials and sets a cookie so they won't be shown again
    $("#remove-tutorials").click(function (e) {
        e.preventDefault();
        $(".tutorial-box").hide();
        $.cookie("tutorials_disabled", 1);
        $(this).html("Turn Tutorials On");
        $(this).unbind("click");
        $(this).click(function (e) {
            e.preventDefault();
            $.cookie("tutorials_disabled", null);
            window.location.reload();
        });
    });
    
    $("#show-tutorials").click(function (e) {
        e.preventDefault();
        $.cookie("tutorials_disabled", null);
        window.location.reload();
    });
}

function init_media_hovers() {
    sections = $(".linkslist");
    for(i=0; i < sections.length; i++){
       var section_pk = $(sections[i]).attr("section_id");
       var section_type = $(sections[i]).attr("section_type");
       if(section_type == "image" || section_type == "video"){
           set_media_hovers(section_type, section_pk);
       }
    }
}

function onclick_user_add_section(e, node){
    e.preventDefault();
    var link = $(node);
    
    var args = [ {"name": "q", "value": $("#page_title").val()} ];
    args.push({"name": "section_type", "value": link.attr("section_type") });
    args = args.concat(API_KEYS);
    
    $("#mahalo-loading-user-add").html( "<span class='loading-text'>&nbsp;&nbsp;Loading...</span>" );
    $("#mahalo-loading-user-add").show();

    $.ajax({
        type: "GET",
        url: API_URL + "/search/get_section/",
        data: args,
        success: function(data){
            $("#mahalo-loading-user-add").hide();

            if (data.status == false) {
                error(data.msg);
            }
            else {
                link.parent().parent().remove();
                $("#extra-search-sections").append(data.rendered);
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong creating the sections for this search page. (" + msg + " : " + xhr.status + ")");
            $("#mahalo-loading-user-add").hide();
        }
    });
}

function onclick_add_link(e, node){
    e.preventDefault();
    
    var section_id = $(node).attr("section_id");
    var section_type = $(node).attr("section_type");
    var page_section_id = $(node).attr("page_section_id");
    
    var args = [{"name": "section_id", "value": section_id }, {"name": "section_type", "value": section_type}, {"name": "page_section_id", "value": page_section_id }];
    args = args.concat(API_KEYS); 

    $.ajax({
        type: "GET",
        url: API_URL + "/guides/get_link_add/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                var placement = $("#" + section_type + "-section-" + section_id).find(".add-form");
                placement.html(data.add_form).show();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong fetching the add a link form. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_add_photo(e, node) {
	section_pk = $(node).attr("section_id");
	page_section_id = $(node).attr("lookup_id");
	e.preventDefault();

	var photoForm = "";
	photoForm += '<div class="clear"></div><div id="photo-header-'+ section_pk +'" style="margin-top:8px;"><h3>Add a Image</h3>';
	photoForm += '<div style="line-height:1.3em;"><small>Enter the URL of a .jpg, .gif, or.png file</small>';
	photoForm += '<br /><small>Or the URL of a photo on Flickr</small></div></div>';
	photoForm += '<form method="post" action="#" id="photo-form-'+ section_pk +'">';
	photoForm += '<input type="hidden" name="section_id" value="'+ section_pk +'" />';
	photoForm += '<input type="hidden" name="page_section_id" value="'+ page_section_id +'" />';
	photoForm += '<input class="textedit" type="text" name="embedphoto" id="embedphoto-'+ section_pk +'" value="" style="width:460px;margin-top:3px;" />';
    photoForm += '<div style="margin-top:6px"><input type="submit" onclick="$(this).addClass(\'gray-button\'); return false;" id="image-submit-'+ section_pk +'" value="Add" class="blue-button" />';
    photoForm += '&nbsp;<input type="button" onclick="$(this).addClass(\'gray-button\'); return false;" id="cancel-photo-form-'+ section_pk +'" value="Cancel" class="gray-button" />';
	photoForm += '</div></form>';

	if($("#photos-"+section_pk).html() == "")
	    $("#photos-"+section_pk).append(photoForm);
    $("#photos-"+section_pk).find('#photo-form-'+section_pk).show(500);
    $("#embedphoto-"+section_pk).focus();
    
    $('#image-submit-'+section_pk).click(function(event){
        event.preventDefault();
        
        $('#image-submit-'+section_pk).attr("disabled", "disabled");
        
        if($("#embedphoto-"+section_pk).val() != "") {
            args = $("#photo-form-"+section_pk).serializeArray();
            args = args.concat(API_KEYS); 
            
            $.ajax({
                url: API_URL + "/guides/add_image/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg);
                        $('#image-submit-'+section_pk).removeAttr("disabled");
                        $('#image-submit-'+section_pk).removeClass("gray-button");
                        $('#image-submit-'+section_pk).addClass("blue-button");
                    }
                    else {
                        replaceSection(data.section_type+"-section-"+data.section_id, data.page_section_id, data.section_id, data.rendered);
                        reset_page_sortables();
                        error();
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong adding your image. (" + msg + " : " + xhr.status + ")");
                    $('#image-submit-'+section_pk).removeAttr("disabled");
                    $('#image-submit-'+section_pk).removeClass("gray-button");
                    $('#image-submit-'+section_pk).addClass("blue-button");
                }
            });
        } else {
            $('#cancel-photo-form-'+section_pk).click();
        }
    });

    $('#cancel-photo-form-'+section_pk).click(function(event){
        event.preventDefault();
        $("#photos-"+section_pk).find('#photo-form-'+section_pk).remove();
        $("#photo-header-"+section_pk).remove();
        $("#photos-"+section_pk).html("");
        error();
    });
}

function onclick_photo_embed(e, node){
    e.preventDefault();
	
	var full_url = $(node).attr('full_url');
	var url = $(node).attr('href');
    var pk = $(node).attr('meta_id');
    var section_pk = $(node).attr('section_id');

    var args = [{"name": "image", "value": full_url}, {"name": "pk", "value": pk}, {"name": "url", "value": url}];
    args = args.concat(API_KEYS);

    $.ajax({
        url: API_URL + "/mahalo2/show_image/",
        data: args,
        success: function(data){
             if (data.status == false) {
                 error(data.msg);
             }
             else {
                 if(data.video_embed != ""){
         			html = "<table><tr><td>" + data.image_embed + "</td><td style='vertical-align:bottom;padding-left:10px;width:80px;'>" +
         			        "Click outside the image to close <span class='image-close'><img src='"+CONTENT_URL+"/content/skins/mahalo/images/clear.gif' class='blue-close-button' /></span></td>" +
         			        "</td><tr></table><div style='clear:both;'><a href='"+ data.image_url+"'><small>"+data.image_url+"</small></a></div>";
         			$(".image-embed").hide();
         			$(".video-embed").hide();
         			$("#image-embed-"+section_pk).fadeIn(200);
         			$("#image-embed-"+section_pk).html(html);

         			$(".image-close").click( function(event){
         	            event.preventDefault();
         				$("#image-embed-"+section_pk).fadeOut(200);
         			});

         			$("body").click( function(event){
         				$("#image-embed-"+section_pk).fadeOut(200);
         			});
         		} else {
         		    document.location.href= data.image_url;
         		}
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong showing this image. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_add_video(e, node) {
	var section_pk = $(node).attr("section_id");
	var page_section_id = $(node).attr("lookup_id");
	
	e.preventDefault();

	var videoForm = "";
	videoForm += '<div class="clear"></div><div id="video-header-'+section_pk+'" style="margin-top:8px;"><h3>Embed a Video</h3>';
	videoForm += '<div style="line-height:1.3em;"><small>Enter the URL of a video e.g. http://www.youtube.com/watch?v=oHg5SJYRHA0</small>';
	videoForm += '<br /><small>On Youtube, Hulu, etc.</small></div></div>';
	videoForm += '<form method="post" action="#" id="add-video-form-'+section_pk+'">';
	videoForm += '<input type="hidden" name="section_id" value="'+section_pk+'" />';
    videoForm += '<input type="hidden" name="page_section_id" value="'+page_section_id+'" />';
	videoForm += '<input class="textedit" type="text" name="embedvideo" id="embedvideo-'+section_pk+'" value="" style="width:460px;margin-top:3px;" />';
    videoForm += '<div style="margin-top:6px"><input type="submit" onclick="$(this).addClass(\'gray-button\'); return false;" id="add-video-submit-'+section_pk+'" value="Add" class="blue-button" />';
    videoForm += '&nbsp;<input type="button" onclick="$(this).addClass(\'gray-button\'); return false;" id="cancel-add-video-form-'+section_pk+'" value="Cancel" class="gray-button" />';
	videoForm += '</div></form>';

	if($("#videos-"+section_pk).html() == "")
	    $("#videos-"+section_pk).append(videoForm);
    $("#videos-"+section_pk).find('#video-form-'+section_pk).show(500);
    $("#embedvideo-"+section_pk).focus();
    
    $('#add-video-submit-'+section_pk).unbind("click");
    
    $('#add-video-submit-'+section_pk).click(function(event){
        event.preventDefault();

        $('#add-video-submit-'+section_pk).attr("disabled", "disabled");
 
        if($("#embedvideo-"+section_pk).val() != "") {
            args = $("#add-video-form-"+section_pk).serializeArray();
            args = args.concat(API_KEYS); 

            $.ajax({
                url: API_URL + "/guides/add_video/",
                data: args,
                success: function(data){
                    if (data.status == false) {
                        error(data.msg);
                        $('#add-video-submit-'+section_pk).removeAttr("disabled");
                        $('#add-video-submit-'+section_pk).removeClass("gray-button");
                        $('#add-video-submit-'+section_pk).addClass("blue-button");
                    }
                    else {
                        replaceSection("video-section-"+data.section_id, data.page_section_id, data.section_id, data.rendered);
                        reset_page_sortables();
                    }
                },
                error: function(xhr, msg, thrownError){
                    on_ajax_request_error("Something went wrong adding your video. (" + msg + " : " + xhr.status + ")");
                    $('#add-video-submit-'+section_pk).removeAttr("disabled");
                    $('#add-video-submit-'+section_pk).removeClass("gray-button");
                    $('#add-video-submit-'+section_pk).addClass("blue-button");
                }
            });
        } else {
            $('#cancel-add-video-form-'+section_pk).click();
            error();
        }
    });

    $('#cancel-add-video-form-'+section_pk).unbind("click");
    $('#cancel-add-video-form-'+section_pk).click(function(event){
        event.preventDefault();
        $("#videos-"+section_pk).html("");
        $("#videos-"+section_pk).find('#add-video-form-'+section_pk).remove();
        $("#video-header-"+section_pk).remove();
    });
}

function onclick_video_embed(e, node){
    e.preventDefault();
	
	var url = $(node).attr('full_url');
    var pk = $(node).attr('meta_id');
    var section_pk = $(node).attr('section_id');

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

    $.ajax({
        url: API_URL + "/mahalo2/show_video/",
        data: args,
        success: function(data){
             if (data.status == false) {
                 error(data.msg);
             }
             else {
                 if(data.video_embed != ""){
         			html = "<table><tr><td id='video-embeded-"+section_pk+"'>" + data.video_embed + "</td><td style='vertical-align:bottom;padding-left:10px;width:80px;'>" +
         			        "Click outside the video to close &nbsp;<span class='fg-button ui-state-default ui-corner-all'><span class='ui-icon ui-icon-close'></span></span></td>" +
         			        "</td><tr></table><div style='clear:both;'><a href="+ data.video_url+"><small>"+data.video_url+"</small></a></div>";

                    //Show throbber
                 	$(".image-embed").hide();
                 	$(".video-embed").hide();
                 	$("#video-embed-"+section_pk).fadeIn(300);
         			$("#video-embed-"+section_pk).html(html);

         			$(".video-close").click( function(event){
         	            event.preventDefault();
         				$("#video-embed-"+section_pk).fadeOut(200);
         			});

         			$("#site").click( function(event){
     				    $("#video-embed-"+section_pk).fadeOut(200);
         			});

         			// this prevents the embeded video from closing when clicked
         			$("#video-embeded-"+section_pk).click( function() {
                        return false;
                     });

         		} else {
         		    document.location.href= data.video_url;
         		}
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong showing this video. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_view_all(e, node){
    e.preventDefault();
    var page_section_pk = $(node).attr("page_section_id");
    
    args = [{"name":"lookup_id", "value": page_section_pk}, {"name":"show_all", "value": true}];
    args = args.concat(API_KEYS);
    
    $.ajax({
        type: "GET",
        url: API_URL + "/page_sections/get_rendered/",
        data: args,
        success: function(data){
            replaceSection(data.section_type+"-section-"+data.section_id, data.page_section_id, data.section_id, data.rendered);
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong fetching more items. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function onclick_submit_comment(e, node){
    e.preventDefault();
    
    var form = $(node).parent();
    var args = form.serializeArray();
    args = args.concat(API_KEYS);
    
    $.ajax({
        url: API_URL + "/mahalo2/comments/add/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
                var offset = $("message-container").offset().top - 10;
                $('html,body').animate({scrollTop: offset}, 1000);
            }
            else {
                form.find("textarea").val("");
                form.find("textarea").focus();
                form.find("textarea").blur(); 
                var new_comment = $(data.rendered_comment);

                // insert the new comment
                form.parent().parent().before(new_comment);

                // scroll to the top of comments
                //var offset = form.parent().prev().offset().top - 10;
                //$('html,body').animate({scrollTop: offset}, 1000);	

                //new_comment.effect("highlight", {"color": "#fff5ca"}, 2000);

                fuzzyTime();
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went adding your comment. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function reset_media_hovers(container){
    var section_type;
    var section_id;
    var sections;

    $(".image-edit-toolbar").hide();

    sections = $(".linkslist");
    for(i=0; i < sections.length; i++){
       var section_pk = $(sections[i]).attr("section_id");
       var section_type = $(sections[i]).attr("section_type");
       if(section_type == "image" || section_type == "video"){
           set_media_hovers(section_type, section_pk);
       }
    }
}

function set_media_hovers(type, section_pk){
    $("#"+type+"-section-"+section_pk).find(".image-hover").unbind();
    $("#"+type+"-section-"+section_pk).find(".image-hover").hover(function(e){ 
        if ($(this).attr("title")){
             $(this).removeAttr("title")
        }

        var id = $(this).attr("meta_id");
        
        clearTimeout(toolbar_timers[type + "_" + id]);
        
        if(!$("."+type+"-edit-toolbar-"+ id).is(":visible")){
            $(".image-edit-toolbar").hide();
            $("."+type+"-edit-toolbar-" + id).show();
            $("."+type+"-edit-toolbar-" + id).css("left", "35px" );
            $("."+type+"-edit-toolbar-" + id).css("top", "40px" );
        }

        if($.browser.msie){
           if($(this).parents(".media-thumb")) {
                $(this).parents(".media-thumb").css("position", "relative");
            }
        
            if($(this).parents(".image-thumb")) {
                $(this).parents(".image-thumb").css("position", "relative");
            }
        }
         
    }, function(e){
        var id = $(this).attr("meta_id");
        toolbar_timers[type + "_" + id] = setTimeout("hide_media_hover('"+ type +"', "+ id + ");", 20);
    });
    
    $("#"+type+"-section-"+section_pk).find(".image-edit-toolbar").unbind("mouseover");
    $("#"+type+"-section-"+section_pk).find(".image-edit-toolbar").mouseover(function(e){
        e.stopPropagation();
        
        var id = $(this).attr("meta_id");
    
        if($.browser.msie){
            if($(this).parent(".media-thumb")) {
                $(this).parent(".media-thumb").css("position", "relative" );
            }
        
            if($(this).parent(".image-thumb")) {
               $(this).parent(".image-thumb").css("position", "relative");
            }
        }

        clearTimeout(toolbar_timers[type + "_" + id]);
    });
    
    $("#"+type+"-section-"+section_pk).find(".image-edit-toolbar").unbind("mouseout");
    $("#"+type+"-section-"+section_pk).find(".image-edit-toolbar").mouseout(function(e){
        e.stopPropagation();
        var id = $(this).attr("meta_id");
        
        toolbar_timers[type + "_" + id] = setTimeout("hide_media_hover('"+ type +"', "+ id + ");", 20);
    });
}

function hide_media_hover( type, id, node ){
    $("."+type+"-edit-toolbar-"+id).hide();

    if($.browser.msie){
        if($("."+type+"-edit-toolbar-"+id).parent(".media-thumb")) $("."+type+"-edit-toolbar-"+id).parent(".media-thumb").css("position", "static" );
        if($("."+type+"-edit-toolbar-"+id).parent(".image-thumb")) $("."+type+"-edit-toolbar-"+id).parent(".image-thumb").css("position", "static" );
    }
}

function onclick_section_prev(e, node) {
    e.preventDefault();
    var page_section_id = $(node).attr("page_section_id");
    var section_id = $(node).attr("section_id");
    var section_type = $(node).attr("section_type");
    var search_term = $(node).attr("search_term");
    var disable = $(node).attr("disable");
    var page = parseInt( $(node).siblings("div").attr("section_current_page"), 10 );
    
    // make sure previous page number is valid
    if(page > 1 && disable !="disable") {
        // Ask API for more results
        $("#section_more_throbber_"+section_type+"_"+page_section_id).html( "<span class='loading-text' style='line-height:1.2em; padding-left:20px;'>&nbsp;</span>" );
        $("#section_more_throbber_"+section_type+"_"+page_section_id).show();
        
        var args = [ {"name": "page_section_pk", "value": page_section_id }, {"name": "section_pk", "value": section_id}, {"name": "section_type", "value": section_type}, {"name": "search_term", "value": search_term}, {"name": "page", "value": (page-1) }];
        args = args.concat(API_KEYS);

        $.ajax({
            type: "GET",
            url: API_URL + "/search/get_more/",
            data: args,
            success: function(data){
                $("#section_more_throbber_"+section_type+"_"+page_section_id).hide();
                if (!data.status) {
                    error(data.msg);
                }
                else {
                    $("#"+section_type+"-section-"+section_id+"-text").hide().html(data.rendered).show("slide", {direction: "left"}, 500);
                    $(node).siblings("div").attr("section_current_page", --page);

                    // hide the previous button if need be
                    if(page==1) {
                        $(node).siblings(".page-back-arrow").removeClass("page-back-arrow-blue");
                        $(node).siblings(".page-back-arrow").addClass("page-back-arrow-grey");
                        $(node).css("color", "#d5d5d5");
                        $(node).attr("disable","disable");
                    }

                    // always enable the next button
                    $(node).siblings(".page-next-arrow").removeClass("page-next-arrow-grey");
                    $(node).siblings(".page-next-arrow").addClass("page-next-arrow-blue");
                    $(node).siblings(".section-next-link").css("color","#003366");
                    $(node).siblings(".section-next-link").attr("disable", "");

                    // always enable the more button
                    $("#"+section_type+"-section-"+section_id).find(".section-more-link").show();

                    if(page_section_id != "None" && (section_type == "image" || section_type == "video")) {
                        set_media_hovers(section_type, section_id);
                    } else if(section_type == "image" || section_type == "video"){
                        //setTimeout('scaleImages();', 3000);
                    }

                    // reset sortables if possible
                    if(typeof reset_page_sortables == 'function') {
                        reset_page_sortables();
                    }
                }
            },
            error: function(xhr, msg, thrownError){
                $("#section_more_throbber_"+section_type+"_"+page_section_id).hide();
                on_ajax_request_error("Something went wrong returning to previous search results. (" + msg + " : " + xhr.status + ")");
            }
        });
    }
}

function onclick_section_next(e, node) {
    e.preventDefault();
    var page_section_id = $(node).attr("page_section_id");
    var section_id = $(node).attr("section_id");
    var section_type = $(node).attr("section_type");
    var search_term = $(node).attr("search_term");
    var disable = $(node).attr("disable");
    var page = parseInt($(node).siblings("div").attr("section_current_page"), 10);
    
    if(disable != "disable") {
        // Ask API for more results
        $("#section_more_throbber_"+section_type+"_"+page_section_id).html( "<span class='loading-text' style='line-height:1.2em;padding-left:20px;'>&nbsp;</span>" );
        $("#section_more_throbber_"+section_type+"_"+page_section_id).show();

        var args = [ {"name": "page_section_pk", "value": page_section_id }, {"name": "section_pk", "value": section_id}, {"name": "section_type", "value": section_type}, {"name": "search_term", "value": search_term}, {"name": "page", "value": (page+1)}];
        args = args.concat(API_KEYS);

        $.ajax({
            type: "GET",
            url: API_URL + "/search/get_more/",
            data: args,
            success: function(data){
                $("#section_more_throbber_"+section_type+"_"+page_section_id).hide();
                if (!data.status) {
                    error(data.msg);
                }
                else {
                    $("#"+section_type+"-section-"+section_id+"-text").hide().html(data.rendered).show("slide", {direction: "right"}, 500);
                    $(node).siblings("div").attr("section_current_page", ++page);

                    // make sure previous button is shown if need be
                    if(page>1){
                        $(node).siblings(".page-back-arrow").removeClass("page-back-arrow-gray");
                        $(node).siblings(".page-back-arrow").addClass("page-back-arrow-blue");                
                        $(node).siblings(".section-previous-link").css("color","#003366");
                        $(node).siblings(".section-previous-link").attr("disable", "");
                    }

                    // disable next button when there are no more results
                    if(data.no_more) {
                        $(node).unbind();
                        $(node).siblings(".page-next-arrow").removeClass("page-next-arrow-blue");
                        $(node).siblings(".page-next-arrow").addClass("page-next-arrow-grey");
                        $(node).css("color", "#d5d5d5");
                        $(node).attr("disable","disable");
                        $("#"+section_type+"-section-"+section_id).find(".section-more-link").hide();
                    }

                    if(page_section_id != "None" && (section_type == "image" || section_type == "video")) {
                        set_media_hovers(section_type, section_id);
                    } else if(section_type == "image" || section_type == "video"){
                        //setTimeout('scaleImages();', 3000);
                    }

                    // reset sortables if possible
                    if(typeof reset_page_sortables == 'function') {
                        reset_page_sortables();
                    }
                }
            },
            error: function(xhr, msg, thrownError){
                $("#section_more_throbber_"+section_type+"_"+page_section_id).hide();
                on_ajax_request_error("Something went wrong going to the next search results. (" + msg + " : " + xhr.status + ")");
            }
        });
    }
}

function onclick_section_more(e, node) {
    e.preventDefault();
    var page_section_id = $(node).attr("page_section_id");
    var section_id = $(node).attr("section_id");
    var section_type = $(node).attr("section_type");
    var search_term = $(node).attr("search_term");
    var page = parseInt($(node).siblings("div").attr("section_current_page"), 10);
    
    // Ask API for more results
    $("#section_more2_throbber_"+section_type+"_"+page_section_id).html( "<span class='loading-text' style='line-height:1.2em;padding-left:20px;'>&nbsp;</span>" );
    $("#section_more2_throbber_"+section_type+"_"+page_section_id).show();

    var args = [ {"name": "page_section_pk", "value": page_section_id }, {"name": "section_pk", "value": section_id}, {"name": "section_type", "value": section_type}, {"name": "search_term", "value": search_term}, {"name": "page", "value": (page+1)}];
    args = args.concat(API_KEYS);

    $.ajax({
        type: "GET",
        url: API_URL + "/search/get_more/",
        data: args,
        success: function(data){
            $("#section_more2_throbber_"+section_type+"_"+page_section_id).hide();
            if (!data.status) {
                error(data.msg);
            }
            else {
                if(section_type == "answers") {
                    $("#"+section_type+"-section-"+section_id+"-text").append($(data.rendered));
                } else {
                    var lis = $(data.rendered).find('li');
                    $("#"+section_type+"-section-"+section_id+"-text").find('ul').append(lis);
                }
                $(node).siblings("div").attr("section_current_page", ++page);

                if(section_type == "video") {
                    // remove "add video" and "video embed" (they will be re-added)
                    $("#add-video-icon-"+section_id).appendTo($("#"+section_type+"-section-"+section_id+"-text"));
                    $("#video-embed-"+section_id).appendTo($("#"+section_type+"-section-"+section_id+"-text"));
                } else if(section_type == "image") {
                    // remove "add image" and "image embed" (they will be re-added)
                    $("#add-image-icon-"+section_id).appendTo($("#"+section_type+"-section-"+section_id+"-text"));
                    $("#image-embed-"+section_id).appendTo($("#"+section_type+"-section-"+section_id+"-text"));  
                }

                // disable the more button if no more
                if(data.no_more) {
                    $(node).hide();
                }

                if(page_section_id != "None" && (section_type == "image" || section_type == "video")) {
                    set_media_hovers(section_type, section_id);
                }

                // reset sortables if possible
                if(typeof reset_page_sortables == 'function') {
                    reset_page_sortables();
                }
            }
        },
        error: function(xhr, msg, thrownError){
            $("#section_more2_throbber_"+section_type+"_"+page_section_id).hide();
            on_ajax_request_error("Something went wrong fetching more search results. (" + msg + " : " + xhr.status + ")");
        }
    });

    $.get(API_URL + "/search/get_more/", args, function(data) {
    }, "json");
}

function onclick_section_more_content(e, node) {
    e.preventDefault();
    var section = $("#left-column .sortable-sections-content");
    section.children("li").show();
    node.remove();
}

function onclick_section_more_facts(e, node) {
    e.preventDefault();
    var section = $("#left-column .sortable-sections-facts");
    section.children("li").show();
    node.remove();
}

function onclick_section_comments_remainder_show(e, node) {
    e.preventDefault();
    $(node).siblings(".section-comments-remainder").show();
    $(node).hide();
}

function onfocus_section_comment_textarea(node) {
    var textarea = $(node);

    if($.trim(textarea.val())=='Write a comment...') {
        textarea.val(''); 
        textarea.siblings('.submit-comment').show();
        textarea.css("width", "520px");

        if(loggedIn)
            textarea.parent().parent().siblings(".section-comment-current-avatar").children("img").attr("src", avatar);
                
        textarea.parent().parent().siblings(".section-comment-current-avatar").show();


        setTimeout(function() {
            textarea.autogrow({ lineHeight: 33 });
        }, 0);
    }

}

function onblur_section_comment_textarea(node)  {
    var textarea = $(node);
    if($.trim(textarea.val())=='') {
        textarea.val('Write a comment...'); 
        textarea.css("width", "582px");
        textarea.siblings('.submit-comment').hide();
        textarea.parent().parent().siblings(".section-comment-current-avatar").hide();
    }
}
function check_txtarea(txtarea){
    if (txtarea.value == txtarea.defaultValue){
        txtarea.value ="";
        txtarea.focus();
    }
    else if(txtarea.value == ""){
        txtarea.value = txtarea.defaultValue;
    }
}
