﻿var c_Hash = "";
var c_HashTimer = null;
var b_initHash = true;
var s_Hash = "";
var w_iframe = null;
var tBState = "";


$(document).ready(function() {

    //I really don't want to have to put it all in this JS file
    $.getScript("js/photo_page.js");
    $.getScript("js/edit_page.js");
    $.getScript("js/avatar_select.js");
    //$.getScript("js/calendar.js");

    function GetParentOfType(objQ, tag) {
        if (objQ.parentNode || objQ.jquery) {
            var obTest = objQ;
            while (obTest[0].tagName.toLowerCase() != tag.toLowerCase()) {
                if (obTest.parent().length > 0) {
                    obTest = obTest.parent();
                } else {
                    return null;
                }
            }
            return obTest;
        }
    }
    
    function TopBar_DoLoad(sFor) {
        switch (sFor) {
            case "Photos":
                if (typeof PhotoUpload != "object") {
                    $.getScript("/members/js/photoload.js", function() {
                        PhotoUpload.init();
                    });
                } else {
                    PhotoUpload.init();
                }
                break;
        }
    }

    function TopBar_DoUnload(sFor) {
        //Nothing yet
    }

    function ShowLoading() {
        $("#bd_main").hide();
        $("#bd_load").show();
    }

    function HideLoading() {
        $("#bd_main").show();
        $("#bd_load").hide();
    }
    
    function ShowSearchLoading() {
        $("#searchload").show();
    }
    function HideSearchLoading() {
        $("#searchload").hide();
    }

    function ShowAddLoading() {
        $("#addingload").show();
    }
    function HideAddLoading() {
        $("#addingload").hide();
    }

    if (jQuery.browser.msie) {

    } else if (jQuery.browser.safari) {
    }

    //Short Article Add/Edit
    $("#arttitleshort").live("keyup", function(e) {
        if ( $(this).val().replace(/(<([^>]+)>)/ig,"") != $(this).val() ) {
    	    $("#testh3").html($(this).val().replace(/(<([^>]+)>)/ig,""));
            $(this).val($(this).val().replace(/(<([^>]+)>)/ig,""))
        } else {
    	    $("#testh3").html($(this).val().replace(/(<([^>]+)>)/ig,""));
        }
    });

    $("#arttextshort").live("keyup", function(e) {
        if ( $(this).val().replace(/(<([^>]+)>)/ig,"") != $(this).val() ) {
            $("#testtext").html($(this).val().replace(/(<([^>]+)>)/ig,"").replace(/\n/g,'<br/>'));
            $(this).val($(this).val().replace(/(<([^>]+)>)/ig,""));
        } else {
            $("#testtext").html($(this).val().replace(/(<([^>]+)>)/ig,"").replace(/\n/g,'<br/>'));
        }
        var matches = $(this).val().replace(/<[^<|>]+?>|&nbsp;/gi,' ').match(/\b/g);
        var count = 0;
        if(matches) {
            count = matches.length/2;
        }
        document.getElementById('short_word_count').innerHTML = count + " word" + (count == 1 ? "" : "s");
        document.getElementById('artwords').value = count;
    });
    
    $("#artlinkshort").live("keyup", function(e) {
        if ( $(this).val().replace(/(<([^>]+)>)/ig,"") != $(this).val() ) {
            $("#testartlink").html($(this).val().replace(/(<([^>]+)>)/ig,""));
            $(this).val($(this).val().replace(/(<([^>]+)>)/ig,""));
        } else {
            $("#testartlink").html($(this).val().replace(/(<([^>]+)>)/ig,""));
        }
    });
    
    //Long Article Page
    
    $("#articlepreview").live("click", function(e) {
        EditorObject.UpdateEditorFormValue();
        var runpreview = true;
        if ( $("#arttitle").val() == '' ) {
            alert('You must enter in an article title');
            runpreview = false;
        }
        if ( $("#artdatetime").val() == '' ) {
            alert('You must enter in an article date/time');
            runpreview = false;
        }
        if ( $("#artarea").val() == 0 ) {
            alert('You must select an article area');
            runpreview = false;
        }
        if ( $("#arttext").val() == '' ) {
            alert('You must enter in some article text');
            runpreview = false;
        }
        if ( $("#artlink").val() != '' ) {
            if ( $("#artlink").val().length > 8 ) {
                if ( $("#artlink").val().toLowerCase().substring(0,7) == 'http://' || $("#artlink").val().toLowerCase().substring(0,8) == 'https://' ) {
                    //Do nothing
                } else {
                    alert('Your link must start http:// or https://');
                    runpreview = false;
                }
            }
        }
        if ( runpreview == true ) {
            var tempwin = window.open('http://www.alltern8.com/library/article_preview.asp', '', 'width=1000,height=600,resizeable,scrollbars');
        }
    });
    
    //Elements used in the page for hover/calendar which need binding and rebinding on page refresh
    ReBindDisplayElements();

    // Force this to be hidden

    //Lets give this a try at least
    $(".userprfilewhaticonsback div > img").live("click", function(e) {
        if (e.button != 0) { return false; } // Abort function, this will not cancel event, basicly we only want left click
        if (tBState == $(this).attr("title"))
            return false;
        if (tBState.length > 0)
            TopBar_DoUnload(tBState);
        tBState = $(this).attr("title") == "Blog" ? "" : $(this).attr("title");
        switch ($(this).attr("title")) {
            case "Blog":
                $("#userprofileaction").children().remove(); $("#userprofileaction").hide();
                $("#userprofilebutadd").show();
                GetParentOfType($(this), "form").attr("target", "internal");
                break;
            default:
                $("#userprofileaction").show();
                $("#userprofilebutadd").hide();
                GetParentOfType($(this), "form").attr("target", $(this).attr("title").toLowerCase());
                TopBar_DoLoad($(this).attr("title"));
                break;
        }
    });

    //If document has no hash, we just set the default
    if (location.hash.length <= 1) {
        var initURL = "";
        var qS = "";
        if (document.URL.indexOf("?") > 0) {
            initURL = document.URL.substring(0, document.URL.indexOf("?"));
            qS = document.URL.substr(document.URL.indexOf("?") + 1);
        } else {
            initURL = document.URL;
        }
        var tSplit = initURL.split("/");
        if (tSplit.length > 0) {
            if (tSplit[tSplit.length - 1].length > 0) {
                if (tSplit[tSplit.length - 1].toLowerCase() != "default.asp") {
                    initURL = "/" + tSplit[tSplit.length - 1];
                } else {
                    initURL = "/blog.asp";
                }
            } else {
                initURL = "/blog.asp"
            }
        } else {
            initURL = "/blog.asp"
        }
        initURL = (qS.length > 0) ? initURL + "?" + qS : initURL;
        location.hash = "#" + initURL;
        //if (b_initHash == true)
        //c_Hash = "#/profile.asp";
        //        if ($("#whatnow").length) {
        //            $("#whatnow").elastic();
        //}
        //PartialUpdateReBind();
    }


    //Page Spooler - clear
    /*if (c_HashTimer != null) {
    clearInterval(c_HashTimer);
    c_HashTimer = null;
    }*/


    //Page Spooler - Do something
    c_HashTimer = setInterval(function() {
        if (location.hash != c_Hash) {
            //The hash has changed
            c_Hash = location.hash;
            if ($("#bd_main").length) {
                //We have a target item.
                //$("#bd_main").load(
                b_initHash = false;
                if (location.hash.indexOf("#") == 0) {
                    s_Hash = location.hash.substring(2);
                } else {
                    s_Hash = location.hash;
                }
                ShowLoading();
                ClearInternalForms();
                if (location.hash.indexOf("?") > 0) {
                    PROFILE_U_ID = MY_U_ID;
                    var qS = location.hash.substr(location.hash.indexOf("?") + 1);
                    if (qS.indexOf("&") >= 0) {
                        var qSSplit = qS.split("&");
                        for (var qSElem in qSSplit) {
                            if (qSSplit[qSElem].indexOf("=") >= 0) {
                                var qSItem = qSSplit[qSElem].split("=");
                                if (qSItem[0].toLowerCase() == "profile") {
                                    if (!isNaN(qSItem[1])) {
                                        PROFILE_U_ID = qSItem[1];
                                    }
                                }
                            }
                        }
                    } else {
                        if (qS.substr(0, 8).toLowerCase() == "profile=") {
                            if (!isNaN(qS.substr(8))) {
                                PROFILE_U_ID = qS.substr(8);
                            } else {
                                PROFILE_U_ID = MY_U_ID;
                            }
                        } else {
                            PROFILE_U_ID = MY_U_ID;
                        }
                    }
                } else {
                    PROFILE_U_ID = MY_U_ID;
                }
                //$("#bd_main").contents().remove();
                $("#bd_main").load("/members/" + s_Hash, { InternalView: 1 }, function(responseText, textStatus, XMLHttpRequest) {
                    tBState = "";
                    if (XMLHttpRequest.status != 200) {
                        alert("Something isnt working - error " + XMLHttpRequest.status);
                    } else {
                        if ($("textarea[").length) {
                            $("#whatnow").elastic();
                            $("#userprofileaction").hide();
                        }
                        PartialUpdateReBind();
                        HideLoading();
                    }
                });
            }
        }
    }, 100);


    //Internal link hooking.
    $("a[rel='internal']").live("click", function(e) {
        if (e.button != 0) { return true; }
        location.hash = "#" + $(this).attr("href").replace("/members/", "/").replace("http://www.alltern8.com", "").replace("http://alltern8.com", "");
        //location.href = location.href.replace(location.hash, "") + "#" + $(this).attr("href").replace("/members/", "/").replace("http://www.alltern8.com", "").replace("http://alltern8.com", "");
        return false;
    });
    $("img[rel='reply']").live("click", function(e) {
        if (e.button != 0) { return true; }
        var ev = jQuery.Event("click");
        ev.button = 0;
        $(this).parent().parent().find("div[rel='reply']:first").trigger(ev);
    });
    
    $("div[rel='reply']").live("click", function(e) {
        if (e.button != 0) { return true; }
        var tParent = $(this).parent().parent().parent();
        $(this).data("f_close", 0);

        $("*[rel='report']").each(function() {
            var cParent = $(this).parent().parent().parent();
            if ($(this).data("m_State") == 1) { 
                cParent.find('.upareport').slideUp(500);
                cParent.find("div[rel='report']").data("m_State", 0);
            }
        });

        $("div[rel='reply']").each(function() {
            if ($(this).data("m_State") == 1) {
                $(this).parent().parent().parent().find('.upareply').slideUp(500);
                $(this).data("m_State", 0);
                $(this).data("f_close", 1);
            }
        });
        if ($(this).data("m_State") == 1) {
            tParent.find('.upareply').slideUp(500);
            $(this).data("m_State", 0);
        } else {
            if ($(this).data("f_close") != 1) {
                tParent.find('.upareply').slideDown(500);
                $(this).data("m_State", 1);
            } else {
                $(this).data("f_close", 0);
                $(this).data("m_State", 0);
            }
        }
    });

    $("#AddFriend, #DelFriend").live("click", function(e) {
        if (e.button != 0) { return true; }
        var tForm = $(this).parent();
        var tThis = $(this);
        var tArray = {};
        $(tForm).find("input, textarea, select").each(function() {
            if ($(this).attr("name").length && $(this).val().length) {
                tArray[$(this).attr("name")] = $(this).val();
            }
        });
        //As the URL is internal - we now just remove /members and replace it with /members/action
        var tURL = $(tForm).attr("action").replace("/members", "/members/action");
        $.ajax({
            type: "POST",
            url: tURL,
            data: tArray,
            success: function(val) {

                if (tThis.attr("id") == "AddFriend") {
                    //
                    tThis.parent().html("Request Pending...");
                } else {

                    tThis.parent().find("input[name='action']").val("fadd");
                    tThis.attr("id", "AddFriend");
                    tThis.attr("src", tThis.attr("src").replace("remove", "add"));
                }
            }
        });
        return false;
    });
    
    $("#amendmiddle").live("click", function(e) {
        $('.userprofilecol2').html('<div id="preloader"><div id="preloaderimg"></div></div>');
        var tURL = $(this).attr("attr");
        $.ajax({
            type: "POST",
            url: tURL,
            success: function(r) {
                $('.userprofilecol2').html(r);
            },
            complete: function(r) {
                PartialUpdateReBind();  
            }            
        });
    });
    
    $("#amendmiddlefriends").live("click", function(e) {
        $('.userprofilecol2').html('<div id="preloader"><div id="preloaderimg"></div></div>');
        var tURL = $(this).attr("attr");
        $.ajax({
            type: "POST",
            url: tURL,
            success: function(r) {
                $('.userprofilecol2').html(r);
            },
            complete: function(r) {
                PartialUpdateReBind();  
            }            
        });
    });

    $("#amendmiddleblog").live("click", function(e) {
        $('.userprofilecol2').html('<div id="preloader"><div id="preloaderimg"></div></div>');
        var tURL = $(this).attr("attr");
        $.ajax({
            type: "POST",
            url: tURL,
            success: function(r) {
                $('.userprofilecol2').html(r);
            },
            complete: function(r) {
                PartialUpdateReBind();  
            }            
        });
    });
    $("#showivlink").live("click", function(e) {
        $('#iv_hidden').hide();
        $('#iv_show').show();
        return false;
    });

    $("#hideivlink").live("click", function(e) {
        $('#iv_show').hide();
        $('#iv_hidden').show()
        return false;
    });

    $("#hidegrplink").live("click", function(e) {
        $('#grp_show').toggle();
        return false;
    });

    $("#hidegrpsearchlink").live("click", function(e) {
        $('#grp_search_show').toggle();
        return false;
    });

    $("#toggleEmailFrom").live("click", function(e) {
        $('#emailformsent').hide();
        $('#emailformhide').toggle();
        $('#emailformshow').toggle();
        return false;
    });
    
    $("#selectall").live("click", function(e) {
       $("input[rel='joincheckbox']").each(
          function() {
           $(this).attr('checked', true)
          }
        );   
        return false;
    });
    
    $("#selectnone").live("click", function(e) {
        $("input[rel='joincheckbox'][checked]").each(
          function() {
           $(this).attr('checked', false)
          }
        ); 
        return false;
    });
    
    $("#joingroups").live("click", function(e) {
        var varIntJoined = 0;
        var varIntAuth = 0;
        var varIntError = 0;
        ShowAddLoading();
        $("input[rel='joincheckbox'][checked]").each(function() {
        
            var GID = $(this).val();
            var GName = $(this).attr('grpname');            
            var mail_data = {};
            mail_data["action"] = "gjoin";
            mail_data["Group"] = GID;
               
            var tURL = "/groups/action/groups.asp";
            $.ajax({
                type: "POST",
                url: tURL,
                data: mail_data,
                dataType: "json",
                success: function(r) {
                    // Response will have a few bits of information - if the group is not public, membership is not instant for eg
                    if (r.RText == "success") {
                        varIntJoined=varIntJoined+1;
                    } else if (r.RText == "pending") {
                        varIntAuth=varIntAuth+1;
                    } else {
                        varIntError=varIntError+1;
                    }
                }
            });
          }
        );
        //Set a timeout as the jQuery seems to take a bit of time to run
        setTimeout(function() {
            if ( varIntJoined > 0 || varIntAuth > 0 || varIntError > 0 ) {
                var strOutPut = 'Multiple Group Joining Completed\n\n';
                if ( varIntJoined > 0) {
                    strOutPut = strOutPut + 'You have sucessfully joined ' + varIntJoined + ' group(s)\n\n';
                }
                if ( varIntAuth > 0) {
                    strOutPut = strOutPut + '' + varIntAuth + ' group(s) will require authorisation from the group admin\n\n';
                }
                if ( varIntError > 0) {
                    strOutPut = strOutPut + '' + varIntError + ' group(s) have errors\n\n';
                } 
                HideAddLoading();
                alert(strOutPut);
            };
            setTimeout(function(){  
                document.location.reload();
            },1000);
        },2000);
        return false;
    });
    
    $("#addfriends").live("click", function(e) {
        var varAdded = 0;
        ShowAddLoading();
        $("input[rel='joincheckbox'][checked]").each(function() {
        
            var FRID = $(this).val();
            var FRName = $(this).attr('membername');            
            var mail_data = {};
            mail_data["action"] = "fadd";
            mail_data["Profile"] = FRID;
               
            var tURL = "/members/action/profile.asp";
            $.ajax({
                type: "POST",
                url: tURL,
                data: mail_data,
                dataType: "json",
                success: function(r) {
                    varAdded=varAdded+1;
                }
            });
          }
        );
        //Set a timeout as the jQuery seems to take a bit of time to run
        setTimeout(function() {
            if ( varAdded > 0 ) {
                var strOutPut = 'Multiple Friend Requests Sent\n\n';
                if ( varAdded > 0) {
                    strOutPut = strOutPut + 'You have sent friend requests to ' + varAdded + ' users\n\n';
                }
                alert(strOutPut);
                setTimeout(function(){    
                    HideAddLoading();
                    document.location.reload();
                },1000);
            };
        },4000);
        return false;
    });
    
    $("img[rel='report']").live("click", function(e) {
        if (e.button != 0) { return true; }
        var ev = jQuery.Event("click");
        ev.button = 0;
        $(this).parent().parent().find("div[rel='report']:first").trigger(ev);
    });
    $("input[name='frAccept']").live("click", function(e) {
        if (e.button != 0) { return true; }
        $form = GetParentOfType($(this), "form");
        $form.find("input[name='sact']").val("accept");
    });
    $("input[name='frDeny']").live("click", function(e) {
        if (e.button != 0) { return true; }
        $form = GetParentOfType($(this), "form");
        $form.find("input[name='sact']").val("deny");
    });
    $("div[rel='report']").live("click", function(e) {
        if (e.button != 0) { return true; }
        var tParent = $(this).parent().parent().parent();
        $("*[rel='reply']").each(function() {
            if ($(this).data("m_State") == 1) {
                var cParent = $(this).parent().parent().parent();
                cParent.find('.upareply').slideUp(500);
                cParent.find("div[rel='reply']").data("m_State", 0);
            }
        });

        tParent.find("div[rel='report']").data("f_close", 0);
        $("*[rel='report']").each(function() {
            if ($(this).data("m_State") == 1) {
                var cParent = $(this).parent().parent().parent();
                cParent.find('.upareport').slideUp(500);
                cParent.find("div[rel='report']").data("m_State", 0);
                cParent.find("div[rel='report']").data("f_close", 1);
            }
        });
        if ($(this).data("m_State") == 1) {
            tParent.find('.upareport').slideUp(500);
            tParent.find("div[rel='report']").data("m_State", 0);
        } else {
            if ($(this).data("f_close") != 1) {
                tParent.find('.upareport').slideDown(500);
                tParent.find("div[rel='report']").data("m_State", 1);
            } else {
                tParent.find("div[rel='report']").data("f_close", 0);
                tParent.find("div[rel='report']").data("m_State", 0);
            }
        }
    });

    $(".friendsallgroup > .butdelete").live("click", function(e) {
        if (e.button != 0) { return true; }
        var friend_del = $(this).parent();
        var friend_text = friend_del.find(".friendsallpictext");
        var friend_id = friend_del.find("input").val();
        var friend_text_a = friend_text.find("a");
        var friend_name = "Unknown"
        if (friend_text_a.length > 0) {
            friend_name = $.trim(friend_text_a.text());
        }
        if (confirm("Are you sure that you would like to delete the friend \"" + friend_name + "\"?")) {
            var friend_data = {};
            friend_data["action"] = "fdel";
            friend_data["Profile"] = friend_id;
            $.ajax({
                type: "POST",
                url: '/members/action/profile.asp',
                data: friend_data,
                success: function(val) {
                    friend_del.remove();
                    friend_del = null; friend_text = null; friend_id = null; friend_text_a = null; friend_name = null; friend_data = null;
                }
            });
        }
    });

    $(".mailboxbutdelete").live("click", function(e) {
        if (e.button != 0) { return true; }
        var mail_del = $(this).parent().parent();
        var mail_text = mail_del.find(".emailsubject");
        var mail_id = mail_del.find("input").val();
        var mail_text_a = mail_text.find("a");
        var mail_name = "Unknown"
        if (mail_text_a.length > 0) {
            mail_name = $.trim(mail_text_a.text());
        }
        if (confirm("Are you sure that you would like to delete the mail\"" + mail_name + "\"?")) {
            var mail_data = {};
            mail_data["action"] = "mdel";
            mail_data["Mail"] = mail_id;
            $.ajax({
                type: "POST",
                url: '/members/action/profile.asp',
                data: mail_data,
                success: function(val) {
                    mail_del.remove();
                    mail_del = null; mail_text = null; mail_id = null; mail_text_a = null; mail_name = null; mail_data = null;
                }
            });
        }
        return false;
    });
    
    $(".mailreply").live("click", function(e) {
        if (e.button != 0) { return true; }
        
        mail_id = $(this).attr('rel')
        var mail_data = {};
        mail_data["action"] = "mreply";
        mail_data["Mail"] = mail_id;
        $.ajax({
            type: "POST",
            url: '/members/action/profile.asp',
            data: mail_data,
            dataType: "json",
            success: function(json) {
                $("#emailformsent").hide();
                
                replyName = json.response.replyName;
                replyID = json.response.replyID;
                replySubject = json.response.replySubject;
                replyMessage = json.response.replyMessage;
                
                $("#EM_Subject").val('RE:'+replySubject); 
                EditorBox.UpdateEditorValue(replyMessage);
                
                var select = $('#EM_To');               
                select.children().remove().end().append("<option value='"+ replyID +"'>"+replyName+"</option>");
            }
        });
        return false;
    });

    $("#EM_Submit").live("click", function(e) {
        if (e.button != 0) { return true; }
        
        //As we're using a texteditor, firstly update the hidden textarea box before submitting the form
        EditorObject.UpdateEditorFormValue();
        var EM_To = $("#EM_To").val();
        var EM_Importance = $("#EM_Importance").val();
        var EM_Subject = $("#EM_Subject").val();
        var EM_Message = $("#EM_Message").val();
        if (EM_To > 0 && EM_Message != '') {
            var mail_data = {};
            mail_data["action"] = "msend";
            mail_data["EM_To"] = EM_To;
            mail_data["EM_Importance"] = EM_Importance;
            mail_data["EM_Subject"] = EM_Subject;
            mail_data["EM_Message"] = EM_Message;
            $.ajax({
                type: "POST",
                url: '/members/action/profile.asp',
                data: mail_data,
                success: function(val) {
                    ClearEmailForm();
                    $("#emailformsent").show();
                },
                error: function(val) {
                    alert('There was a problem sending this email, please check and try again');
                }
            });
        } else {
            alert('You must select a friend to send this email to.');
        }
        return false;
    });
    
    $("#EM_NewEmail").live("click", function(e) {
        return ClearEmailForm();
    });

    function ClearEmailForm() {
        $("#emailformsent").hide();
        //Set the Subject
        $("#EM_Subject").val(''); 
        //Set the Message
        EditorBox.UpdateEditorValue(' ');
        //Reset the Friends
        $.ajax({
            type: "POST",
            url: '/members/action/getmyfriends.asp',
            success: function(val) {
                var select = $('#EM_To');
                select.children().remove().end().append(val);
            }
        });
        return false; 
    }

    $(".groupsallgroup > .butdelete").live("click", function(e) {
        if (e.button != 0) { return true; }
        
        //alert('Leave Group Pressed');
        var group_del = $(this).parent();
        var group_text = group_del.find(".groupsallpictext");
        var group_id = group_del.find("input").val();
        var group_text_a = group_text.find("a");
        var group_name = "Unknown"
        if (group_text_a.length > 0) {
            group_name = $.trim(group_text_a.text());
        }
        if (confirm("Are you sure that you would like to leave the group \"" + group_name + "\"?")) {
            var group_data = {};
            group_data["action"] = "gleave";
            group_data["Group"] = group_id;
            $.ajax({
                type: "POST",
                url: '/groups/action/groups.asp',
                data: group_data,
                success: function(val) {
                    group_del.remove();
                    group_del = null; group_text = null; group_id = null; group_text_a = null; group_name = null; group_data = null;
                }
            });
        }
    });
    
    function PartialUpdateReBind() {
        //For now until there is a better method, we'll also do the re-hooks for photo page too
        if (typeof PhotoPage_Begin == "function")
            PhotoPage_Begin();

        if (typeof pehb_hook == "function") //ProfileEdit
            pehb_hook();

        if (typeof peas_hook == "function") //ProfileEditAvatarSelection - P.E.A.S
            peas_hook();

        if (typeof calendar_hook == "function")
            calendar_hook();

        BindInternalForms();
        ReBindDisplayElements();
        $('input[type=radio].star').rating();
        tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
        imgLoader = new Image(); // preload image
        imgLoader.src = tb_pathToImage;
             
    }

    function ReBindDisplayElements() {
        $(".btn_black").each(function() {
            $("<div class=\"btn_black_end\">").insertAfter($(this));
        });
        $(".upalreplies").mouseover(function() {
            $(this).addClass("replieshover");
            //$(this).find(".upalrepliesremove").show();
        });
        $(".upalreplies").mouseout(function() {
            $(this).removeClass("replieshover");
            //$(this).find(".upalrepliesremove").hide();
        });
        $(".upacontent").mouseover(function() {
            //$(this).find(".upalcontentremove").show();
        });
        $(".upacontent").mouseout(function() {
            //$(this).find(".upalcontentremove").hide();
        });
        $(".friendsallgroup").mouseover(function() {
            $(this).addClass("friendhover");
            $(this).find(".butdelete").show();
        });
        $(".friendsallgroup").mouseout(function() {
            $(this).removeClass("friendhover");
            $(this).find(".butdelete").hide();
        });
        $(".groupsallgroup").mouseover(function() {
            $(this).addClass("grouphover");
            $(this).find(".butdelete").show();
        });
        $(".groupsallgroup").mouseout(function() {
            $(this).removeClass("grouphover");
            $(this).find(".butdelete").hide();
        });
        
        $('input:checkbox:not([safari])').checkbox();
        
	    $('.upamessage').each(function() {
            var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/<]))?)/gi;   
            $(this).html(   
                $(this).html().replace(regexp,'<A href="$1" target="_blank">$1</A>')   
            );   
        });

    }
    
    function ClearInternalForms() {
        if ($("form[target='internal']").length) {
            $("form[target='internal']").each(function() {
                $(this).unbind("submit");
            });
        }
        if ($("form[target='reply']").length) {
            $("form[target='reply']").each(function() {
                $(this).unbind("submit");
            });
        }

        if ($("form[target='complain']").length) {
            $("form[target='complain']").each(function() {
                $(this).unbind("submit");
            });
        }

        if ($("form[target='internalhide']").length) {
            $("form[target='internalhide']").each(function() {
                $(this).unbind("submit");
            });
        }

        if ($("#friend_form").length) {
            $("#friend_form").unbind("submit");
        }
        if ($("#grp_form").length) {
            $("#grp_form").unbind("submit");
        }
        if ($("#iv_form").length) {
            $("#iv_form").unbind("submit");
        }        
    }

    function BindInternalForms() {
        if ($("#iv_form").length) {
            //We have an invite form somewhere around :o
            $("#iv_form").unbind("submit").submit(function() {
                //Updated the contents:
                $("#iv_names").val($("#iv_names").val().replace("\r", ""));
                var tArr = Array();
                tArr = $("#iv_names").val().split("\n");
                for (var i = 0; i < tArr.length; i++) {
                    if (jQuery.trim(tArr[i]).length > 0) {
                        if (!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(jQuery.trim(tArr[i])))) {
                            tArr.splice(i, 1); // Not valid email, remove it - we need to move the counter back one also
                            i--;
                        }
                    } else {
                        tArr.splice(i, 1);
                        i--;  //Counter needs to be moved back 1 to offset the removal of array item.
                    }
                }
                // Now to get this to function as we'd hope, we need to iterate through the array again producing a HTML element and
                if ($("#iv_resultparent").length) {
                    $("#iv_resultparent").remove();
                }
                var pDiv = $("<div />").attr("id", "iv_resultparent");
                $("#iv_target").append(pDiv);


                var iDiv;
                for (i = 0; i < tArr.length; i++) {
                    iDiv = $("<div />").attr("id", "ivblock_" + i);
                    pDiv.append(iDiv);
                    iDiv.append($("<div />").attr("id", "ive_" + i).attr("class", "ev_left").text(tArr[i]));
                    iDiv.append($("<div />").attr("id", "ivr_" + i).attr("class", "ev_right").html("<img src=\"/images/alltern8-main/user_profile/preloader_small.gif\" />"));

                    //We've appended the DOM - now we have to do the lovely task of actually calling the ajax script.
                    $.ajax({
                        type: "POST",
                        url: "/members/action/invite.asp",
                        data: { iv_addr: tArr[i], iv_id: i },
                        dataType: "json",
                        success: function(json) {
                            var sClass = "";
                            var sText = "";
                            if (json.response.sType == 'user') {
                                switch (json.response.sResult) {
                                    case 0:
                                        sClass = "fr_pending";
                                        sText = "Friend request pending with %s";
                                        break;
                                    case 1:
                                        sClass = "fr_added";
                                        sText = "Requested %s to be your friend";
                                        break;
                                    case 2:
                                        sClass = "fr_exist";
                                        sText = "%s is already your friend!";
                                        break;
                                }
                                var tLink = sText.replace("%s", "<a href=\"/members/profile.asp?Profile=" + json.response.sPID + "\" rel=\"internal\">" + $("<div />").text(json.response.sName).html() + "</a>");
                                $("#ivr_" + json.iv_id).html(tLink);
                                $("#ivr_" + json.iv_id).addClass(sClass);
                            } else {
                                if (json.response.sResult == 0) {
                                    $("#ivr_" + json.iv_id).html("Unable to send email, have you alredy invited them?");
                                    $("#ivr_" + json.iv_id).addClass("em_fail");
                                } else {
                                    $("#ivr_" + json.iv_id).html("Email Sent!");
                                    $("#ivr_" + json.iv_id).addClass("em_sent");
                                }
                            }
                        }
                    });
                }
                //pDiv.text(sMsg);
                return false;
            });
        }
        
        if ($("#friend_form").length) {
            //We have an invite form somewhere around :o
            $("#friend_form").unbind("submit").submit(function() {
                //Updated the contents:
                var friend_name = $("#friend_name").val();
                var friend_area = $("#friend_areas").val();
                
                friend_name = friend_name.replace("\r", "");
                
                ShowSearchLoading();
                $("#friendssearchpages").html('');
                $("#friend_search_show").hide();
                        
                $.ajax({
                    type: "POST",
                    url: "/members/action/friend_search.asp",
                    data: { friend_name: friend_name, friend_area: friend_area },
                    dataType: "json",
                    success: function(json) {
                        
                        var intTotalFriends = 9999;
                        thisGroup = ''
                        for (var i=0; i < json.response.length; i++) {
                        
                            var iID, sPhoto, sName, thisGroup;
                            
                            iID = json.response[i].iID;
                            sPhoto = json.response[i].sPhoto;
                            sName = json.response[i].sName;
                            sLocation = json.response[i].sLocation;
                            iFriend = json.response[i].iFriend;
                            
                            if ( intTotalFriends == 9999 ) {
                                thisGroup = thisGroup + '<span class="friendpages">';
                                intTotalFriends = 0;
                            }
                            
                            if (iFriend == 1 ) {
                                strChecked = ' checked="checked" disabled="disabled" membername="'+sName+'"'
                            } else {
                                strChecked = ' rel="joincheckbox" membername="'+sName+'"'
                            }
                            
                            thisGroup = thisGroup + '<div class="friendsallgroup"><input type="hidden" name="trUID" value="' + iID + '" />'
                            thisGroup = thisGroup + '<div class="friendsallpic"><a href="/members/profile.asp?Profile=' + iID +'"><img src="' + sPhoto + '" alt="' + sName + '" title="' + sName + '" /></a></div>'
                            thisGroup = thisGroup + '<div class="friendsallpictext"><a href="/members/profile.asp?Profile=' + iID + '">' + sName + '</a></div>'
                            thisGroup = thisGroup + '<div class="butjoin"><input type="checkbox" ' + strChecked + ' class="friendinput" name="FR_Add" value="'+iID+'"></div>'
                            thisGroup = thisGroup + '<div class="friendslocation">'+sLocation+'</div>'
                            thisGroup = thisGroup + '</div>'
                            
                            intTotalFriends = intTotalFriends + 1
                            if ( intTotalFriends == 15 ) {
                                thisGroup = thisGroup + '</span>';
                                intTotalFriends = 9999;
                            }                           
                        }      
                        if ( intTotalFriends != 9999 ) {
                            thisGroup = thisGroup + '</span>'    
                        }          
                        
                        HideSearchLoading();
                        if ( thisGroup != '' ) {
                            
                            $("#friend_search_show").show();
                            $("#friend_search_show").find('#searchtext').show();
                            $("#friend_search_show").find('#searchbuts').show();
                            
                            $("#friendssearchpages").html($("#friendssearchpages").html() + thisGroup);                            
                            $('#friendssearchpages').pager('span.friendpages',{prevText: '<<',nextText: '>>',linkText: ['[1]','[2]','[3]','[4]','[5]','[6]','[7]','[8]','[9]','[10]','[11]','[12]','[13]']});
                            
                            $('.friendinput').checkbox();
                        } else {
                        
                            $("#friend_search_show").show();
                            $("#friendssearchpages").html($("#friendssearchpages").html() + '<p style="text-align:center;font-weight:bold;">There are no people matching this search, you may have already added them. If you can\'t find them simply put their email address in the box at the top and we\'ll email them for you</p>');
                            $("#friend_search_show").find('#searchtext').hide();
                            $("#friend_search_show").find('#searchbuts').hide();
                        }
                    },
                    error: function(json) {
                        $("#friend_search_show").find(".friendsallmain").html('Unfortunately there were no matching friends');
                    }
                });
                
                //Show results
                return false;
            });
        }


        if ($("#grp_form").length) {
            //We have an invite form somewhere around :o
            $("#grp_form").unbind("submit").submit(function() {
                //Updated the contents:
                var grp_name = $("#grp_name").val();
                var grp_area = $("#grp_areas").val();
                
                grp_name = grp_name.replace("\r", "");
                
                ShowSearchLoading();
                $("#groupsearchpages").html('');
                $("#grp_search_show").hide();
                
                $.ajax({
                    type: "POST",
                    url: "/members/action/group_search.asp",
                    data: { grp_name: grp_name, grp_area: grp_area },
                    dataType: "json",
                    success: function(json) {
                        $("#groupsearchpages").html('');
                        var intTotalGroups = 9999;
                        var thisGroup = '';
                        for (var i=0; i < json.response.length; i++) {
                        
                            var iID, sPhoto, sName, thisGroup;
                            
                            iID = json.response[i].iID;
                            sPhoto = json.response[i].sPhoto;
                            sName = json.response[i].sName;
                            iMember = json.response[i].iMember;
                            
                            if ( intTotalGroups == 9999 ) {
                                thisGroup = thisGroup + '<span class="grouppages">';
                                intTotalGroups = 0;
                            }
                            
                            if (iMember == 1 ) {
                                strChecked = ' checked="checked" disabled="disabled" grpname="'+sName+'"'
                            } else {
                                strChecked = ' rel="joincheckbox" grpname="'+sName+'"'
                            }
                            
                            thisGroup = thisGroup + '<div class="groupsallgroup"><input type="hidden" name="trGRPID" value="' + iID + '" />'
                            thisGroup = thisGroup + '<div class="groupsallpic"><a href="/groups/groups.asp?Group=' + iID +'"><img src="' + sPhoto + '" alt="' + sName + '" title="' + sName + '" /></a></div>'
                            thisGroup = thisGroup + '<div class="groupsallpictext"><a href="/groups/groups.asp?Group=' + iID + '">' + sName + '</a></div>'
                            thisGroup = thisGroup + '<div class="butjoin"><input type="checkbox" ' + strChecked + ' class="groupinput" name="GRP_Join" value="'+iID+'"></div>'
                            thisGroup = thisGroup + '</div>'
                        
                            intTotalGroups = intTotalGroups + 1
                            if ( intTotalGroups == 15 ) {
                                thisGroup = thisGroup + '</span>';
                                intTotalGroups = 9999;
                            }  
                        }  
                        if ( intTotalGroups != 9999 ) {
                            thisGroup = thisGroup + '</span>'    
                        }          
                        
                        HideSearchLoading();
                        if ( thisGroup != '' ) {
                            //Show results
                            $("#grp_search_show").show();
                            $("#grp_search_show").find('#searchtext').show();
                            $("#grp_search_show").find('#searchbuts').show();
                            
                            $("#groupsearchpages").html($("#groupsearchpages").html() + thisGroup);                            
                            $('#groupsearchpages').pager('span.grouppages',{prevText: '<<',nextText: '>>',linkText: ['[1]','[2]','[3]','[4]','[5]','[6]','[7]','[8]','[9]','[10]','[11]','[12]','[13]']});
                                       
                            $('.groupinput').checkbox();
                        } else {
                        
                            $("#grp_search_show").show();
                            $("#groupsearchpages").html($("#groupsearchpages").html() + '<p style="text-align:center;font-weight:bold;">There are no groups matching this search, you may have already joined them or they may not exist (so why not start one!).</p>');
                            $("#grp_search_show").find('#searchtext').hide();
                            $("#grp_search_show").find('#searchbuts').hide();
                        }                       
                    },
                    error: function(json) {
                        $("#grp_search_show").find(".groupsallmain").html('Unfortunately there were no matching groups');
                    }
                });
                
                return false;
            });
        }
        
        if ($("form[target='internalhide']").length) {
            $("form[target='internalhide']").unbind("submit").submit(function() {
                var tForm = this;
                var tTarget = $(this);
                if ($(this).attr("hidetarget") != undefined) {
                    if ($(tTarget.attr("hidetarget")).length > 0) {
                        tTarget = $(tTarget.attr("hidetarget"));
                    }
                }
                var tArray = {};
                $(this).find("input, textarea, select").each(function() {
                    if ($(this).attr("name").length && $(this).val().length) {
                        tArray[$(this).attr("name")] = $(this).val();
                    }
                });
                //As the URL is internal - we now just remove /members and replace it with /members/action
                var tURL = $(tForm).attr("action").replace("/members", "/members/action");
                $.ajax({
                    type: "POST",
                    url: tURL,
                    data: tArray,
                    success: function() {
                        //c_Hash = ""; // Testing something
                        $(tForm).unbind("submit");
                        tForm = tTarget.parent();
                        tTarget.remove();
                        if (tForm.hasClass("requestfriend")) {
                            if (tForm.children().length <= 2) {
                                tForm.remove();
                                tForm = null;
                            }
                        }
                        tTarget.hide();
                        var tDiv = GetParentOfType(tTarget, "div");
                        if (tDiv != null) {
                            tDiv.remove();
                        }
                        tDiv = null;
                        tTarget = null;
                        return false;
                    }
                });
            });
        }
        if ($("form[target='internal']").length) {
            $("form[target='internal']").each(function() {
                $("form[target='internal']").unbind("submit").submit(function() {
                    var tForm = this;
                    var tArray = {};
                    $(this).find("input, textarea, select").each(function() {
                        if ($(this).attr("name").length && $(this).val().length) {
                            tArray[$(this).attr("name")] = $(this).val();
                        }
                    });
                    //As the URL is internal - we now just remove /members and replace it with /members/action
                    var tURL = $(tForm).attr("action").replace("/members", "/members/action");
                    $.ajax({
                        type: "POST",
                        url: tURL,
                        data: tArray,
                        success: function() {
                            tForm.reset();
                            c_Hash = ""; // Testing something
                        }
                    });
                    return false;
                });
            });
        }
        if ($("form[target='reply']").length) {
            $("form[target='reply']").each(function() {
                var tForm = this;
                $(this).unbind("submit").submit(function() {
                    $(tForm).parent().parent().find(".upareplyloading").show();
                    $(tForm).parent().slideToggle(500);
                    var tArray = {};
                    $(this).find("input, textarea, select").each(function() {
                        if ($(this).attr("name").length && $(this).val().length) {
                            tArray[$(this).attr("name")] = $(this).val();
                        }
                    });
                    //As the URL is internal - we now just remove /members and replace it with /members/action
                    var tURL = $(tForm).attr("action").replace("/members", "/members/action");
                    $(tForm).parent().slideToggle(500);
                    $.ajax({
                        type: "POST",
                        url: tURL,
                        data: tArray,
                        success: function() {
                            tForm.reset();
                            //Future thing to do - use a response from action to update page - instead we'll just force the update of page
                            c_Hash = "";
                        },
                        error: function() {
                            $(tForm).parent().slideToggle(500);
                        }
                    });
                    return false;
                });
            });
        }

        if ($("form[target='complain']").length) {
            $("form[target='complain']").each(function() {
                var tForm = this;
                $(this).unbind("submit").submit(function() {
                    $.post("/xtusercomplaint.asp",
                        { CMPT_Name: $(this).find("input[name=ComplainName]").val(),
                            CMPT_Email: $(this).find("input[name=ComplainEmail]").val(),
                            CMPT_Complaint: $(this).find("textarea[name=Complaint]").val(),
                            CMPT_Type: $(this).find("input[name=ComplaintType]").val(),
                            CMPT_TypeID: $(this).find("input[name=ComplaintTypeID]").val(),
                            CMPT_Page: $(this).find("input[name=ComplaintPage]").val()
                        },
                        function() {
                            $(tForm).parent().slideToggle(500);
                        }
                    );
                    return false;
                });
            });
        }

    }

});
