function getObj(name)
{
	return getObjFromDoc(document, name);
}

function getObjFromDoc(document, name)
{
	var obj = null;
	
	if(document.getElementById)
	{
		obj = document.getElementById(name);
	}
	else if(document.all)
	{
		obj = document.all[name];
	}
	else if (document.layers)
	{
		obj = document.layers[name];
	}
	
	return obj;
}

function rotateImage(imageName, source, doBackup)
{
	var imageObj = getObj(imageName);
	if(imageObj != null) imageObj.src = source;
	
	if(doBackup)
	{
		var sourceBackupObj = getObj(imageName + "SourceBackup");
		if(sourceBackupObj != null) sourceBackupObj.value = source;
	}
}

function rotateImageBack(imageName)
{
	var sourceBackupObj = getObj(imageName + "SourceBackup");
	if(sourceBackupObj != null)
	{
		var imageObj = getObj(imageName);
		if(imageObj != null) imageObj.src = sourceBackupObj.value;
	}
}

function rotateLink(obj)
{
	var elements = document.getElementsByTagName('a');
	for(i = 0; i < elements.length; i++)
	{
		if(elements[i] != obj && elements[i].className == "ContentLinkRollableOn")
			elements[i].className = "ContentLinkRollableOff";

		if(elements[i] != obj && elements[i].className == "ContentLinkRollableHighlightedOn")
			elements[i].className = "ContentLinkRollableHighlightedOff";
	}

	if(obj.className == "ContentLinkRollableOff")
		obj.className = "ContentLinkRollableOn";
	else if(obj.className == "ContentLinkRollableHighlightedOff")
		obj.className = "ContentLinkRollableHighlightedOn";
}

function highlightLink(id)
{
	var linkObj = getObj(id);
	if(linkObj != null)
	{
		if(linkObj.className == "ContentLinkRollableOff")
			linkObj.className = "ContentLinkRollableHighlightedOff";

		if(linkObj.className == "ContentLinkRollableOn")
			linkObj.className = "ContentLinkRollableHighlightedOn";
	}
}

function highlightLinks(idList)
{
	resetRotateLinkHighlights();
	
	var idArray = idList.split(",");
	for(i = 0; i < idArray.length; i++)
		highlightLink(idArray[i]);

	var firstLinkObj = getObj(idArray[0]);
	if(firstLinkObj != null)
		firstLinkObj.onclick();
}

function resetRotateLinkHighlights()
{
	var elements = document.getElementsByTagName('a');
	for(i = 0; i < elements.length; i++)
	{
		if(elements[i].className == "ContentLinkRollableHighlightedOff")
			elements[i].className = "ContentLinkRollableOff";

		if(elements[i].className == "ContentLinkRollableHighlightedOn")
			elements[i].className = "ContentLinkRollableOn";
	}
}

var hasError = false;

function validate_form(form)
{
	hasError = false;
	
	for(var i = 0; i < form.length; i++)
	{
		if(form[i].onblur != null)
			if((form[i].onblur+"").match("validate"))
				form[i].onblur();
	}

	return !hasError;
}

function validate_required(obj, message)
{
	var valid = false;
	
	if(obj.type == "checkbox" || obj.type == "radio")
	{
		// Currently not supported
		valid = true;
	}
	else if(obj.options)
		valid = (obj.options[obj.selectedIndex].value.length > 0);
	else
		valid = (obj.value.length > 0);

	if(!valid)
	{
		show_error(obj, (message && message != "" ? message : "This field is required."));
		hasError = true;
	}
	else hide_error(obj);
	
	return valid;
}

function validate_format(obj, format, message)
{
	var valid = false;

	if(obj.value == "")
		valid = true;
	else if(format == "email")
		valid = obj.value.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
	else if(format == "url")
		valid = obj.value.match(/(http:\/\/)?\S+\.\S+/);
	else
	{
		// This does not seem work
		var re = new RegExp(format, "i");
		valid = obj.value.match(re);
	}
	
	if(!valid)
	{
		show_error(obj, (message && message != "" ? message : "Enter a valid value."));
		hasError = true;
	}
	else hide_error(obj);
	
	return valid;
}

function show_error(obj, message)
{
	obj.className = "Error";

	var errorDivID = get_ErrorDivID(obj);

	var errorDiv = getObj(errorDivID);
	if(errorDiv)
	{
		errorDiv.style.display = "block";
		errorDiv.innerHTML = message;
	}
	else
	{
		var div = document.createElement("div");
		div.id = errorDivID;
		div.className = "ErrorMessage";
		div.innerHTML = message;
		obj.parentNode.appendChild(div);
	}
}

