// Rapattoni Corporation Customer Splash Screen Logon JS
// NOTE: This JS is used for PRODUCTION SITES. Please do not modify the URL's.
 
// Logon URL
var strLogonUrl = "http://login.rapmlsstg.com/";
var strMediaUrl = "http://media.rapmlsstg.com/";
var strLogonPage = "login.aspx";
var strForgotPasswordPage = "ForgotPassword.aspx";
var strMagicDLL = "/scripts/mgrqispi.dll";

// encrypt keys
var signKey = null;
var cipherKey = '12345678';

// login field variables used for password save
var agentIDField = "txtAgentId";
var passwordField = "txtPassword";

// global bool for save	password
var savePassword;


//Cross Browser AttachEvent
//Call like this AttachEvent(window, 'load', AddPageButtons)
//Note the omitted 'on' from the evt string parameter
function mlsAttachEvent(obj, evt, func, useCap) {
    if (!useCap) {
        useCap = false;
    }
    if (obj.addEventListener) {
        obj.addEventListener(evt, func, useCap)
        return true;
    }
    else if (obj.attachEvent) {
        return obj.attachEvent("on" + evt, func);
    }
}


// Opens new empty window.
function openEmptyWindow(url)
{
	var popUpContent = url;
	var popUpContentHTML = '';
	
	if (url == null)
	{
		// Set the content to be written in popup.
		popUpContentHTML = "javascript:document.write(&quot;<html><head><title>Loading</title></head><body><table width='100%' height='100%'><tr><td valign='middle' align='center'><img src='" + strMediaUrl + "rapmlsimages/search/loading.gif'></td></tr></table></body></html>&quot;)"
		popUpContent = strMediaUrl + "html/LoadingSplash.htm";
	}
	 
	// Get mls name
	var MLS = document.InputForm.hidMLS.value;
	
	// Generate new window name dynamically
	var winName = "new_window_"  + MLS + new Date().getHours() + new Date().getMinutes() +new Date().getSeconds();
	
	// Set new window properties.
	var properties = "status=0,toolbar=no,location=no,menubar=no,width=850,height=600,resizable=yes";
	
	// open new window.
	var newWindow = window.open(popUpContent,winName,properties);
	
	// Check for pop-up blocker.
	if (newWindow == null || newWindow.closed)
	{
		winName = 'undefined';
	}
	
	// returns window name.
	return winName;
}

// Closes the opener window and leaves the logon page opened.
function closeWindow()
{
	self.opener = this;
	self.close();
}

// Gets the MLS Name.
function getMLS()
{
	return document.InputForm.hidMLS.value;
}

// Gets the Entry point for logon.
function getEntryPoint()
{
	return document.InputForm.hidEntryPoint.value;
}

// return encrypted value.
function doSecure(strValue) 
{
	var encryptValue = '';

	try
	{
		var sc = new SecureContext(strValue, signKey, false);
		sc.secure(cipherKey);
		encryptValue = sc.strText;
	}
	catch(excp)
	{
		//do nothing
	}
	return encryptValue;
}

// Return decrypted value.
function doUnsecure()
{
	var decryptValue = '';
	var password = get_cookie('pass') + " ";
	var passwordLength =  get_cookie('passlength');

	try
	{
		var sc = new SecureContext(password, signKey, false);
		if (!sc.unsecure(cipherKey)); 
		decryptValue = (sc.strText.substring(4)).substring(0,passwordLength);
	}
	catch(excp)
	{
		//do nothing
	}
	return decryptValue;
}

// Logon button click handler. (Use this if user enters login info)
function logOn(bCloseWindow, targetSelf)
{
	var chkSaveCookie = document.getElementById("cboxSaveLogin");
	
	if (targetSelf == null)
	{
		targetSelf = false;
	}
	
	//Sets cookie for login on checkbox state
	if(chkSaveCookie != null)
	{
		createCookie('save', document.InputForm.cboxSaveLogin.checked, 999);
	}
	if(chkSaveCookie != null && chkSaveCookie.checked)
	{
		createCookie('id', document.InputForm.txtAgentId.value, 999);
		createCookie('pass', doSecure("pass" + document.InputForm.txtPassword.value), 999);
		createCookie('passlength',document.InputForm.txtPassword.value.length,999);
	}

	// Set up form attributes.
	document.InputForm.action = strLogonUrl + strLogonPage;
	
	if(targetSelf == true)
	{
	document.InputForm.target = "_self";
	//alert(document.InputForm.target)
	}
	else
	{
	document.InputForm.target = "_top";
	}
	
	// Submit form.
	document.InputForm.submit();
	
	// clear user AgentID and Password field
	if(document.InputForm.cboxSaveLogin)
	{
		if(document.InputForm.cboxSaveLogin.checked == false)
		{
			document.InputForm.txtAgentId.value = '';
			document.InputForm.txtPassword.value = '';
		}
		else
		{
			if(savePassword == false)
			{
			document.InputForm.txtPassword.value = '';
			}
		}
	}
	else
	{
		document.InputForm.txtAgentId.value = '';
		document.InputForm.txtPassword.value = '';
	}
	
	return false;
}

