﻿
//AJAX CODE
var moXmlApplication=null;
//This will hold an array of company names
var companyNames = [];
//This will hold the companies' associated GUIDs
var companyIds = [];
//This will hold the name of the company entered in the registration form
var companyName;
//This is the variable for the company textbox in the form so its value can be modified
var moCompanyTextbox;
//This is the variable for the hidden CRM field to hold the selected company's GUID
var moCRMHiddenField;
//This is the variable for the popup div that will display suggested company names if any are found
var companyDiv;
//This is the variable for the div to contain the image notifications
var imageDiv;
//This will hold the text portion of the companyDiv
var companyDivText = document.createElement('div');
//This is a bool to tell wheter the companyDiv has been built already
var mbIsBuilt = false;
//This is to reference the submit button of the form
var submitButton;
//This is to set if the popup came from clicking the submit button or the actual image
var userClickedSubmit = false;

// JScript File
function GetCRMAccounts(companyDivId, hiddenCRMId, btnSaveId)
{
	//debugger;
	submitButton = document.getElementById(btnSaveId)
	
	//lockForm();
	moCompanyTextbox = document.getElementById(companyDivId);
	moCRMHiddenField = document.getElementById(hiddenCRMId);
	companyDiv = document.getElementById("crmCompanies");
	//companyDiv.style.border = "10px solid red";
	companyDiv.style.height="150px";
	companyDiv.style.width="310px";

	companyName = moCompanyTextbox.value;
	imageDiv = document.getElementById("crmAlert");
	var pos = findPos(moCompanyTextbox);
	//companyDivText.left = pos[0] + "px";
	//companyDivText.top = pos[1] + "px";
	
	companyDiv.style.left = pos[0] + moCompanyTextbox.scrollWidth + "px";
	companyDiv.style.top = pos[1] - companyDiv.style.pixelHeight  + moCompanyTextbox.scrollHeight + 1 + "px";
	//companyDivText.style.left = pos[0] + moCompanyTextbox.scrollWidth + "px";
	//companyDivText.style.top = pos[1] - companyDiv.style.pixelHeight  + moCompanyTextbox.scrollHeight + 1 + "px";
	if(companyName != "")
	{
	
	init();
	}
		
} 

function lockForm()
{	
	submitButton.disabled = true;
	var imgButton = document.getElementById("imgCRM");	
	imgButton.click();
}
function lockFormSubmitBtn()
{
	submitButton.disabled = true;
	var imgButton = document.getElementById("imgCRM");	
	imgButton.click();
	userClickedSubmit = true;
}

function unlockForm()
{	
	submitButton.disabled = false;
	//submitButton.onclick = null;
	submitButton.onclick = loadAnimation;
	if(userClickedSubmit == true)
	{
		submitButton.click();
	}
}
function loadAnimation()
{
	createOverlay();
	document.getElementById('loadingDiv').style.visibility = 'visible';
	document.getElementById('loadingDiv').style.zIndex = 9999999;
}
			
function displayErrorMessage(message)
{
	alert(message);
}
			
function init()
{		
	//debugger;
	submitButton.onclick = lockFormSubmitBtn;
	moXmlApplication = ajaxInitObject(moXmlApplication);
	// set the longitude and latitude parameters
			//var sParameters = 'Type=' + lsApplicationType + '&Width=' + window.screen.width + '&Height=' + window.screen.height   ;
			var sParameters = 'accountName=' + companyName;
			//debugger;
	var result = ajaxCallbackWS(moXmlApplication, 'GetRelatedAccounts', sParameters, InitApplicationResponse);
	
}

