﻿//ImagecastLauncher Feature List:
// 1.) Submit on pressing return key (Done)
// 2.) Provide Domain & Imagecast Authentication (Done)
// 3.) Default to "IDXRAD" application view (complete Imagecast UI). (Done)
// 4.) Cancel button clear's username and password (Done)
// 5.) Username and password boxes are cleared after Login complete. (Done)
// 6.) Default Authentication drop down to option last selected by profile user. (Done)
// 7.) Check to see if Imagecast URL is available and if not direct user to VPN site (www.pacsventure.com). (DONE)
// 8.) Clear username & password textbox default value when gotfocus (DONE)
// 9.) Add validation to user auth to check for following default "username": (i)Username; (ii)'' (DONE)
//10.) Add "Checking Network connectivity" DIV as default view when control is loading. (DONE) (7/9/2008)
//11.) Modify javascript to be cross browser compatible. (7/9/2008) (DONE)
//12.) Change "txtUserName" object to more unique name to aid in form identification. (7/9/2008) (DONE)
//13.) Change "span..." labeled objects to "div..." labeled. (7/9/2008) (DONE)
//14.) Change ImageCast image connectivity check HTML so that IMG tag isn't hidden (use DIV display:none instead) (7/9/2008) (DONE)
//15.) Modify HandleReturnKey() method to handle Firefox browser (7/11/2008) (DONE)
//16.) Create minimum browser check routine and disply alert if not IE 5.5 (7/11/2008) (DONE)

//Declare global variables for page 
//var strInDomain = new String('unkown');   //Variable used to store whether ImageCast URL is available or not 
var strImageCastURL = new String('https://pacs.inlandimaging.com/imagecast/Integration/ModuleLaunch/LaunchEnter.asp'); 
//var strImageCastChangePwdURL = new String('://pacs.inlandimaging.com/imagecast/ChangePassword.asp?LinkPageOnSuccess=/imagecast/fsmain.asp'); 
var strIE_Browser = false;

//function OnConnectionCheckError() 
//{ 
//    strInDomain = 'false'; 
//    OnFormLoad(); 
//} 
//function OnConnectionCheckLoad () 
//{ 
//    strInDomain = 'true'; 
//    OnFormLoad(); 
//}

function SetChangePWDUrl() {
    var prefix = strImageCastURL.substring(0,strImageCastURL.indexOf(':',0))
    return prefix + strImageCastChangePwdURL;
}
 
function OnFormLoad() {
    //alert(strImageCastURL); 
    detectBrowser(); //Run minimum browser detection routine

    SetAuthenticationPreference(); //Set cooking with auth source preference

    SetLogonMode(); //Determine connectivity and display appropriate logon box
    
    document.getElementById('txtImageCastLogonUserName').focus();
}

