/// <reference path="../../../vendor/jquery/jquery-1.3.2.custom.js"/>

var functionHash = {
	autocomplete: $.autocomplete
};

getDialogOptions = (function($)
{
	var commonDialogOptions = {
		draggable: true,
		bgiframe: true, // solves IE6 zIndex problem
		modal: true,
		resizable: false,
		autoOpen: false,
		width: 'auto'
	};

	return function(options)
	{
		return $.extend({}, commonDialogOptions, options);
	};
})(jQuery);

function applyBehaviors(domChunk)
{
    /// <summary> apply a set of behaviors to the elements of domChunk</summary>
    /// <param name="domChunk" type="Object"> the collection of DOM elements to apply behaviors to </param>
    ///	<returns type="undefined" />

	// send request popup
	$(".sendRequest", domChunk).each(function()
	{
		var $sendRequestContainer = $(this);
		var $messageHeaderPanel = $(".messageHeadersPanel", $sendRequestContainer);
		var $composeMessagePanel = $(".composeMessagePanel", $sendRequestContainer);
		var $previewMessagePanel = $(".previewMessagePanel", $sendRequestContainer);
		var $messageBox = $(".infoSoughtTextBox", $sendRequestContainer);
		var $infoSoughtSpan = $(".InfoSought", $sendRequestContainer);
		var $sendRequestForm = $("form", $sendRequestContainer);
		var $buttons = $(".button", $sendRequestContainer);

		var $sendRequestDialog = $(".sendrequest-container", $(".sendrequest-hider", this))
			.dialog(getDialogOptions({ width: 550 }));
		$sendRequestContainer.clickableButton({ doClick: function(e, callback)
		{
			$sendRequestDialog.dialog("open");
			// initally, display the edit message div
			$messageHeaderPanel.show();
			$composeMessagePanel.show();
			$messageBox.val("");
			$previewMessagePanel.hide();
			$sendRequestDialog.data('title.dialog', 'Compose Request');
			callback();
		}
		});

		// hide the dialog when the cancel button is clicked
		$(".cancelButton .button", $sendRequestDialog).clickableButton({ doClick: function(e, callback)
		{
			$sendRequestDialog.dialog("close");
			callback();
		}
		});

		// preview button
		$(".previewRequestButton .button", $sendRequestDialog).clickableButton({ doClick: function(e, callback)
		{
			// get the message content
			var message = $messageBox.val();
			// assign the template contents to the view
			$infoSoughtSpan.empty().append(message);
			// hide the edit message 
			$composeMessagePanel.hide();
			// show the preview message
			$previewMessagePanel.show();
			$sendRequestDialog.data('title.dialog', 'Preview Request');
			callback();
		}
		});

		// back button
		$(".backButton .button", $sendRequestDialog).clickableButton({ doClick: function(e, callback)
		{
			// show the edit message 
			$composeMessagePanel.toggle();
			// hide the preview message
			$previewMessagePanel.toggle();
			$sendRequestDialog.data('title.dialog', 'Compose Request');
			callback();
		}
		});

		// send request button
		$(".sendRequestButton .button", $sendRequestDialog).clickableButton({ doClick: function(e, callback)
		{
			$buttons.clickable('disable');
			$sendRequestForm.ajaxSubmit({ dataType: 'json', success: function(data)
			{
				callback();
				emailSent(data);
				return;
			}
			});
			return false;
		}
		});

		function emailSent(data)
		{
			closeOkDialog = function(e, buttonCallback, closeDialogCallback)
			{
				buttonCallback(); 	//callback the ok button
				closeDialogCallback(); //callback to close the dialog
			}

			// enable buttons that were temporarily disabled
			$buttons.clickable('enable');
			// close dialog
			$sendRequestDialog.dialog("close");
			//display result
			okDialogOptions = { autoOpen: true, width: '300', height: 'auto' };
			var okDialogButtonHash = new Array();
			okDialogButtonHash["Ok"] = { buttonClass: 'button-positive', iconClass: 'icon-check', click: closeOkDialog };
			// show ok dialog
			var message = "";

			for (var i = 0; i < data.messages.length; i++)
			{
				message += "<p>" + data.messages[i] + "</p>";
			}
			createNButtonAlert(data.title, message, okDialogOptions, okDialogButtonHash);
		}
	});
	

	//add vcard icon to non-private relationships
	$(".relationshipListRow", domChunk).filter(":not(.behaved)").addClass("behaved").each(function() {
		$("td.relationshipName",this)
			.not(":has(.private-relationship)")
			.not(".behaved")
			.addClass("behaved")
			.addClass("clickable")
			.attr("title", "Click to see relationship details")
			.hover(function() { $(this).addClass("relationshipListRow_over"); }, function() { $(this).removeClass("relationshipListRow_over"); })
			.children(".contactName").append("<span class='icon vcardIcon'></span>")
			.end()  // close the children selector moving back up the stack to the .relationshipNames
			.each(function()
				{
					//relationships that are not private generate popups
					var $div = $(".vcard-hider .vcard-container", this)
						.dialog(getDialogOptions({ width: 300 }));
					$(".vCardDownload .button", $div).clickableButton({ addLoader: false});
					$(this).click(function()
					{
						$div.dialog("open");
					});
				});			
	});
	

	//inner "see more" links show more relationships
	$(".moreRelationshipsLink", domChunk).clickable({
		addLoader: true,
		doClick: function(e, callback)
		{
			try
			{
				var $link = $(this);
				var $linkRow = $link.closest(".moreRelationshipsRow")
				
				$.get($link.attr("href"),
					function(data)
					{
						var rows = $("tr.relationshipListRow, tr.moreRelationshipsRow", data);
						$linkRow.after(rows).parents(".relationshipBox").each(function() { applyBehaviors(this); });
						$linkRow.remove();
						callback();
					}
				);
			}
			catch (err) { callback(); alert(err); }
			return false;
		}
	});
	
	//outer "see more" link pulls in more contacts/colleagues
	$(".moreResultsLink", domChunk).clickable({ addLoader: true, doClick: function(e, callback)
		{
			try
			{
				var $link = $(this);
				var $container = $link.closest(".resultsContainer");
				$.get($link.attr("href"),
					function(data)
					{
						// call the call back to hide the loader icon. This has to be performed before inserting the new data which changes the dom
						callback();
						$link.after($("div.relationshipBox, a.moreResultsLink", data));
						crossUpdate(".resultsCount", data, $container);
						$(".collapseAllLink", $container).hide().siblings(".expandAllLink").show();
						applyBehaviors($container);
						$link.remove();
					}
				);
			}
			catch (err) { callback(); alert(err); }
			return false;
		}
	});

	//metadata paging
	$(".metadata-paging-anchor", domChunk).clickable({ addLoader: true, doClick: function(e, callback)
		{
			try
			{
				var $link = $(this);
				var $container = $link.closest(".metaData");
				$.get($link.attr("href"),
					function(data)
					{
						$container.empty();
						$container.append(data);
						applyBehaviors($container);
						callback();
					}
				);
			}
			catch (err) { callback(); alert(err); }
			return false;
		}
	});

	// ICONS WHICH APPEAR IN THE META DATA SECTION SHOULD APPEAR HERE TO BE VALID WHEN INTERACTING WITH THE PAGING COMPONENT
	// add the linkedIn icon to all spans of this class
	$("span.linkedIn", domChunk).each(function () {
		new LinkedIn.CompanyInsiderPopup(this.id, $(this).attr('organizationname'));
	})

	// setup officers and directors link
	// We only need to apply this behavior to relevant elements which don't have it. Reapplying it to elements which do have it results in some weird symptoms (e.g., #5914)
	$("#search-box .officers-and-directors").not(".clickable").addClass("clickable").each(function ()
	{
		var openLinkInNewWindow = getOpenLinkInNewWindowHandler(this);
		$(this).clickable({ addLoader: true, doClick: openLinkInNewWindow });
	});

	$(".externalSourceEntryPoint", domChunk).clickable({addLoader: true, doClick: showExternalSearchWindow});

	//clicking on a contact/colleague shows relationships
	$(".relationshipLink", domChunk)
		.attr("title", "Click to show relationships")
		.disableSelection()
		.clickable(
			{
				addLoader: true,
				loaderAddCallback: function(clicked, loader)
				{
					$(".nameCell", clicked).append(loader);
				},
				hoverClass: "relationshipLink_over",
				doClick: function(e, callback)
				{
					var $link = $(this);
					var $pane = $link.siblings("div.relationshipPane");
					ExpandUnexpandRelationships($pane, $link, callback);
				}
			}
		);	

	//clicking on a reminder list in the Lonely Contacts page shows relationships of this contact
	$(".reminder-link .minMaxCell ", domChunk)
		.attr("title", "Click to show relationships to this contact")
		.disableSelection()
		.clickable(
			{
				addLoader: true,
				loaderAddCallback: function(clicked, loader)
				{
					$(".nameCell", clicked.closest(".reminder-link")).append(loader);
				},
				doClick: function(e, callback)
				{
					var $link = $(this).closest(".reminder-link");
					var $pane = $link.next().find(".relationshipPane");
					ExpandUnexpandRelationships($pane, $link, callback); 
				}
			}
		);	
		
	//Setup widget accordion buttons
	setupWidgetExpandCollapseButtons(domChunk);
	setupWidgetAccordions(domChunk);

	return domChunk;
}

function select_RemoveByValue(select, valueToRemove)
{
	for (var i = 0; i< select.length; i++)
	{
		if (select.options[i].value == valueToRemove)
		{
			select.remove(i);
			break;
		}
	}
}

// pane: relationship details container
// link: contains url to target controller to get relationship details
function ExpandUnexpandRelationships($pane, $link, callback)
{
	if (!$pane.is(":visible"))
	{
		if ($pane.find(".relationshipArea").size() == 0 )
		{
		      $.get($link.attr("url"),
	                function(data)
	          {
	                $pane.append(data);
		            showRelationships($link, $pane, callback);
		            $pane.each(function() { 
		                applyBehaviors(this); 
		            });
		            $link.clickable("removeLoader"); 
		      });
        }		  
		else
		{
			showRelationships($link, $pane, callback);
		}
	}
	else
	{
		hideRelationships($link, $pane, callback);
	}
}


