// character count and length enforcement for textarea's

function updateCharCount(textarea, max_len, span_id, submit_button_id, noun) {
    var chars_left = max_len - textarea.value.length;

    if (submit_button_id) {
        if (textarea.value.length == 0) {
            $("#"+submit_button_id).filter(":enabled").attr("disabled", true);
        }
        else {
            $("#"+submit_button_id).filter(":disabled").removeAttr("disabled");
        }
    }

    if (chars_left < 0) {
        textarea.value = textarea.value.substring(0, max_len);
        textarea.focus();
        chars_left = 0;
        textarea.scrollTop = textarea.scrollHeight;
    }

    chars_left_span = $("#" + span_id);
    if (textarea.value.length == 0) {
        chars_left_span.html("Please enter your " + noun);
    }
    else if (chars_left > 0) {
        chars_left_span.html(chars_left + " characters remaining");
    }
    else {
        chars_left_span.html('<em class="warning">You have reached the length limit for this ' + noun + '</em>');
    }
}

// collapse a text area if it's empty
function textareaCollapse(elem, removeCls) {
    text_length = elem.value.length;
    if (text_length == 0) {
        $(elem).removeClass(removeCls);
    }
}


function disableButtonIfEmpty(button_sel, form_elem_sel) {
    var toggle_function = function() {
        var any_empty = false;
        var elements = $(form_elem_sel);

        for (var i = 0; i < elements.length; i++) {
            if (elements[i].value.length == 0 || elements[i].value == 0){
                any_empty = true;
                break;
            }
        }

        if (any_empty) {
            $(button_sel).attr("disabled", true);
            $(button_sel).addClass("disabled");
        }
        else {
            $(button_sel).removeAttr("disabled");
            $(button_sel).removeClass("disabled");
        }
    };

    toggle_function();

    $(form_elem_sel).keyup(toggle_function);
    $(form_elem_sel).change(toggle_function);
}


function _limitTextAreaLength(textarea, max_len) {
    if (textarea == undefined)
        return;

    var chars_left = max_len - textarea.value.length;
    if (chars_left < 0) {
        textarea.value = textarea.value.substring(0, max_len);
        chars_left = 0;
        textarea.scrollTop = textarea.scrollHeight;
    }
}

function limitTextAreaLength(textarea_sel, length) {
    var textarea = $(textarea_sel)[0];
    _limitTextAreaLength(textarea, length);

    $(textarea).keyup(function() {
        _limitTextAreaLength(textarea, length);
    });

    $(textarea).keydown(function() {
        _limitTextAreaLength(textarea, length);
    });

    $(textarea).blur(function() {
        _limitTextAreaLength(textarea, length);
    });
}

// for city/state dropdowns
function onStateSelect(initial) {
    var city_dropdown = $("#cityDropdown")[0];
    
    if (initial && city_dropdown.options.length > 1) {
        // back-end has already populated city list, so don't load
        // it again
        return;
    }

    var state = $("#stateDropdown")[0].value;
    if (state.length) {
        $.getJSON("/utils/get_city_options_json",
                  { "state": state },
                  function(choices) {
                      city_dropdown.options[0] = new Option("(pick a city)", "");
                      city_dropdown.options.length = 1;
                      for (var i = 0; i < choices.length; i++) {
                          var option = new Option(choices[i], choices[i])
                          city_dropdown.options[city_dropdown.options.length] = option;
                      }
                      $(city_dropdown).removeAttr("readonly");
                  });
    }
    else {
        var city_dropdown = $("#cityDropdown")[0];
        city_dropdown.options.length = 1;
        city_dropdown.options[0] = new Option("(pick a state first)");
        $(city_dropdown).attr("readonly", true);
    }
}

function fixThumb(img) {
    img.onerror = "";
    return;
    img.src = "/images/nothumb.gif";
    img.onerror = "";
}


function replaceMissingThumbnails() {
    var thumbnails = $("img.smallerThumbnail,img.smallThumbnail,img.journalThumbnail,img.mediumThumbnail,img.largeThumbnail,div.thumb img");

    // needed because in IE, error events sometimes occur before DOM
    // is ready -- not compatible with Safari though, so just use this on IE
    if (document.all) {
        thumbnails.each(function() {
            if ((typeof this.naturalWidth != "undefined" &&
                this.naturalWidth == 0 ) 
                || this.readyState == 'uninitialized' ) {
                fixThumb(this);
            }
        });
    }


    // handles errors that occur after DOM is ready
    for (var i = 0; i < thumbnails.length; i++) {
        $(thumbnails[i]).error(function() {
            fixThumb(this);
        });
    }
}