//Logon link click handler. (use this to navigate to standard logon page.)
function logOnPage(bCloseWindow)
{
	// Get logon password url.
	var logonPageUrl = strLogonUrl + strLogonPage + "?hidMLS=" + getMLS() + "&hidEntryPoint=" + getEntryPoint() + "&hidSplash=N";
	
	// open window with logon url.
	//var newWindow = openEmptyWindow(logonPageUrl);
	document.location = logonPageUrl;
	
}

//Forgot Password click handler.
function forgotPassword(bCloseWindow)
{
	// Get forgot password url.
	var forgotPasswordUrl = strLogonUrl + strForgotPasswordPage + "?hidMLS=" + getMLS() + "&hidEntryPoint=" + getEntryPoint() + "&hidSplash=N";
	
	// open window with forgot password url.
	var newWindow = openEmptyWindow(forgotPasswordUrl);
	
	// check for popup blocker.
	if (newWindow == 'undefined')
	{
		RedirectPopupBlocker();
		return;
	}
}

// Public search link handler.
function publicSearch(mgArguments, bEncrypted)
{
	// if args are encrypted use ARGUMENTS else ARGUMENT
	var argsName = "ARGUMENT";
	
	if (bEncrypted == null || !bEncrypted)
	{
		bEncrypted = false;
		argsName = "ARGUMENTS";
	}// if (bEncrypted == null)
	
	// Get app name.
	var strAppName = document.InputForm.hidAppName.value;
	
	// Generate search url
	var strSearchURL = strMagicDLL + "?APPNAME=" + strAppName + "&PRGNAME=MLSLogin&" + argsName + "=" + mgArguments;
	
	// Navigate to search
	document.location.href = strSearchURL;
}

// Public search link handler for SSO.
function publicSearchSSOSplash(mgArguments, bEncrypted)
{
	// if args are encrypted use ARGUMENTS else ARGUMENT
	var argsName = "ARGUMENT";
	
	if (bEncrypted == null || !bEncrypted)
	{
		bEncrypted = false;
		argsName = "ARGUMENTS";
	}// if (bEncrypted == null)
	
	// Get app name.
	var strAppName = document.InputForm.hidAppName.value;
	
	// Generate search url
	var strSearchURL = strMagicDLL + "?APPNAME=" + strAppName + "&PRGNAME=MLSLogin&" + argsName + "=" + mgArguments;
	
	// Navigate to search
	document.location.href = strSearchURL;
}

// Sets focus on user name field.
function focusUserName()
{
	document.getElementById('txtAgentId').focus();
}

// Opens up logon help.
function logonHelp()
{
	var strLogonHelpUrl = strMediaUrl + "help/logonhelp/";
	
	// open window with logon url.
	var newWindow = openEmptyWindow(strLogonHelpUrl);
}

// Redirect user to pop-up blocker help.
function RedirectPopupBlocker()
{
	document.location.href = strMediaUrl + "popupredirect/Redirect.htm";
}

//Initializes login fields based on cookie
function initFields(pw,sso)
{
	savePassword = pw;
	
	if(pw == null){ pw = true; }
	if(sso == null){ sso = false; }
	
	if(sso == true)
	{
		agentIDField = "SSOLogin1$Login1$UserName";
		passwordField = "SSOLogin1$Login1$Password";
	}

	if(get_cookie('save') == 'true')
	{
		document.InputForm.cboxSaveLogin.checked = true;
	}
	else if(get_cookie('save') == 'false')
	{
		document.InputForm.cboxSaveLogin.checked = false;
	}

	if(document.InputForm.cboxSaveLogin.checked)
	{
		document.InputForm.elements[agentIDField].value = get_cookie('id');
		
		if(pw == true)
		{
			document.InputForm.elements[passwordField].value = doUnsecure();
		}
	}
}

//Clears login field if save info checkbox is unchecked
function updateFields()
{
	if(!document.InputForm.cboxSaveLogin.checked)
	{
		document.InputForm.elements[agentIDField].value = '';
		document.InputForm.elements[passwordField].value = '';
	}
}

//Creates cookie
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+";";
}

//Retrieves cookie values
function get_cookie(Name) 
{
	var search = Name + "="
	var returnvalue = ""
	
	if (document.cookie.length > 0) 
	{
		offset = document.cookie.indexOf(search)
		if (offset != -1) 
		{
			offset += search.length
			end = document.cookie.indexOf(";", offset)
			
			if (end == -1)	
				end = document.cookie.length;
			
			returnvalue=unescape(document.cookie.substring(offset, end))
		}
	}
	return returnvalue;
}

//Finds and returns x position of login fields
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