function InitApplicationResponse(){
	//debugger;
	if(ajaxIsValidObject(moXmlApplication))	
	{
		//debugger;
		
		//if there is an alert image, remove it. this will allow the image to change if the alert is 
		//different and the user has not addressed the previous alert.
		if(document.getElementById("imgCRM") != null)
			removeAlert();

		var companies = moXmlApplication.responseXml.text.split("*");
		var l = companies.length;
		var count = 0;
		
		
		for (i=0; i < l; i+=2)
		{
			companyNames[count] = companies[i];
			companyIds[count] = companies[i+1];
			count++;
		}
		
		
		//Exact Match for Company Name
		if(companyNames[0].toLowerCase() == companyName.toLowerCase())
		{
			//debugger;
			moCRMHiddenField.value = companyIds[0];		
			var img = document.createElement("img");
			img.id = "imgCRM";
			img.src='/images/msgCheck.jpg';
			img.onmouseover=changeCursor;
			img.onclick = exactMatch;
			if(imageDiv.children.length == 1)
				imageDiv.appendChild(img);	
			
			//img.onmouseover = exactMatch();
				
		}
		
		//No Match for Company Name
		else if(companyNames[0] == "" || companyNames[0] == null)
		{
		
			var img = document.createElement("img");
			img.id = "imgCRM";
			img.src='/images/msgYell.jpg';
			img.onmouseover= changeCursor;
			img.onclick = noMatch;
			if(imageDiv.children.length == 1)
				imageDiv.appendChild(img);			
		}

		//One or more matches for Company Name, none exact.
		else
		{
			var img = document.createElement("img");
			img.id = "imgCRM";
			img.src='/images/msgYell.jpg';
			img.onmouseover= changeCursor;
			img.onclick = otherMatch;
			if(imageDiv.children.length == 1)
				imageDiv.appendChild(img);					
			
			
		}
	}
}
function removeNotification()
{

	Effect.Fade('registerValidation');
}
function changeCursor()
{
	this.style.cursor="hand";
}
function exitPopup()
{
	removeOverlay();
	Effect.Shrink('crmCompanies', {direction: 'bottom-left'});

	companyDiv.removeChild(companyDivText);
	unlockForm();
}
function exitPopupNew()
{
	removeOverlay();
	Effect.Shrink('crmCompanies', {direction: 'bottom-left'});	
	companyDiv.removeChild(companyDivText);
	moCRMHiddenField.value = "";

	unlockForm();
}

function removeAlert()
{
	imageDiv.removeChild(document.getElementById("imgCRM"));
}
function exactMatch()
{
	//debugger;
	removeAlert();
	companyDivText.innerHTML = "<table cellpadding='3px' cellspacing='3px'><tr><td><br/>We found your company in our databases and will add you as a contact. <br/></td></tr>"
	companyDivText.innerHTML += "<tr><td><br/><p align='center'><a href='javascript:exitPopup()');'>OK</a></p></td></tr></table>";
	Effect.Grow('crmCompanies', {direction: 'bottom-left'});
	createOverlay();
	buildDiv();
	modalContainer.focus();
	

}
function noMatch()
{
	removeAlert();
	companyDivText.innerHTML = "<table cellpadding=5><tr><td><br/>We did not find your company in our databases. We will now add " + companyName + " to our database. Feel free to enter some of the optional information. <br/></td></tr>";
	companyDivText.innerHTML += "<tr><td><br/><p align='center'><a href='javascript:exitPopup()');'>OK</a></p></td></tr></table>";
	Effect.Grow('crmCompanies', {direction: 'bottom-left'});
	createOverlay();
	buildDiv();
	modalContainer.focus();
	

}

function otherMatch()
{
	//debugger;
	removeAlert();
	companyDivText.innerHTML = "<table width='100%'>";
	companyDivText.innerHTML += "<tr><td width='45%'></td><td width='50%'>We found some companies similar to yours. Are any of these your company?"
	companyDivText.innerHTML += "<ul>";
	for(j=0; j<companyNames.length; j++)
	{
		if(companyNames[j] != "")
			companyDivText.innerHTML += "<li><a href='javascript:selectCompany(\"" + companyIds[j] + "\", \"" + companyNames[j] + "\")'>" + companyNames[j] + "</a></li>";
	}
	companyDivText.innerHTML += "</ul></td><td width='5%'></td></tr>";
	companyDivText.innerHTML += "<tr><td colspan='3'><p align='center'><a href='javascript:exitPopupNew()'>[Add New Company " + moCompanyTextbox.value + "]</a></p></td></tr></table>";
	Effect.Grow('crmCompanies', {direction: 'bottom-left'});
	createOverlay();
	buildDiv(companyNames.length);
	modalContainer.focus();
}
function selectCompany(companyGuid, companyName)
{
	//debugger;	
	moCompanyTextbox.value = companyName.replace(/^\s+/,"");
	moCRMHiddenField.value = companyGuid;
	exitPopup();
	
}
function buildDiv(numberOfCompanies)
{
	//debugger;
	if(mbIsBuilt == false)
	{
	companyDivText.style.color="#000066";
	companyDivText.style.fontSize="11px";
	companyDivText.style.fontFamily="Verdana";
	var moMenuBar = document.createElement('div');
	moMenuBar.style.background = "#000066";
	moMenuBar.style.pixelWidth = companyDiv.style.pixelWidth - 2;
	moMenuBar.style.height = "15px";
	moMenuBar.style.posTop = "10";
	moMenuBar.style.border = "1px solid black";
	var moCloseLink = document.createElement('a');
	moCloseLink.href = "#";
	moCloseLink.onclick = exitPopup;
	moCloseLink.style.color = "white";
	moCloseLink.style.fontWeight = "bold";
	moCloseLink.style.textDecoration = "none";	
	moCloseLink.style.left = 400;
	moCloseLink.style.fontSize="12px";
	var txtClose = document.createTextNode('X');
	
	var moCloseP = document.createElement('p');	
	moCloseP.align = "right";
	moCloseLink.appendChild(txtClose);	
	moCloseP.appendChild(moCloseLink);
	moMenuBar.appendChild(moCloseP);	
	companyDiv.appendChild(moMenuBar);
	companyDiv.style.zIndex = 99999999;			
	companyDivText.style.background = "#FFFFCC";
	companyDiv.style.background = "none";
	companyDiv.style.visibility = "visible";
	//companyDiv.style.border = "1px solid black";
	//companyDiv.style.overflow = "hidden";
	companyDivText.style.border = "1px solid black";
	companyDivText.style.overflow = "visible";
	companyDivText.style.width = companyDiv.style.width;
	//companyDivText.style.verticalAlign = "bottom";
	//companyDivText.style.height = (companyDiv.style.pixelHeight - moMenuBar.style.pixelHeight) + "px";		
	mbIsBuilt = true;
	}
	//debugger;
	if(numberOfCompanies > 0)
	{
	companyDivText.style.pixelHeight = 135 + ((numberOfCompanies) * 10);
	}
	else
	{
		companyDivText.style.pixelHeight = 135;
	}
	//debugger;
	//if(companyDivText.style.pixelHeight < 135)
	//{
	//	companyDivText.style.pixelHeight = 135;
	//}
	companyDiv.style.pixelHeight = companyDivText.style.pixelHeight + 15;
	companyDiv.appendChild(companyDivText);
}
function createOverlay()
{
	
	var d = document;
	//Create the modular object that stops all actions on screen but shows the popup box
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	mObj.style.height = d.documentElement.scrollHeight + "px";
}

