﻿//###############################
//# Declarations                #
//###############################



var _mstrWebEditURL = getRoot() + 'Editor/'; //Note: Always end this var with a / char
var _mintEscCount = 0;
var _mstrLoginBox = '';

//###############################
//# Event Hooks                 #
//###############################
window.document.onkeyup = _icb_KeyDown; // Monitors key presses to check for Escape x 3

//###############################
//# Functions                   #
//###############################
function getRoot() {
    //alert(location.href.substring(0, location.href.lastIndexOf("/Editor") + 1));

    var base = "";

    if (location.href.lastIndexOf("/Editor") > 0)
        base = location.href.substring(0, location.href.lastIndexOf("/Editor") + 1);
    else
        base = location.href.substring(0, location.href.lastIndexOf("/") + 1);

    

    return base; 

}

function _icb_GetActiveLink() {
    return _mobjActiveLink;
}
function _icb_GetActiveImage() {
    return _mobjActiveImage;
}

function _icb_DesignMode(pstrId) {
    document.getElementById(pstrId).contentWindow.document.designMode = 'On';
}



function _icb_ShowUserList() {
    var intWidth = 600;
    var intHeight = 500;
    var intLeft = (screen.availWidth / 2) - (intWidth / 2);
    var intTop = (screen.availHeight / 2) - (intHeight / 2) - 40;

    window.open(_mstrWebEditURL + 'aspx/UserList.aspx', '_blank', 'Height=' + intHeight + ', Width=' + intWidth + ', Top=' + intTop + ', Left=' + intLeft + ', toolbar=no, statusbar=yes, menu=no, scrollbars=no, resizable=yes');
}

function _icb_KeyDown(e) {
    //Declarations
    var objEvent;

    //Cross browser compliance for identifying key press events
    if (navigator.appName.toLowerCase() == 'microsoft internet explorer' || navigator.platform.toLowerCase() == 'macintel') { objEvent = event } else { objEvent = e }

    //Function that monitors every key press on the page and displays a centered login box
    //if it detects that the escape key has been pressed quickly 3 times in a row
    if (objEvent.keyCode == 27) {

            _mintEscCount++;
            if (document.getElementById('_icb_Login').style.display == '') {
                document.getElementById('_icb_Login').style.display = 'none';
                _mintEscCount = 0;

            }
            else if (_mintEscCount >= 3) {

                var intHeight = 202;
                var intWidth = 392;
                var intTop = 0;
                var intLeft = 0;


                if (navigator.platform.toUpperCase() == 'MACINTEL') {
                    intTop = (self.innerHeight / 2) - (intHeight / 2) - 100;
                    intLeft = (self.innerWidth / 2) - (intWidth / 2);
                }
                else {
                    intTop = (f_clientHeight() / 2) - (intHeight / 2) - 100;
                    intLeft = (f_clientWidth() / 2) - (intWidth / 2);
                }
                if (intTop < 0)
                    intTop = 0;

                document.getElementById('_icb_Login').style.top = parseInt(intTop) + 'px';
                document.getElementById('_icb_Login').style.left = parseInt(intLeft) + 'px';
                document.getElementById('_icb_Login').style.display = '';
                document.getElementById('_icb_username').focus();

                _mintEscCount = 0;
            }
            else {
                window.setTimeout('_mintEscCount=0;', 2000);
            }
        
    }
}




function _icb_Login() {

    //Declarations

    var objHTTPRequest = _icb_CreateHTTPRequestObject();  //Create an ajax request object

    var strParams = '_icb_username=' +
                        document.getElementById('_icb_username').value + '&' +
                        '_icb_password=' +
                        document.getElementById('_icb_password').value + '&' +
                        '_icb_page=' +
                        escape(window.location.href);

    //Disable the Login button and fiels so that the user cannot keep clicking or changing them mid post
    document.getElementById('_icb_LoginFields').style.display = 'none';
    document.getElementById('_icb_LoginWaitMessage').style.display = '';

    //Setup an ajax GET command to the IsFirstLogin.aspx script to see if this is the first time
    //anyone has logged into WebEdit on this website.
   

    objHTTPRequest.open("POST", _mstrWebEditURL + 'Login.ashx', true);
    objHTTPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objHTTPRequest.setRequestHeader("Content-length", strParams.length);
    objHTTPRequest.setRequestHeader("Connection", "close");

    //Build the function that will be executed the HTTPRequest object's onreadystatechange event
    objHTTPRequest.onreadystatechange = function() {
        if (objHTTPRequest.readyState == 4)
            _icb_LoginResponse(objHTTPRequest.responseText);
    };
    //Send the ajax request
    objHTTPRequest.send(strParams)

}