function goToUrl(url) {
    window.location = url;
    return false;
}

function cancel() {
    window.location = g_cancel_url;
    return false;
}

// namespaced form utilities
var MMW = { }
MMW.forms = {
    disableButton: function(sel) { 
        $(sel).attr("disabled", "true");
        $(sel).addClass("disabled");
    },

    enableButton: function(sel) {
        $(sel).removeAttr("disabled");
        $(sel).removeClass("disabled");
    },

    // enables/disables "sel" depending on value of "cond"
    enableButtonCond: function(sel, cond) {
        if (cond)
            this.enableButton(sel);
        else
            this.disableButton(sel);
    },

    addVar: function($form, name, value) {
        $("<input type='hidden'>")
        .attr("name", name)
        .attr("value", value)
        .appendTo($form);
    },

    showCond: function(sel, cond) {
        if (cond)
            $(sel).show();
        else
            $(sel).hide();
    }
}

MMW.notifications = {
    selectSearchOption: function() {
        var option = $("#searchOptionDropdown").val()
        var url = g_select_search_option_url + "?option=" + option;
        $.post(url, {'option': option}, function(data) {
            $("#searchOptionNotification").html(data);
        });
    },

    hideProfileColorNag: function() {
        $.post(g_hide_nag_url, function() {
            $("#notification .inner").html("You won't see this reminder again.  If you want to pick your profile colors later, go to \"Your Account\" then click \"Edit profile information\" (at the bottom of the About Me section) later.");
        });
        return false;
    },

    hideGroupMessageNag: function() {
        $.post(g_hide_nag_url, function() {
            $("#notification").slideUp("slow");
        });
        return false;
    },

    hideGeneralNag: function() {
        $.post(g_hide_nag_url, function() {
            $("#notification").slideUp("slow");
        });
        return false;
    },

    hide: function(timeout_msecs) {
        if (!timeout_msecs)
            $('#notification').slideUp('normal');
        else 
            setTimeout("$('#notification').slideUp('normal');", timeout_msecs);
    }
}

MMW.themes = {
    setup: function() {
        // requires c.themed to be set
        var $checked = $('input[name="theme"]:checked');
        if ($checked.length) {
            $("#main").removeClass().addClass($checked.val());
        }
        $('input[name="theme"]').click(function() {
            $("#main").removeClass().addClass(this.value);
        });
    }
}

/* monkey patches for built in stuff */

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

// http://yensdesign.com/2009/01/how-to-set-maxlength-textareas-by-creating-jquery-plugin/
jQuery.fn.limit = function(max){  
    this.each(function(){  
        if(this.value.length > max){  
            this.value = this.value.substring(0,max);  
        }  

        //Get the type of the matched element  
        var type = this.tagName.toLowerCase();  
        //If the type property exists, save it in lower case  
        var inputType = this.type? this.type.toLowerCase() : null;  
        //Check if is a input type=text OR type=password  
        if(type == "input" && inputType == "text" || inputType == "password"){  
            //Apply the standard maxLength  
            this.maxLength = max;  
        }  
        //Check if the element is a textarea  
        else if(type == "textarea"){  
            //Add the key press event  
            this.onkeypress = function(e){  
                //Get the event object (for IE)  
                var ob = e || event;  
                //Get the code of key pressed  
                var keyCode = ob.keyCode;  
                //Check if it has a selected text  
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;  
                //return false if can't write more  
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);  
            };  
            //Add the key up event  
            this.onkeyup = function(){  
                //If the keypress fail and allow write more text that required, this event will remove it  
                if(this.value.length > max){  
                    this.value = this.value.substring(0,max);  
                }  
            };  
        }  
    });  
};  

jQuery.fn.truncate = function(length) {
    this.each(function() {
        var original = $(this).html().replace(/&lt;/g, "<").replace(/&gt;/g, ">");
        if (original.length > length) {
            var excerpt = original.substring(0, length) + "...";
            excerpt = excerpt.replace(/</g, "&lt;").replace(/>/g, "&gt;");
            var see_more_html = ' (<a href="#">more</a>)';
            var $this = $(this);

            $(this).html(excerpt + see_more_html);
            $(this).children("a").click(function() {
                $this.html(original);
                return false;   
            });
        }
    });
};