function detectBrowser()
{  
    var browser=navigator.appName;    
    
    function vIE()
    {
        return (browser=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;
    }    
    
    var version=parseFloat(vIE());    
    
    if ((browser=="Microsoft Internet Explorer") && (version>=5.5)) 
    {
        strIE_Browser = 'true';
    }
    else
    {
        strIE_Browser = 'false';
    }
}

function SetLogonMode() { 
    if (strIE_Browser == 'true')
    {        
        document.getElementById('divCheckBrowser').style.display = 'none';
        //document.getElementById('divCheckVPN').style.display = 'block'; 
        //if (strInDomain == 'true'){ 
            document.getElementById('divLoginImageCast').style.display = 'block'; 
        //    document.getElementById('divLoginVPN').style.display = 'none'; 
        //    document.getElementById('divCheckVPN').style.display = 'none'; 
        //} 
        //if  (strInDomain == 'false'){ 
        //    document.getElementById('divLoginImageCast').style.display = 'none'; 
        //    document.getElementById('divLoginVPN').style.display = 'block'; 
        //    document.getElementById('divCheckVPN').style.display = 'none'; 
        //} 
    }else{
        document.getElementById('divCheckBrowser').style.display = 'block';
    }
} 

function SetAuthenticationPreference() 
{    
    strAuthPrefvalue = new String(readCookie('AuthPref'));    
    
    if (strAuthPrefvalue == 'null') 
    { 
        //setCookie('AuthPref', 'Centricity') 
        createCookie('AuthPref','Centricity', 365);
    } 
    
    switch (strAuthPrefvalue.toString()){ 
        case 'DUVOISIN': 
            document.getElementById('optDUVOISIN').selected = true; 
            break; 
        default: 
            document.getElementById('optIMAGECAST').selected = true; 
    } 
} 

function ValidateCredentials() 
{ 
    if (document.getElementById('txtImageCastLogonUserName').value == '')
    {
        alert('Please enter your username to continue');
    } 
    else if (document.getElementById('txtPassword').value == '') 
    {
        alert('Please enter your password to continue');
    } 
    else 
    {
        FormSubmit(); 
    }
}  

function FormSubmit() {
    //
    // setup variables
    var parentForm = document.getElementById('txtImageCastLogonUserName').form;        
    var authType = document.getElementById('optAuthSource').value;
    //
    // Authentication type is Centricity 
    // Check the user credentials before login
    if (authType == "Centricity") 
    {
        //
        // Setup Ajax call
        var ajaxRequest;
        try {
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        }
        catch (e) {
            //IE Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    //
                    // Error
                    alert("Your browser does not support XMLHTTP!");
                    return false;
                }
            }
        }
        //
        // Setup ajax Callback
        ajaxRequest.onreadystatechange = function() {
            if (ajaxRequest.readyState == 4) {
                var ajaxResponse = ajaxRequest.responseText;
                switch (ajaxResponse)
                {
                case 'uiderror':
                    alert("You have entered an invalid user id");
                    break;
                case "pwexpired":
				    alert ("Your password is expired\r\rYou will be redirected to change your password.");
					// Set the intergration mode to change password and turn off viewer.
					document.getElementById('txtImagecastMode').value = 'CHANGEPASSWORD';
					document.getElementById('txtImageViewer').value = 'N';
										
                    parentForm.method = 'POST'; 
                    parentForm.action = strImageCastURL; 
                    parentForm.target = '_new'; 
                    parentForm.submit();
                    
                    // reset the intergration mode to change password and turn off viewer.
					document.getElementById('txtImagecastMode').value = 'IDXRAD';
					document.getElementById('txtImageViewer').value = 'Y';
					//
                    //clear password field and set focus
                    var pwdFld = document.getElementById('txtPassword');
                    pwdFld.value = '';
                    pwdFld.focus();
                    break;
                case "pwvalid":
				    //
				    //Set the parent form values and submit
                    parentForm.method = 'POST'; 
                    parentForm.action = strImageCastURL; 
                    parentForm.target = '_self'; 
                    parentForm.submit();
                    //
                    //clear username and password fields of values 
                    ClearDataFields();
                    //
                    //set cookie to selected authentication method 
                    //setCookie('AuthPref',document.getElementById('optAuthSource').value);  
                    createCookie('AuthPref',document.getElementById('optAuthSource').value, 365);
                    break;
                 default:
                    break; 
				}				
            }   
        }
        
		var userID = document.getElementById('txtImageCastLogonUserName').value; // "sbrus" //
		var queryString = "?userid=" + userID;
		ajaxRequest.open("GET", "/utils/check_user.aspx" + queryString, true);
		ajaxRequest.send(null);
    }
    else // Domain authentication
    {

        //Store the parent form values
        //var parentFormMethod = parentForm.method;
        //var parentFormAction = parentForm.action;
        //var parentFormTarget = parentForm.target;
       
        //Set the parent form values and submit
        parentForm.method = 'POST'; 
        parentForm.action = strImageCastURL; 
        //parentForm.target = '_new'; 
        parentForm.target = '_self'; 
        parentForm.submit(); 

        //Restore parent form values
        //parentForm.method = parentFormMethod;
        //parentForm.action = parentFormAction;
        //parentForm.target = parentFormTarget;
        //
        //clear username and password fields of values 
        ClearDataFields();
        //
        //set cookie to selected authentication method 
        //setCookie('AuthPref',document.getElementById('optAuthSource').value); 
        createCookie('AuthPref',document.getElementById('optAuthSource').value, 365); 
    } 
 } 
 
 function AfterFormSubmit() { 
    //window.close(); 
 } 
 
function HandleReturnKey(e) { 
     if ((e.keyCode && e.keyCode == 13) || (window.event.keyCode == 13))
     {
              // When they hit the return key, act like they hit the 'Login' button. 
              ValidateCredentials();       
              return true; 
     } else { 
       return true; 
     } 
} 
 
function ClearDataFields(){ 
    document.getElementById('txtImageCastLogonUserName').value = '';
    document.getElementById('txtPassword').value = '';
} 

//function getCookieVal (offset) { 
//  var endstr = document.cookie.indexOf (';', offset); 
//if (endstr == -1) 
//    endstr = document.cookie.length; 
//  return unescape(document.cookie.substring(offset, endstr)); 
//} 

//function GetCookie (name) { 
//  var arg = name + '='; 
//  var alen = arg.length; 
//  var clen = document.cookie.length; 
//  var i = 0; 
//  while (i < clen) { 
//    var j = i + alen; 
//    if (document.cookie.substring(i, j) == arg) 
//      return getCookieVal (j); 
//    i = document.cookie.indexOf(' ', i) + 1; 
//    if (i == 0) break;  
//  } 
//return null; 
//}
 
//function setCookie (name,value,expires,path,domain,secure) { 
//  document.cookie = name + '=' + escape (value) + 
//    ((expires) ? '; expires=' + expires.toGMTString() : '') + 
//    ((path) ? '; path=' + path : '') + 
//    ((domain) ? '; domain=.uregina.ca' : '') + 
//    ((secure) ? '; secure' : ''); 
//}

 
//function DeleteCookie (name,path,domain) { 
//  if (GetCookie(name)) { 
//    document.cookie = name + '=' + 
//      ((path) ? '; path=' + path : '') + 
//      ((domain) ? '; domain=.uregina.ca' : '') + 
//      '; expires=Thu, 01-Jan-70 00:00:01 GMT'; 
//  } 
//} 

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+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