function _icb_LoginResponse(pstrResponse) {

    //If the ajax response was FAILED then the login details are incorrect  
    if (pstrResponse != '' && (!isNaN(pstrResponse)) && pstrResponse != '0') {
        //Login details have been validated so show the Success message and refresh
        document.getElementById('_icb_LoginWaitMessage').style.display = 'none';
        if (navigator.platform.toUpperCase() != 'MACINTEL')
            document.getElementById('_icb_LoginSuccess').style.display = '';

        //Now refresh the page so that the content block components can test for the WebEdit cookies
        //and render themselves in Edit mode.
        window.location.href = _mstrWebEditURL + 'EditorMain.aspx'; //window.location.href;
    }
    else {
        //Have received a login response so hide the please wait message
        document.getElementById('_icb_LoginWaitMessage').style.display = 'none';

        //If the Login script has returned a message show it to user otherwise just show the invalid login try again message
        if (pstrResponse.indexOf('<message>') != -1) {
            document.getElementById('_icb_LoginFailureMessage').innerHTML = pstrResponse.replace('<message>', '').replace('</message>', '')
            document.getElementById('_icb_LoginFailureMessage').style.display = '';
        }
        else {
            document.getElementById('_icb_LoginFailure').style.display = '';
            document.getElementById('_icb_tryagain').focus();
        }
    }
}
function _icb_TryLoginAgain() {
    //User wishes to try the login again after a failure so show the login fields again
    document.getElementById('_icb_LoginFields').style.display = '';
    document.getElementById('_icb_LoginWaitMessage').style.display = 'none';
    document.getElementById('_icb_LoginFailure').style.display = 'none';
    document.getElementById('_icb_LoginFailureMessage').style.display = 'none';
    document.getElementById('_icb_username').focus();
}

function _icb_PasswordReset() {
    //Declarations
    var objHTTPRequest = _icb_CreateHTTPRequestObject();  //Create an ajax request object

    //Make sure that the user has entered their email address in the login Email field
    if (document.getElementById('_icb_username').value != '') {
        if (confirm('Are you sure you wish to reset your WebEdit password?')) {
            objHTTPRequest.open("GET", _mstrWebEditURL + 'aspx/ResetPassword.aspx?Email=' + escape(document.getElementById('_icb_username').value), true);

            //Build the function that will be executed the HTTPRequest object's onreadystatechange event
            objHTTPRequest.onreadystatechange = function() {
                if (objHTTPRequest.readyState == 4)
                    _icb_PasswordResetResponse(objHTTPRequest.responseText);
            };
            //Send the ajax request
            objHTTPRequest.send(null)

            //Show the user that we are resetting their password
            document.getElementById('_icb_ForgottenPasswordLabel').innerHTML = 'Please wait...';
        }
    }
    else
        alert('Please enter your email address in the Email field before asking for your password to be reset');
}
function _icb_PasswordResetResponse(pstrResponse) {
    if (pstrResponse == 'OK')
        document.getElementById('_icb_ForgottenPasswordLabel').innerHTML = 'Password Reset [<span style="text-decoration:underline; color:blue; cursor:pointer" title="Your password has been reset and an email containing your new password has been sent to the address specified" onclick="alert(\'Your password has been reset and an email containing your new password has been sent to the address specified\')">?</span>]';
    else
        document.getElementById('_icb_ForgottenPasswordLabel').innerHTML = 'Password NOT Reset! [<span style="text-decoration:underline; color:blue; cursor:pointer" title="' + pstrResponse + '" onclick="alert(\'' + pstrResponse + '\')">?</span>]<br /><a href="javascript:mfForgottenPasswordTryAgain()">try again</a>';

}
function mfForgottenPasswordTryAgain() {
    document.getElementById('_icb_ForgottenPasswordLabel').innerHTML = '<a href="javascript:_icb_PasswordReset();">I\'ve Forgotten My Password</a>';
}