jQuery.fn.expandOnFocus = function(focus_css_height, regular_css_height){  
    $(this).focus(function() {
        $(this).height(focus_css_height);
    });
    $(this).blur(function() {
        if ($(this).val().length == 0)
            $(this).height(regular_css_height);
    });
};

jQuery.fn.enableControl = function() {
    $(this).removeAttr("disabled");
    $(this).removeClass("disabled");
};

jQuery.fn.disableControl = function() {
    $(this).attr("disabled", "true");
    $(this).addClass("disabled");
};

jQuery.fn.linkify = function() {
    // http://tangible.ca/articles/44/snippet-jquery-linkifier
    $(this).each(function() {
        if (!$(this).html())
                return;
        var linkable_content = $(this).html().replace(/(https?:\/\/[^ ;|\\*'"!,()<>]+\/?)/g,'<a href="$1">$1</a>');
        $(this).html(linkable_content);
    });
};

jQuery.fn.roundModule = function() {
    var settings = {
        tl: { radius: 10 },
        tr: { radius: 10 },
        bl: { radius: 10 },
        br: { radius: 10 },
        antiAlias: true,
        autoPad: false
    }

    $(this).each(function() {
        curvyCorners(settings, this);
    });
};

jQuery.fn.equalizeHeight = function() {
    var max_height = 0;
    $(this).each(function() {
        var height = $(this).height();
        max_height = (height > max_height) ? height : max_height;
    });
    $(this).css("min-height", max_height);

    /* ie6 hack */
    if($.browser.msie && $.browser.version=="6.0")
        $(this).css("height", max_height);
};

jQuery.fn.protectForm = function(t) {
    var $pt = $(this).children('input[name="pt"]');
    if (!$pt.length)
        return;

    var clickFunc = function() {
        $pt.val(t);
    };

    $(this).find("input,textarea").each(function() { 
        $(this).focus(clickFunc).click(clickFunc);
    });
}


// from: http://ejohn.org/blog/javascript-array-remove/#postcomment
Array.prototype.remove = function(from, to) {
    this.splice(from, (to || from || 1) + (from < 0 ? this.length : 0));
    return this.length;
};

if (!Array.indexOf){
    // IE sucks
    Array.prototype.indexOf = function(obj){
        for (var i=0; i<this.length; i++){
            if (this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

/* kudos */
MMW.kudos = {
    setupOverlay: function() {
        $("#kudoMessage").limit(150);
        $("#giveKudoOverlay .kudo").click(function() {
            $(this).siblings('input[type="radio"]').click();
        });
    },

    disableKudos: function(kudos) {
        $(".kudoChoice div.kudo").removeClass("disabled");
        $(".kudoChoice .kudoRadio").show().enableControl();
        $(".kudoChoice .given").hide();
        for (var i = 0; i < kudos.length; i++) {
            $(".kudo_"+kudos.charAt(i)+" div.kudo").addClass("disabled");
            $(".kudo_"+kudos.charAt(i)+" .kudoRadio").hide().disableControl();
            $(".kudo_"+kudos.charAt(i)+" .given").show();
        }

        $(".kudos .kudoRadio:enabled:first").click();
    }
};

/* module tabs */
MMW.mtabs = {
    tabs: {},

    activate: function(tab) {
        if ($(this).hasClass("active"))
            return false;

        var $active = $(this).siblings(".active");
        var active_id = $active.attr("id");
        $("#"+MMW.mtabs.tabs[active_id]).hide();
        $active.removeClass("active");

        $(this).addClass("active");
        var new_active_id = $(this).attr("id");
        $("#"+MMW.mtabs.tabs[new_active_id]).show();

        return false;
    }
}

jQuery.fn.setupTabs = function(tabs) {
    for (var t in tabs)
        MMW.mtabs.tabs[t] = tabs[t];

    $(this).children("li")
        .click(MMW.mtabs.activate)
        .hover(MMW.mtabs.activate);
};


/* global ready() */
$(document).ready(function() {
    registered = { }
    if ($("#success").length) 
        setTimeout("$('#success').slideUp('normal');", g_success_timer);

    $('input[name="fcr"]').val("");

    $(".ad a").attr("target", "_blank");
    if ($.browser.msie)
        $("div.round").roundModule();

    if (g_logged_in && !g_ev) {
        registerPopup(".actions a, .discussionBottom a, a.evReq", "#evPopup", "#evPopupClose");
    }
});
