// jQuery work

$(document).ready(function() {

    //IE6 adjacent sibling fix for tool drop-downs
    $(".drawerHandle + div").addClass("ToolBox");


    //Title icons - bookmark and subscription tooltips
    $("h1 .Bookmark").append('<span id="BookMarkExplanation" style="display: none;">Click to bookmark this page.</span>');
    $("h1 .Bookmark").hover(function() {
        $("#BookMarkExplanation").show();
    }, function() {
        $("#BookMarkExplanation").hide();
    });
    $("h1 .Subscription").append('<span id="AlertsExplanation" style="display: none;">Click to get emails when new content is added to this page.</span>');
    $("h1 .Subscription").hover(function() {
        $("#AlertsExplanation").show();
    }, function() {
        $("#AlertsExplanation").hide();
    });



    //create dashboard panels
    $("#masthead").append('<div id="StarsBoard" class="Dashboard fix"></div>');
    $("#masthead").append('<div id="ProfileBoard" class="Dashboard fix"></div>');
    $("#masthead").append('<div id="EditorBoard" class="Dashboard fix"></div>');
    $("#masthead").append('<div id="PostsBoard" class="Dashboard fix"></div>');
    refreshConsole();

    //email autopost
    $("#EasyMailLogin").css({ background: "url(/assets/i/ajax-loader.gif) 50% 50% no-repeat", height: "50px", width: "auto" });
    $("#EasyMailLogin").submit();


    //select all checkboxes
    $(".autocheck ul").before('<p class="browserRenderFix">Select <span class="checkall">all</span> <span class="uncheckall">none</span></p>');
    $(".autocheck ol").before('<p class="browserRenderFix">Select <span class="checkall">all</span> <span class="uncheckall">none</span></p>');
    $(".checkall").click(function() {
        $(this).parents('.autocheck').find('input[@type=checkbox]').attr('checked', 'checked');
    });
    $(".uncheckall").click(function() {
        //$(this).parents(".autocheck").children('input[@type=checkbox]').removeAttr('checked');
        $(this).parents('.autocheck').find('input[@type=checkbox]').removeAttr('checked');
    });


    //global search - fancy radio button selection
    $("#DashSearch fieldset").addClass("AutoSearch");
    PortalSearchFlag();
    $("#DashSearch li label").click(function() {
        PortalSearchFlag();
    });

    if ($(".hiddenPeopleSearch").val() == "1") {
        $("#DashSearch input[@type='radio']").each(
		    function() {
		        if (this.value == 'People') {
		            this.checked = true;
		            $(".hiddenPeopleSearch").val() == "0";
		            PortalSearchFlag();
		        }
		    }
	    );
    }

    if ($(".hiddenPlaceSearch").val() == "1") {
        $("#DashSearch input[@type='radio']").each(
		    function() {
		        if (this.value == 'Places') {
		            this.checked = true;
		            $(".hiddenPlaceSearch").val() == "0";
		            PortalSearchFlag();
		        }
		    }
	    );
    }

    if ($(".hiddenPostSearch").val() == "1") {
        $("#DashSearch input[@type='radio']").each(
		    function() {
		        if (this.value == 'Posts') {
		            this.checked = true;
		            $(".hiddenPostSearch").val() == "0";
		            PortalSearchFlag();
		        }
		    }
	    );
    }


    //striping + sorting tables
    $("table.sortable tr:nth-child(odd)").addClass("odd");

    $("table.sortable").tablesorter();
    //assign the sortStart event
    $("table").bind("sortEnd", function() {
        $("table.sortable tr").removeClass("odd");
        $("table.sortable tr:nth-child(odd)").addClass("odd");
    });


    // MonthlyHits
    $("#Hits").click(function() {
        $("#HitsCanvas").html('<p class="browserRenderFix"><img src="/assets/i/ajax-loader.gif" alt="Loading" /></p>');
        var vfmURL = $("#fmURL").attr("value");
        var vfmDomain = $("#fmDomain").attr("value");
        var vfmSectionRef = $("#fmSectionRef").attr("value");
        var vfmPageRef = $("#fmPageRef").attr("value");
        var vfmMonth = $("#fmMonth").attr("value");
        var vfmYear = $("#fmYear").attr("value");
        $.post("/apps/articles/stats/monthlyhits/wrapper/index.asp", {
            fmURL: vfmURL,
            fmDomain: vfmDomain,
            fmSectionRef: vfmSectionRef,
            fmPageRef: vfmPageRef,
            fmMonth: vfmMonth,
            fmYear: vfmYear
        },
			function(data) {
			    $("#HitsCanvas").html(data);
			}

						)
        return false;
    });


    //Tabs
    $("#NewsBlock > ul").tabs();
    $("#TabbedEditor > ul").tabs();

    $("#TabbedArea h2").append(" <img class=\"drawerArrow\" src=\"\/assets\/i\/icons\/trans\/bullet_arrow_down_white.gif\" alt=\"\" />");
    $("#TabbedArea h2").addClass("tabHandles")


    $('#TabbedArea>div').hide();
    $('#TabbedArea div:first').show();
    $('#TabbedArea h2').click(
        function() {
            var checkElement = $(this).next("div");
            $("#TabbedArea h2 img").attr("src", "\/assets\/i\/icons\/trans\/bullet_arrow_down_white.gif");

            if ((checkElement.is('div')) && (checkElement.is(':visible'))) {
                checkElement.slideUp('normal');
                checkElement.prev("h2").find("img").attr("src", "\/assets\/i\/icons\/trans\/bullet_arrow_down_white.gif");
            }
            if ((checkElement.is('div')) && (!checkElement.is(':visible'))) {
                $('#TabbedArea>div:visible').slideUp('normal');
                checkElement.slideDown('normal');
                checkElement.prev("h2").find("img").attr("src", "\/assets\/i\/icons\/trans\/bullet_arrow_up_white.gif");
            }
        }
    );


    //dashboard show + hide
    $("#PostsButton").click(function() {

        $("#StarsBoard").hide();
        $("#AlertsBoard").hide();
        $("#ProfileBoard").hide();
        $("#EditorBoard").hide();
    }).toggle(
			function() {
			    $("#PostsBoard").html('<p style="text-align: center;"><img src="/assets/i/ajax-loader.gif" alt="Loading" /></p>');
			    $("#PostsBoard").slideToggle("slow");
			    $("#PostsBoard").load("/people/posts/wrapper/default.aspx");
			},
			function() {
			    $("#PostsBoard").slideToggle("slow");
			}

		);

    $("#StarsButton").click(function() {

        $("#PostsBoard").hide();
        $("#AlertsBoard").hide();
        $("#ProfileBoard").hide();
        $("#EditorBoard").hide();
    }).toggle(
			function() {
			    $("#StarsBoard").html('<p style="text-align: center;"><img src="/assets/i/ajax-loader.gif" alt="Loading" /></p>');
			    $("#StarsBoard").slideToggle("slow");
			    $("#StarsBoard").load("/settings/stars/stars.aspx");
			},
			function() {
			    $("#StarsBoard").slideToggle("slow");
			}

		);

    $(".ProfilesButton").click(function() {
        $("#PostsBoard").hide();
        $("#AlertsBoard").hide();
        $("#StarsBoard").hide();
        $("#EditorBoard").hide();
    }).toggle(
			function() {
			    $("#ProfileBoard").html('<p style="text-align: center;"><img src="/assets/i/ajax-loader.gif" alt="Loading" /></p>');
			    $("#ProfileBoard").slideToggle("slow");
			    var s = "/people/profiles/Default.aspx?returnURL=" + escape(document.URL);
			    $("#ProfileBoard").load(s).ajaxStop(function() {
			        $("#ProfileSetting #Q").val(document.URL); //delay setting the value of the input until the form has loaded
			        $("#ProfileDefault #D").val(document.URL);
			    });

			},
			function() {
			    $("#ProfileBoard").slideToggle("slow");
			}

		);

    $("#EditorButton").click(function() {
        $("#PostsBoard").hide();
        $("#AlertsBoard").hide();
        $("#StarsBoard").hide();
        $("#ProfileBoard").hide();
    }).toggle(
			function() {
			    $("#EditorBoard").html('<p style="text-align: center;"><img src="/assets/i/ajax-loader.gif" alt="Loading" /></p>');
			    $("#EditorBoard").slideToggle("slow");
			    $("#EditorBoard").load("/people/account/sections/Header.aspx");
			},
			function() {
			    $("#EditorBoard").slideToggle("slow");
			}

		);



    //TAG MANAGER
    /*
    runTagCheck();
    //give the tags a cursor
    $(".TagList li").hover(
    function(){
    $(this).css("cursor","pointer");
    },
    function(){
    $(this).css("cursor","default");
    }
    );
		
		//add onclick to tags
    //updates the tag box with the new tag and highlights the term in the list
    $(".TagList li").click(function() {
    $(this).toggleClass('selected');
    if ($("#fmTags").attr("value")>"") {
    //check the box for pre-existing term
    var arrTerms = $("#fmTags").attr("value").split(",");
    var found = false;
    var newText;
    newText = "";
    for(i=0; i<arrTerms.length; i++) {
    if (jQuery.trim(arrTerms[i]) == $(this).text()) {
    //block the adding of the text again
    found = true;
    //console.log("found");
    } else {
    //add the selected text to the collector
    if (newText>""){
    newText = newText + ", "
    }
    newText = newText + jQuery.trim(arrTerms[i])
    }
    }
    $("#fmTags").attr("value",newText);
    if (found == false) {
    $("#fmTags").attr("value",$("#fmTags").attr("value") + ", " + $(this).text());
    }
    } else {
    $("#fmTags").attr("value",$(this).text());
    }
    runTagCheck();
    })
		
		//when something in the text-box changes
    $("#fmTags").keyup(function(){
    runTagCheck();
    });
    */

    //abilities form
    $(".abilityForm button").click(function() {
        var role = $(this).parent().parent().siblings("input")[0].value;
        var orgID = $(this).parent().parent().siblings("input")[1].value;
        var ability = $(this).parent().parent().siblings("input")[2].value;
        var userId = $(this).parent().parent().siblings("input")[3].value;
        $(this).load("/configure/people/abilities/toggle.ashx?mode=ajax&userId=" + userId + "&role=" + role + "&ability=" + ability + "&OrganizationId=" + orgID);
        return false;
    });

    //abilities organization form
    $(".abilityForm1 button").click(function() {
        var role = $(this).parent().parent().siblings("input")[0].value;
        var userId = $(this).parent().parent().siblings("input")[1].value;
        var ability = $(this).parent().parent().siblings("input")[2].value;
        var OrganizationID = $(this).parent().parent().siblings("input")[3].value;
        $(this).load("/configure/people/abilities/OrgToggler.ashx?mode=ajax&userId=" + userId + "&role=" + role + "&ability=" + ability + "&OrganizationID=" + OrganizationID);
        return false;
    });

    //abilities section form
    $(".abilityForm2 button").click(function() {
        var role = $(this).parent().parent().siblings("input")[0].value;
        var userName = $(this).parent().parent().siblings("input")[1].value;
        var ability = $(this).parent().parent().siblings("input")[2].value;
        var SectionID = $(this).parent().parent().siblings("input")[3].value;
        $(this).load("/configure/people/abilities/SectionToggler.ashx?mode=ajax&userName=" + userName + "&role=" + role + "&ability=" + ability + "&SectionID=" + SectionID);
        return false;
    });

    //Subscription toggle
    $(".Subscription").click(function() {
        //var arrUrl = $(this).attr("href").split("=");
        $(this).load($(this).attr("href") + "&mode=ajax");
        return false;
    });

    /*	//Bookmark toggle
    $(".Bookmark").click(function() {
    var myID = $(this).attr("id")
    var arrUrl = $(this).attr("href").split("?");
    $("#" + myID).load("/apps/bookmarks/toggle.asp?" + arrUrl[1]);
    return false;
    });
		
	//Your bookmarks - delete
    $(".MyBookmarks").click(function() {
    var myID = $(this).attr("id")
    var arrUrl = $(this).attr("href").split("?");
    $("#" + myID).parent().parent().parent().load("/apps/bookmarks/delete.asp?" + arrUrl[1]);
    return false;
    });
	
	*/
    //Drawer
    $(".drawerHandle").next().hide();
    $(".drawerHandle span").append(" <img class=\"drawerArrow\" src=\"\/assets\/i\/icons\/trans\/bullet_arrow_down_white.gif\" alt=\"\" />");
    $(".drawerHandle").css("cursor", "pointer");
    $(".drawerHandle").click(function() {
        $(this).next().slideToggle("slow");
    }).toggle(
			function() {
			    $(".drawerArrow").attr("src", "\/assets\/i\/icons\/trans\/bullet_arrow_up_white.gif")
			},
			function() {
			    $(".drawerArrow").attr("src", "\/assets\/i\/icons\/trans\/bullet_arrow_down_white.gif")
			}
		);


    //password strength
    $('#ctl00_ContentPlaceHolder1_UserEdit1_PasswordTextBox').pstrength();
    $('#ctl00_ContentPlaceHolder1_NewPasswordTextBox').pstrength();

    //Date picker

    $(function() {
        $('.date-pick').datePicker({ startDate: '01/01/2004' })
        $('#fmPublishDate').bind(
				'dpClosed',
				function(e, selectedDates) {
				    var d = selectedDates[0];
				    if (d) {
				        d = new Date(d);
				        $('#fmUnpublishDate').dpSetStartDate(d.addDays(0).asString());
				        $('#fmCommentExpireDate').dpSetStartDate(d.addDays(0).asString());
				    }
				}
			);
        $('#fmUnpublishDate').bind(
				'dpClosed',
				function(e, selectedDates) {
				    var d = selectedDates[0];
				    if (d) {
				        d = new Date(d);
				        $('#fmPublishDate').dpSetEndDate(d.addDays(0).asString());
				        $('#fmCommentExpireDate').dpSetEndDate(d.addDays(0).asString());
				    }
				}
			);
        $('#fmCommentExpireDate').bind(
				'dpClosed',
				function(e, selectedDates) {
				    var d = selectedDates[0];
				    if (d) {
				        d = new Date(d);
				        $('#fmPublishDate').dpSetEndDate(d.addDays(0).asString());
				    }
				}
			);

        //Events
        $('#fmEvStartDate').bind(
				'dpClosed',
				function(e, selectedDates) {
				    var d = selectedDates[0];
				    if (d) {
				        d = new Date(d);
				        $('#fmEvEndDate').dpSetStartDate(d.addDays(0).asString());
				    }
				}
			);
        $('#fmEvEndDate').bind(
				'dpClosed',
				function(e, selectedDates) {
				    var d = selectedDates[0];
				    if (d) {
				        d = new Date(d);
				        $('#fmEvStartDate').dpSetEndDate(d.addDays(0).asString());
				    }
				}
			);

    });

    /*ToolTip
    $(".trigger").parent().css("position","relative");
    $(".trigger").hover(function() {
    $(this).next(".popup").animate({opacity: "show", top: "30"}, "slow");
    }, function() {
    $(this).next(".popup").animate({opacity: "hide", top: "40"}, "fast");
    });*/
    $('.bubbleInfo').each(function() {
        // options
        var distance = 10;
        var time = 250;
        var hideDelay = 500;

        var hideDelayTimer = null;

        // tracker
        var beingShown = false;
        var shown = false;

        var trigger = $('.trigger', this);
        var popup = $('.popup', this).css('opacity', 0);

        // set the mouseover and mouseout on both element
        $([trigger.get(0), popup.get(0)]).mouseover(function() {
            // stops the hide event if we move from the trigger to the popup element
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // don't trigger the animation again if we're being shown, or already visible
            if (beingShown || shown) {
                return;
            } else {
                beingShown = true;

                // reset position of popup box
                popup.css({
                    top: -110,
                    left: -33,
                    display: 'block' // brings the popup back in to view
                })

                // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
            top: '-=' + distance + 'px',
            opacity: 1
        }, time, 'swing', function() {
            // once the animation is complete, set the tracker variables
            beingShown = false;
            shown = true;
        });
            }
        }).mouseout(function() {
            // reset the timer if we get fired again - avoids double animations
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // store the timer so that it can be cleared in the mouseover if required
            hideDelayTimer = setTimeout(function() {
                hideDelayTimer = null;
                popup.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function() {
                    // once the animate is complete, set the tracker variables
                    shown = false;
                    // hide the popup entirely after the effect (opacity alone doesn't do the job)
                    popup.css('display', 'none');
                });
            }, hideDelay);
        });
    });



});               //end of on load