function hide_error(obj)
{
	obj.className = "";

	var errorDivID = get_ErrorDivID(obj);

	if(getObj(errorDivID))
		getObj(errorDivID).style.display = "none";
}

function get_ErrorDivID(obj)
{
	return obj.id + "_ErrorMessage";
}

function onIDSelection(checkbox)
{
	var enable = getHasIDSelection();
	
	if($('#AddButton').size() > 0)
	{
		if(!enable) $('#AddButton').attr('disabled', true)
		else $('#AddButton').removeAttr('disabled');
	}
	
	if($('#RemoveButton').size() > 0)
	{
		if(!enable) $('#RemoveButton').attr('disabled', true)
		else $('#RemoveButton').removeAttr('disabled');
	}
}

function getHasIDSelection()
{
	return $('.IDCheckBox:checked').size() > 0;
}

function warnIfHasSelection()
{
	if(getHasIDSelection()) return confirm('You will lose your selection. Do you want to continue?');
	return true;
}

function getSelectedIDs()
{
	var ids = [];
	$('.IDCheckBox:checked').each(function() {
		var matches = $(this).attr('id').match(/SelectedIDs_(\d+)/);
		if(matches != null) ids.push(matches[1]);
	});
	return ids.join(',');
}

function prepareModalPopup(content, top, left, width, height)
{
	// Add the div if necessary, clear any style that might be directly on div from previous use of dialog
	var divPopup = $('div.ModalPopup');
	if(divPopup.size() == 0)
	{
		$('body').append('<div class="ModalPopup"></div>');
		divPopup = $('div.ModalPopup');
	}
	else
	{
		divPopup.removeAttr('style');
	}

	// Add Content
	divPopup.html(content);

	// Set Popup Size
	var divWidth = (width != null ? width : divPopup.width());
	var divHeight = (height != null ? height : Math.min(divPopup.height(), Math.ceil($(window).height() * 0.75)));

	divPopup.css({'width': width, 'height': divHeight});
	divPopup.find('div.content').css({'height': divHeight-30-30});

	// Center the Popup
	var divTop = (top != null ? top : Math.ceil(($(window).height() - divHeight) / 2));
	var divLeft = (left != null ? left : Math.ceil(($(window).width() - divWidth) / 2));
	divPopup.css({'top': divTop, 'left': divLeft});

	return divPopup;
}

function showModalMessage(message, top, left)
{
	var divPopup = prepareModalPopup("<div class='message'><img src='../images/icons/v3/blueSpinner-mac.gif' id='spinner'/> " + message + "</div>", top, left);
	divPopup.show();
}

function hideModalMessage()
{
	var divPopup = $('div.ModalPopup');
	if(divPopup.size() > 0) divPopup.hide();
}

function loadModalPopup(url, submitCallback, beforeSubmitCallback, top, left, width, height)
{
	var getUrl = url+'&modal=true';
	$.get(getUrl, function(response) {

		var divPopup = prepareModalPopup(response, top, left, width, height);
		
		// Handle Submit Buttons
		var form = divPopup.find('form');
		var buttons = form.find("input[type='submit']");
		if(buttons.size() > 0) buttons.click(function(e) {

			e.preventDefault();
			divPopup.hide();
			
			var button = $(this);
			if(!button.hasClass('cancel'))
			{
				var postData = form.serialize();
				postData += '&' + button.attr('id') + '=ok';
				
				if(beforeSubmitCallback != null) beforeSubmitCallback(postData);
				
				$.post(getUrl, postData, function(response) {
					if(submitCallback != null) submitCallback(response);
				});
			}
		});
		
		divPopup.show();
	});
}

function showHandpickedListPopup(link, type)
{
	link = $(link);
	loadModalPopup(link.attr('href'), function(response) { setHandpickedIcon(link.find('img'), type, response); hideModalMessage(); }, function(postData) { showModalMessage('Saving...'); });
}

function showHandpickedListPopupForSelection(urlPrefix, type)
{
	loadModalPopup(urlPrefix + getSelectedIDs(), function(response) { window.location = window.location.href; }, function(postData) { showModalMessage('Saving...'); });
}

