﻿/// <reference path="jquery-1.3.2-min-vsdoc.js" />

var mouse = new Mouse();
var dragTimer;


//Capture mouse information
function Mouse(x, y)
{
	this.x = x;
	this.y = y;
}
function captureMouse(e)
{
	mouse.x = e.clientX;
	mouse.y = e.clientY;
}

function Editor_Notes_OnClientCommandExecuted(editor, args)
{
    pageTracker._trackEvent('Notes Button', args.get_commandName());
}
function Editor_Notes_OnClientLoad(editor, args)
{
    var notesText = getCookie("notesText");
    if (notesText != null)
    {
        editor.set_html(getCookie("notesText"));
    }
    editor.attachEventHandler("onkeyup", function(e)
    {
	    setCookie("notesText", editor.get_text(), 3); //Store cookie with notes each time user updates notes and make cookie valid for 3 hours
    });
}

$(document).ready(initDashboard); //Initialize the panels
function initDashboard() {
    $("#submitConnectionCard").live("mouseup", submitConnectionCard);
    
	jQuery.each(jQuery.browser, function(i, val) {
			if($.browser.msie && parseInt(jQuery.browser.version.substr(0,1))<8) //If dealing with IE 7 or lower, handle bug.
			{
				$(".clear").css("display", "none");
			}
		}
		);
	
    Telerik.Web.UI.Editor.CommandList["Email"] = function(commandName, editor, args)
    {
        window.location = "mailto:?subject=" + escape("Message Notes") + "&body=" + escape(editor.get_text());
    };
    
    $("#editorNotesSpellCheck").click(function(e){
        var editor = $find("Editor_Notes"); //get a reference to RadEditor's client object
        editor.fire("AjaxSpellCheck");
     });
    $("#editorNotesEmail").click(function(e){
        var editor = $find("Editor_Notes"); //get a reference to RadEditor's client object
        editor.fire("Email");
     });
    $("#editorNotesPrint").click(function(e){
        var editor = $find("Editor_Notes"); //get a reference to RadEditor's client object
        editor.fire("Print");
     });
	
	$(document).bind("mousemove", captureMouse); //Attach a handler to capture mouse info
	$(".splitterBarV").bind("mousedown", splitterBarVDragStartHandler);
	
	$(window).resize(dashboardWidthResizeHandler);
	$(window).resize(layoutSplitterBarVs);
	dashboardWidthResizeHandler();
	dashboardUpdateHeight();
	
	$(".dashboard .showhide").click(dashboardShowHideClickHandler);
	
	setInterval ('dashboardUpdateClock()', 1000); //Set interval to update clock every 1 second.
	dashboardUpdateClock();
	
	$(".dashboard .bar").corner("top 5px");
	
	$(".dashboard .tab").live("click", tabClickHandler);
	$(".dashboard .tab .close").live("click", closeTabHandler);
	
    //DISABLE RESIZE of dashboard
	//$(".dashboard .grabber").bind("mousedown", dashboardGrabberDragStartHandler);
    $(".dashboard .grabber").hide();
	
	$(".dashboard .nav span.navActive").corner("left 6px");
	
	$(".dashboard .nav span.navItem").mouseover(function(e)
											{
												$(this).addClass("navHover");
											}
											);
	$(".dashboard .nav span.navItem").mouseout(function(e)
											{
												$(this).removeClass("navHover");
											}
											);
											$(".dashboard .nav span.navItem").click(function (e) {
											    e.preventDefault();
											    $(this).siblings().removeClass("navActive");
											    $(this).siblings().uncorner();
											    $(this).addClass("navActive");
											    $(this).corner("left 6px");

											    var contentToDisplay = $(".dashboard .content " + $(this).attr("href"));
											    contentToDisplay.siblings().css("position", "static"); //Fix bugs in some browsers with fade code

											    contentToDisplay.siblings().hide();

											    contentToDisplay.show(1, function () {
											        dashboardUpdateHeight();
											        dashboardWidthResizeHandler();
											        layoutSplitterBarVs();

											        pageTracker._trackEvent('Dashboard Navigation', $(this).attr("id"));

											        if ($(this).attr("id") == "chat") {
											            showChat();
											        }
											        else {
											            chat.visible = false;
											        }

											    });

											    contentToDisplay.css("position", "relative"); //Fix bugs in some browsers with fade code
											});
	$("#donateLink").click(function(e)
									{
										dashboardShow();
										$(".dashboard .nav #donateTab").click();
									}
									);
	
	//Set up all button divs to react like a button would.
	$(".button").corner("5px");
	
	$(".button").live("mousedown", function(e){$(this).addClass("buttonDown");});
	$(document).mouseup(function(e){$(".button").removeClass("buttonDown");});
	
	layoutSplitterBarVs(); //Layout the vertical splitters
}