function runTagCheck() {
    //un-highlight all spans
    $(".TagList li").removeClass('selected');

    //re-examine the value of the textbox and re-highlight matching spans
    //if there is something in the text-box..
    if ($("#fmTags").attr("value") > "") {

        var arrTerms = $("#fmTags").attr("value").split(",");
        $(".TagList").find("li").each(
			function() {
			    var x = $(this).html();
			    for (i = 0; i < arrTerms.length; i++) {
			        if (jQuery.trim(x) === jQuery.trim(arrTerms[i])) {
			            $(this).addClass("selected");
			        };
			    }
			}
		);

    } else {

        //the text-box is empty, so de-select all the tags
        $("#TagList li").removeClass('selected');

    }
}

function refreshConsole() {
    var ConvID = $("#ConversationID").attr("value");
    if ($('#ConversationID').length) {
        $("#Conversation").load("/apps/forums/thread/index.asp", { id: ConvID });
    }

    var ConvWatchID = $("#ConversationWatchID").attr("value");
    if ($('#ConversationWatchID').length) {
        //$("#ConversationWatch").load("/apps/forums/thread/watch/index.asp",{id: ConvWatchID});
    }

    var ForumWatchID = $("#ForumWatchID").attr("value");
    if ($('#ForumWatchID').length) {
        //$("#ConversationWatch").load("/apps/forums/watch/index.asp",{id: ForumWatchID});
    }

    var SectionForumWatchID = $("#SectionForumWatchID").attr("value");
    if ($('#SectionForumWatchID').length) {
        //$("#ConversationWatch").load("/apps/sections/forums/watch/index.asp",{id: SectionForumWatchID});
    }

    setTimeout("refreshConsole()", 30000);
}


function PortalSearchFlag() {
    $("#DashSearch input[@type='radio']").each(
		function() {
		    if (this.checked === true) {
		        //hide unwanted controls
		        if (this.value == 'People') {
		            $("label[for='s']").parent().removeClass("hide");
		        } else {
		            $("label[for='s']").parent().removeClass("hide");
		            $("label[for='s']").parent().addClass("hide");
		            $(this).find("input").checked = false;
		        };
		        if (this.value == 'Places') {
		            $("label[for='r']").parent().removeClass("hide");
		            $("label[for='r']").parent().addClass("hide");
		            $(this).find("input").checked = false;
		        } else {
		            $("label[for='r']").parent().removeClass("hide");
		        };

		        $(this).parent("label").addClass("Active");
		    } else {
		        $(this).parent("label").removeClass("Active");
		    };
		}
	);

}