function removeOverlay()
{

	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}



//
// Initialize and return the AJAX XML object properly
//
// Parameters:
//   oXmlObj - the ajax xml object to validate and initialize if necessary
//
function ajaxInitObject(oXmlObj)
{
	// if the object hasn't been created yet, attempt to create it
	if (oXmlObj == null)
	{
		try
		{	
			oXmlObj = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{	
				oXmlObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e1)
			{
				oXmlObj = null;
			}
		}
	}
	// otherwise, abort the current call
	else
		oXmlObj.abort();

	// return the AJAX XML object
	return oXmlObj;
}

//
// Perform an ajax call to the server.  
// This function assumes that there is file called AjaxCallsWS.aspx that handles the different functions.
//
// Parameters:
//   oAjaxXml - the ajax xml object that is responsible for doing the callback to the server
//   sServerFunction - the name of the function inside AjaxCalls.aspx that will be called to handle the routine
//   sURLParameters - the parameters to pass back for the function call 
//					  <ParameterName1>=<ParameterValue1>&<ParameterName2>=<ParameterValue2>&...
//   vCallbackFunction - the function that will be called on the page to do the processing of the data returned from the server

function ajaxCallbackWS(oAjaxXml, sServerFunction, sURLParameters, vCallbackFunction)
{
	// check that the object is initialized
	oAjaxXml = ajaxInitObject(oAjaxXml);
	
	// if the object is available
	if (oAjaxXml != null)
	{
		// set the callback function
		oAjaxXml.onreadystatechange = vCallbackFunction;
				
		// open up the request
		oAjaxXml.open("POST", "http://www.wsn.net/CRMRelayService/Service.asmx/" + sServerFunction,true);				
		oAjaxXml.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8;");
		//debugger;		
		if (sURLParameters != '')		
			oAjaxXml.send(sURLParameters);		
		else
			oAjaxXml.send(null); 		
		// return true if successful
		return true;      
		//return oAjaxXml;
	}
	
	// return false if failed
	return false;
}

// validates the ajax xml object
function ajaxIsValidObject(oAjaxXml)
{
	//
	// return true if all the following conditions are met:
	//		- the object hasn't been destroyed
	//		- all of the data has been retrieved (readystate == 4)
	//		- the http status is set to OK (200)
	//
	
	return (oAjaxXml != null && typeof(oAjaxXml) == 'object' && oAjaxXml.readyState == 4 && oAjaxXml.status == 200);
}
function findPos(obj) {
			var curleft = curtop = 0;

			if (obj.offsetParent) 
			{
				do 
				{
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				} 
				while (obj = obj.offsetParent);

				return [curleft,curtop];
			}
		}