function layoutSplitterBarVs()
{
	//Set up the vertical splitter bars and set the widths of the elements to which they apply
	var splitBarsV = $(".splitterBarV");
	splitBarsV.each(initSplitterBarVLayout);	
}
function initSplitterBarVLayout(i)
{
	var sb = $(this);
	var visible = sb.css("display") == "none" ? false : true;
	var autoStretch = sb.attr("autoStretch");
	var stretchElem, stretchToElem;
	
	switch(autoStretch)
	{
		case "left":
		{
			stretchElem = sb.prev(":visible");
			stretchToElem = sb.nextAll(":visible");
			break;
		}
		case "right":
		{
			stretchElem = sb.next(":visible");
			stretchToElem = sb.prevAll(":visible");
			break;
		}
	}
	if (!sb.parent().sbEvents)
	{
		sb.parent().bind("resize", initSplitterBarVLayoutParentResizeHandler);
	}
	var stretchElemOrigWidth = stretchElem.width();
	
	var stretchToWOuterWidth = 0;
	stretchToElem.each(function(i) {
									stretchToWOuterWidth += $(this).outerWidth(true);
								});
	
	var targetWidth = sb.parent().width() - stretchToWOuterWidth;
	if (visible)
	{
		targetWidth -= sb.outerWidth(true)
	}
	if (targetWidth > sb.parent().width()) //ensure it winds up no wider than the parent.
	{
		targetWidth = sb.parent().width()
	}
	stretchElem.width(targetWidth);
	
	if (stretchElemOrigWidth != stretchElem.width())
	{
		stretchElem.trigger("resize");
	}
}
function initSplitterBarVLayoutParentResizeHandler()
{
	$(this).children(".splitterBarV").each(initSplitterBarVLayout);
}