//Positions the announcement div to the right or left of login fields
function dropDiv()
{
	var fieldLeft = document.getElementsByName('txtAgentId');

	if(fieldLeft.length > 0)
	{
		var leftPos = findPosX(fieldLeft[0]);
		
		if(leftPos > 450)
		{
			addDiv('left');
		}
		else if(leftPos < 450)
		{
			addDiv('right');
		}
	}
	else
	{
		addDiv('left');
	}
}

function checkAnnouncementExp()
{
	if(document.getElementById('hidAnnounExp'))
	{
		// get current date
		var today = new Date();

		// get announcement expire date.
		var targetDate = new Date(document.getElementById('hidAnnounExp').value);

		// evaluate difference in days
		var timeDiff = Math.floor(( targetDate.getTime() - today.getTime() ) / 86400000)
		
		// check if within 2wks show announcement.
		if(timeDiff < 14 && timeDiff > 0)
		{
			dropDiv();
		}
	}
}

	var speedDown=50;
	var speedOut=30000;
	var iLeft = -330;
//Drops the announcment div
function dropDiv2(side)
{
	if(side == 'left')
	{
		document.getElementById("container").style.left = iLeft;
	}
	else if(side == 'right')
	{
		document.getElementById("container").style.right = iLeft;
	}

	if(iLeft<50)
	{
		iLeft+=10;dropper=setTimeout("dropDiv2('" + side + "')",speedDown);
	}
	else 
	{
		clearTimeout(dropper);setInterval('removeDiv()',speedOut);
	}
}
//Sets content of announcement div
function addDiv(side)
{
	var strContainer =  '<table border="0" width="270" cellspacing="0" cellpadding="0">'
	+'  <tr>'
	+'    <td width="10"><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_corn_ul2.gif" width="10" height="30"></td>'
	+'    <td width="208" background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_top_bg.gif">&nbsp;</td>'
	+'    <td width="12" background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_top_bg.gif"></td>'
	+'    <td width="9" background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_top_bg.gif"></td>'
	+'    <td width="10"><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_corn_ur.gif" width="10" height="30"></td>'
	+'  </tr>'
	+'  <tr valign="top">'
	+'    <td class="sBlackText" background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_side_l.gif" width="10"></td>'
	+'    <!-- height="120"--><td class="sBlackText" colspan="3"  bgcolor="#FFFFFF"><p>'
	+'     <!--<!$MG_MLS_Annoucement_Title></B><DIV></DIV>'
	+' <div align="center"><img src="newinthemls.jpg"></div-->'
	+'      <table id="RIA_Content" width="326" height="320" border="0" cellpadding="0" cellspacing="0">'
	+'          <tr>'
	+'            <td align="right"><a href="#" onclick="removeDiv()" style="color:blue; font-family:arial"><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/close.gif" border="0"></a></td>'
	+'          </tr>'
	+'          <tr>'
	+'            <td><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/v10_10_01.gif" width="326" height="85"></td>'
	+'          </tr>'
	+'          <tr>'
	+'            <td><a href="http://www.rapattoni.com/multimedia/mls/v10/" target="_blank"><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/v10_20_02.gif" width="326" height="68" alt="" border="0"></a></td>'
	+'          </tr>'
	+'          <tr>'
	+'            <td><a href="http://tutorial.rapmls.com/showme10/resolution.htm" target="_blank"  ><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/v10_20_03.gif" width="326" height="83" border="0"></a></td>'
	+'          </tr>'
	+'          <tr>'
	+'            <td><a href="http://media.rapmls.com/tools/MlsToTrusted/rapmls/BrowserOptimizationTool.exe"><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/v10_20_04.gif" width="326" height="84"border="0"></a></td>'
	+'          </tr>'
	+'      </table></td>'
	+'    <td class="sBlackText" background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_side_r.gif" width="10"></td>'
	+'  </tr>'
	+'  <tr>'
	+'    <td><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_corn_ll.gif" width="10" height="30"></td>'
	+'    <td background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_bot_bg.gif"></td>'
	+'    <td background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_bot_bg.gif"></td>'
	+'    <td background="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_bot_bg.gif" align="right"></td>'
	+'    <td><img src="http://www.rapattoni.com/multimedia/mls/ria/v10/images/ann_corn_lr.gif" width="10" height="30"></td>'
	+'  </tr>'
	+'</table>';

	var divTag = document.createElement("div");
	divTag.id = "container";
	divTag.style.cssText = "position:absolute; top: 0; margin-top:5px; display:none; z-index: 1000";
	divTag.innerHTML = strContainer;
	document.body.insertBefore(divTag);
	document.getElementById('container').style.display ='';

	if(side == 'left')
	{
		divTag.style.left = iLeft;
	}
	else(side == 'right')
	{
		divTag.style.right = iLeft;
	}
	
	dropDiv2(side);
}

//Removes announcement div
function removeDiv()
{
	document.getElementById('container').style.display = 'none';
}

mlsAttachEvent(window, 'onload', checkAnnouncementExp, null);