function _icb_BuildLoginBox() {

    //Declare a variable and populate it with the HTMl that will make up the Login Box layer
    var _strLoginBox = '<div id="_icb_Login" style="color:black;display:none; width:392px; height:202px; position:absolute;top:0px;left:0px; background-image:url(\'' + _mstrWebEditURL + 'images/LoginBox_Background.gif\');">' +
                       '<div style="font-family:arial; font-size:medium; text-align:right; margin-left:60px; height:60px; padding:10px; margin-top:4px; margin-right:10px;">' +
                         'SJLC Admin Login' +
                         '<div id="_icb_LoginFormHeader" style="color:black;padding-top:3px; text-align:center; font-size:x-small;">' +
                           '' +
                         '</div>' +
                       '</div>' +
                       '<div style="color:black;font-family:arial; font-size:small; text-align:center; margin-top:10px; margin-right:20px;">' +
                         '<div id="_icb_LoginFields" style="text-align:center; font-size:x-small;">' +
                           '<center>' +
                             '<form id="_icb_Loginform" method="post">' +
                               '<table  style="border:0px;padding:0px; margin:0px;">' +
                                 '<tr>' +
                                   '<td align=right style="color:black;border:0px;padding:0px; margin:0px;">Username:</td>' +
                                   '<td style="border:0px;padding:0px; margin:0px;"><input type="text" name="_icb_username" id="_icb_username" style="width:200px" onkeydown="if (event.keyCode == 13) {_icb_Login()}"/></td>' +
                                 '</tr>' +
                                 '<tr>' +
                                   '<td align=right style="color:black;border:0px;padding:0px; margin:0px;">Password:</td>' +
                                   '<td style="border:0px;padding:0px; margin:0px;"><input type="password" name="_icb_password" id="_icb_password" style="width:200px" onkeydown="if (event.keyCode == 13) {_icb_Login()}"/></td>' +
                                 '</tr>' +
                                 '<tr>' +
                                   '<td colspan="2" align="right" style="border:0px;padding:0px; margin:0px; text-align:right;">' +
                                     '<!--<div id="_icb_ForgottenPasswordLabel" style="float:left; margin-top:5px; margin-left:50px; text-align:center;"><a href="javascript:_icb_PasswordReset();">I\'ve Forgotten My Password</a></div>-->' +
                                     '<div style="float:right;"><input id="cmdLogin" type="button" value="Login >" onclick="_icb_Login()" /></div></td>' +
                                 '</tr>' +
                               '</table>' +
                               '<input type="hidden" name="_icb_webeditlogin" />' +
                             '</form>' +
                           '<center>' +
                         '</div>' +
                         '<div id="_icb_LoginWaitMessage" style="text-align:center; font-size:medium; display:none">' +
                           '<br />Checking login details<br />Please wait...' +
                         '</div>' +
                         '<div id="_icb_LoginFailureMessage" style="text-align:center; font-size:medium; display:none">' +
                         '</div>' +
                         '<div id="_icb_LoginFailure" style="text-align:center; font-size:medium; display:none">' +
                           '<br />Invalid login details!<br /><br /><input type="button" id="_icb_tryagain" value="Try Again" onclick="_icb_TryLoginAgain();"/>' +
                         '</div>' +
                         '<div id="_icb_LoginSuccess" style="text-align:center; font-size:medium; display:none">' +
                           '<br />Login successfull!<br /><br />Please wait while we enable Editor' +
                         '</div>' +
                       '</div>' +
                     '</div>';

    //Write the Login layer to the document
    document.write(_strLoginBox);
}

function _icb_CreateHTTPRequestObject() {
    var xmlhttp = false;

    /*@cc_on@*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    @end@*/

    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
            //xmlhttp.overrideMimeType('text/xml');
        } catch (e) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}

function f_clientWidth() {
    return f_filterResults(
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
    return f_filterResults(
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
    return f_filterResults(
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
    return f_filterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


//###############################
//# Page Load Code              #
//###############################


//Set all p tags so that they do not carry a margin.  This will solve the double line break issue in WebEdit mode
document.write('<style' + ' type="text/css">p {margin:0px;}<\/style>');

_icb_BuildLoginBox();