function addHandpickedList(url, type)
{
	loadModalPopup(url, function(response) { if(response=='added') window.location = window.location.href; }, function(postData) { showModalMessage('Adding...'); });
}

function removeHandpickedList(url, type, name)
{
	var confirmed = window.confirm('Are you sure you want to remove this ' + type + ' from ' + name + '?');
	if(confirmed)
	{
		showModalMessage('Removing...');
		$.get(url, function(response) {
			if( response == 'removed' )
				window.location = window.location.href; 
		});
	}
}

function updateHandpickedListCompany(link, companyName)
{
	link = $(link);

	var confirmed;
	if(link.attr('href').indexOf('RemoveStaticList') == -1)
		confirmed = true;
	else
		confirmed = window.confirm('Are you sure you want to remove ' + companyName + ' from your list? This will remove all contacts from ' + companyName + ' that you have not manually added.');
		
	if(confirmed)
	{
		$.get(link.attr('href'), function(response) {

			// Reload the page since company changes affect multiple contacts which will impact pagination
			if(response == 'added' || response =='removed')
				window.location = window.location.href;

		});
	}
}

function updateHandpickedListContact(link, companyInList)
{
	skipNextHandpickMouseOut = true;

	showModalMessage('Saving...');

	link = $(link);
	$.get(link.attr('href'), function(response) {

		if(response == 'added' || response =='removed')
		{
			// Update the page rather than reloading it
			setHandpickedIcon(link.find('img'), 'Contact', response);

			// Update Count and Swap Add/Remove Links
			var countSpan = $('div.pagination div.count span').eq(0);
			if(response == 'added')
			{
				if(!companyInList && countSpan.size() > 0) countSpan.text(parseInt(countSpan.text()) + 1);
				link.attr('href', link.attr('href').replace('AddStaticList', 'RemoveStaticList'));
			}
			else if(response == 'removed')
			{
				if(!companyInList && countSpan.size() > 0) countSpan.text(parseInt(countSpan.text()) - 1);
				link.attr('href', link.attr('href').replace('RemoveStaticList', 'AddStaticList'));
			}
			
			// NOTE: As we only update contact counts, there leaves open the situation where there is a
			// contact included at a company that is not explicitly included. Removing the contact should
			// decrement the company count also IF there are no other included contacts at that company.
			// As those contacts may be on other pages, the only simple way to handle this would be to
			// do a page refresh. However that woudl eliminate the option of "undoing" the removal
			// which is currently kept on the page until the next refresh. So choosing to keep the
			// BUG for now. NN
		}

		hideModalMessage();
	});
}

var skipNextHandpickMouseOut = false;

function setHandpickedIcon(img, type, response)
{
	// Capitalize first letter of type
	if(type == type.toLowerCase()) type = type[0].toUpperCase() + type.substring(1);

	if(img.size() > 0)
	{
		if(response == 'added')
		{
			if(img.attr('src').indexOf('Empty') != - 1)
				img.attr('src', img.attr('src').replace('Empty', type));
		}
		else if(response == 'removed')
		{
			if(img.attr('src').indexOf(type) != - 1)
				img.attr('src', img.attr('src').replace(type, 'Empty'));
		}
	}
}

function handpickMouseOver(img, type, useHover)
{
	// Capitalize first letter of type
	if(type == type.toLowerCase()) type = type[0].toUpperCase() + type.substring(1);

	img = $(img);
	
	if(img.attr('src').indexOf('Empty') != -1)
		img.attr('src', img.attr('src').replace('Empty', type));
	else if(useHover != null && useHover == true)
		img.attr('src', img.attr('src').replace(type, type+'Hover'));
	else
		img.attr('src', img.attr('src').replace(type, 'Empty'));
		
	skipNextHandpickMouseOut = false;
}

function handpickMouseOut(img, type)
{
	// Capitalize first letter of type
	if(type == type.toLowerCase()) type = type[0].toUpperCase() + type.substring(1);

	img = $(img);

	if(skipNextHandpickMouseOut == true)
		skipNextHandpickMouseOut = false;
	else
	{
		if(img.attr('src').indexOf(type+'Hover') != -1)
			img.attr('src', img.attr('src').replace(type+'Hover', type));
		else if(img.attr('src').indexOf(type) != -1)
			img.attr('src', img.attr('src').replace(type, 'Empty'));
		else
			img.attr('src', img.attr('src').replace('Empty', type));
	}
}