var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
function dashboardUpdateClock()
{
	var d = new Date();
	var day = days[d.getDay()].substr(0, 3);

	var time = day + " " + d.format("h:mm:ss tt");
	
	$(".dashboard .bar .clock").text(time);
}
function cancelBubble(e) {
    e.cancelBubble = true;
    e.returnValue = false;
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
function preventSelect(e) //Disables built-in events.  Prevents text selecting, etc.
{
    cancelBubble(e);
	
	$("*").css("MozUserSelect", "none"); //Prevent selecting text in mozilla
}
function dashboardGrabberDragStartHandler(e) //Start handler for dragging the dashboard sizer
{
	var self = this;
	if ($(this).siblings(".title").children(".showhide").text() == "[hide]")
	{
		dragTimer = setInterval(function(){dashboardGrabberDragging($(self))}, 10);
		$(document).bind("mouseup", dragStopHandler);
		$("body").css("cursor", "n-resize"); //Set cursor to indicate we're resizing in the up-down direction	
		$(document).bind("mousemove", preventSelect); //Prevent selecting text during the drag.
		preventSelect(e); //Initial call to stop select on first firing
	}
}
function dashboardGrabberDragging(grabber) //Handle dragging the dashboard grabber
{
	var parent = grabber.parent().parent().parent();
	
	var minHeight = parent.attr("minHeight");
	var targetHeight = $(window).height() - mouse.y + grabber.height()/2;
	
	if (targetHeight > minHeight)
	{
		parent.height(targetHeight);
	}
	else
	{
		parent.height(minHeight);
	}
	dashboardUpdateHeight();
}
function dragStopHandler(e) //Handles stopping any drag operation
{
	clearInterval(dragTimer); //Clear the timer
	$("body").css("cursor", "auto"); //Reset the mouse cursor to the default
	$(document).unbind("mousemove", preventSelect); //Allow selecting text in all other browsers.
	$("*").css("MozUserSelect", ""); //Allow selecting text in Mozilla.
}


function splitterBarVDragStartHandler(e) //Start handler for dragging a vertical splitter bar
{
	var self = this;
	var next = $(this).next(":first");
	
	dragTimer = setInterval(function(){slitterBarVDragging($(self))}, 100);
	$(document).bind("mouseup", dragStopHandler);
	$("body").css("cursor", "e-resize"); //Set cursor to indicate we're resizing in the left-right direction
	$(document).bind("mousemove", preventSelect); //Prevent selecting text during the drag.
	preventSelect(e); //Initial call to stop select on first firing
}
function slitterBarVDragging(sb) //Handle dragging a vertical splitter bar
{
	var minWidthLeft = sb.attr("minWidthLeft");
	var minWidthRight = sb.attr("minWidthRight");
	var prev = sb.prev();
	var next = sb.next();
	
	var totalWidth = prev.outerWidth(true) + sb.outerWidth(true) + next.outerWidth(true);
	var nextTargetRight = next.offset().left + next.width();
	var prevTargetWidth = mouse.x - prev.offset().left + sb.width();
	var nextTargetWidth = totalWidth - prevTargetWidth;
	
	if (minWidthLeft != null)
	{
		if (prevTargetWidth < minWidthLeft)
		{
			prevTargetWidth = minWidthLeft;
			nextTargetWidth = totalWidth - sb.outerWidth(true) - minWidthLeft;
		}
	}
	if (minWidthRight != null)
	{
		if (nextTargetWidth < minWidthRight)
		{
			nextTargetWidth = minWidthRight;
			prevTargetWidth = totalWidth - sb.outerWidth(true) - minWidthRight;
		}
	}
	
	prev.width(prevTargetWidth);
	next.width(nextTargetWidth);
	prev.trigger("resize");
	next.trigger("resize");
}
function dashboardWidthResizeHandler(e)
{
	var inner = $(".dashboard .inner");
	var grabber = $(".dashboard .grabber");
	var nav = $(".dashboard .nav");
	var content = $(".dashboard .content");
	
	var contentTargetWidth = inner.width() - nav.outerWidth(true);
	content.width(contentTargetWidth);
	
	grabber.css("margin-left", grabber.parent().width()/2 - grabber.prev().width());
}
function dashboardUpdateHeight()
{
	var dashboard = $(".dashboard:first");
	var bar = $(".dashboard .bar:first");
	var nav = $(".dashboard .nav:first");
	var content = $(".dashboard .content:first");
	var contentInner = $(".dashboard .content .inner:first");
	
	var targetHeight = dashboard.height() - bar.height();
	nav.height(targetHeight);
	content.height(targetHeight);
	
	var innerAdjustment = contentInner.outerHeight(true) - contentInner.height();

	//Handle chat height resize
	var chatSettings = $(".chat .settingsWrapper:first");
	var chatTabs = $(".chat .tabs:first");
	var chatContent = $(".chat .conversation:first");
	var chatMessage = $(".chat .message:first");
	var chatUsersCount = $(".chat .usersWrapper .count:first");
	var chatUsers = $(".chat .usersWrapper .users:first");
	var chatSBVs = $(".chat .splitterBarV:first");
	
	var chatContentAdjustment = chatContent.outerHeight(true) - chatContent.height();
	var chatUsersAdjustment = chatUsers.outerHeight(true) - chatUsers.height();

	chatContent.height(content.height() - chatSettings.outerHeight(true) - chatTabs.outerHeight(true) - chatMessage.outerHeight(true) - innerAdjustment - chatContentAdjustment);
	chatUsers.height(content.height() - chatSettings.outerHeight(true) - chatUsersCount.outerHeight(true) - innerAdjustment - chatUsersAdjustment);
	chatSBVs.height(content.height()-innerAdjustment);
	
	//Resize editors
	$(".RadEditor").each(function()
	{
	    $(this).find("iframe").height(targetHeight - $(this).find(".reToolCell").outerHeight(true) - $("#editorNotesTools").outerHeight(true) - innerAdjustment);
	}
	);
}
function dashboardShow()
{
	var showHideButton = $(".dashboard .showhide:first");
	var inner = showHideButton.parent().parent().parent();
	
	if (showHideButton.text() == "[show]")
	{
		inner.animate({marginTop: "0"}, 1500);
		showHideButton.text("[hide]");
	}
}
function dashboardShowHideClickHandler(e)
{
	var showHideButton = $(this);
	var inner = showHideButton.parent().parent().parent();
	
	var dashboard = inner.parent();
	var bar = showHideButton.parent();
	
	if (showHideButton.text() == "[hide]")
	{
	    chat.visible = false;
		inner.animate({marginTop: dashboard.height()-bar.height()}, 1500);
		showHideButton.text("[show]");
	}
	else
	{
	    chat.visible = true;
		inner.animate({marginTop: "0"}, 1500);
		showHideButton.text("[hide]");
	}
}
function tabClickHandler(e) //Handle clicking on a tab
{
	$(this).siblings().removeClass("tabActive");
	$(this).addClass("tabActive");
}
function closeTabHandler(e) {
    var tab = $(this).parent();
	if (tab.next(".tab").length > 0)
	{
	    tab.next(".tab").click();
	}
	else if (tab.prev(".tab").length > 0)
	{
	    tab.prev(".tab").click();
	}
	tab.attr("ignoreClick", true); //Handle bug where click handler for removed tab gets fired
	tab.remove();
	dashboardUpdateHeight();
}

//Notes
function sendNotesSuccess(result) {
    if (result == true) {
        alert("Sent!");
    }
}
function sendNotesFailure(result) {
}

//Connection Card
function submitConnectionCard() {
    pageTracker._trackEvent('Connection Card', 'Submit Clicked');
    $("#connect #connectError").html("");
    var errorsCount = 0;
    var errorStr = "";
    if ($("#connect #fullname").val().replace(/\s+/g, "") == "")
    {
        if (errorsCount > 0)
        {
            errorStr += ", ";
        }
        errorStr += "Full Name";
        errorsCount++;
    }
    if ($("#connect #email").val().replace(/\s+/g, "") == "")
    {
        if (errorsCount > 0)
        {
            errorStr += ", ";
        }
        errorStr += "E-mail";
        errorsCount++;
    }
    if ($("#connect #location").val() == "")
    {
        if (errorsCount > 0)
        {
            errorStr += ", ";
        }
        errorStr += "Location";
        errorsCount++;
    }
    
    var lastComma = errorStr.lastIndexOf(",");
    if (lastComma > 0)
    {
        errorStr = errorStr.substring(0, lastComma) + " and" + errorStr.substring(lastComma+1);
    }
    
    if (errorsCount == 1)
    {
        $("#connect #connectError").html("<div>" + errorStr + " is required.</div>");
        pageTracker._trackEvent('Connection Card', 'Validation Error', errorStr + ' is required.');
    }
    else if (errorsCount > 1)
    {
        $("#connect #connectError").html("<div>" + errorStr + " are required.</div>");
        pageTracker._trackEvent('Connection Card', 'Validation Error', errorStr + ' are required.');
    }
    else
    {
        pageTracker._trackEvent('Connection Card', 'Sending');
        iCampus.SubmitConnectionCard(
            $("#connect #fullname").val(),
            $("#connect #email").val(),
            $("#connect #location").val(),
            $("#connect #gender").val() == "" ? null : parseInt($("#connect #gender").val()),
            $("#connect #age").val() == "" ? null : parseInt($("#connect #age").val()),
            $("#connect #visitortype").val(),
            $("#connect #contactabout").val(),
            $("#connect #commentsprayerrequests").val(),
            submitConnectionCardSuccess, submitConnectionCardFailure
            );
    }
}
function submitConnectionCardSuccess(result) {
    if (result == true) {
        pageTracker._trackEvent('Connection Card', 'Sent');
        alert("Your connection card was sent. Thank you!");
        $("#connect #fullname").val("");
        $("#connect #email").val("");
        $("#connect #location").val("");
        $("#connect #gender").val("");
        $("#connect #age").val("");
        $("#connect #visitortype").val("");
        $("#connect #contactabout").val("");
        $("#connect #commentsprayerrequests").val("");
    }
    else{
        pageTracker._trackEvent('Connection Card', 'Error');
        alert("Problem submitting connection card!");
    }
}
function submitConnectionCardFailure(result) {
    pageTracker._trackEvent('Connection Card', 'Error', result.get_message());
}
