/**
 * Namespace for website authentication methods
 */
cfc.namespace("auth");

//'xmlhttp' request object, do not access directly, use getXmlHttp instead
var xmlhttp = null;

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = '';
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\\r\\n/g,'\\n');
        var utftext = '';
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    }
}

cfc.auth = {
		
		/**
		 * Logout of the website
		 */
		logout: function(ctx, redirect) {
			// try to clear the authentication cache of the browser for our site
		    if (document.all) {
		        // Internet Explorer: 'ClearAuthenticationCache' is only available in IE
		        document.execCommand('ClearAuthenticationCache');
		
		    } else {
		        if (navigator.userAgent.indexOf("Safari") != -1
		            || navigator.userAgent.indexOf("Chrome") != -1
		            || navigator.userAgent.indexOf("Opera") != -1) {
		
		            // Safari, Chrome and Opera: remove authorization cookie
		            document.cookie = "Authorization=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
		        } else {
		        	var xmlhttp = cfc.auth.getXmlHttp();
				    if (!xmlhttp) {
				    	return;
				    }

				    if (xmlhttp.readyState < 4) {
						xmlhttp.abort();
					}
				    
		            // Firefox/Mozilla: use anonymous "login" to trigger a "logout"
		            xmlhttp.open("GET", ctx + "?sling:authRequestLogin=1", false, "anonymous", "null");
		            xmlhttp.send('');
		        }
		    }
		    
		    if(redirect)
		    {
		    	document.location.href=document.location.href;
		    }
		},
		
		getXmlHttp: function() {
		    if (xmlhttp) {
			return xmlhttp;
		    }

		    if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		    } else if (window.ActiveXObject) {
			try {
			    xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
			} catch (ex) {
			    try {
				xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
			    } catch (ex) {
			    }
			}
		    }
		    return xmlhttp;
		},
		
		sendRequest: function(/* String */contextPath, /* String */user, /* String */ pass) {
		    var xmlhttp = cfc.auth.getXmlHttp();
		    if (!xmlhttp) {
		    	return;
		    }

		    if (xmlhttp.readyState < 4) {
			xmlhttp.abort();
		    }

		    // Safari, Chrome and Opera: use cookie instead of Authorization http header
		    var authCookie = null;
		    if (navigator.userAgent.indexOf('Safari') != -1
		        || navigator.userAgent.indexOf('Chrome') != -1
		        || navigator.userAgent.indexOf('Opera') != -1) {
		        var credentials = 'Basic ' + Base64.encode(user + ':' + pass);
		        authCookie = 'Authorization="' + credentials + '"; path=/';
		        document.cookie = authCookie;
		    }

		    // send the authentication request
		    xmlhttp.open('GET', "/cfc.html?sling:authRequestLogin=1", false, user, pass);
		    xmlhttp.send('');
		    var success = xmlhttp.status == 200;

		    // if we weren't successful, make sure we don't stay logged in
		    // with bogus credentials
		    if(!success)
		    {
		    	if (authCookie) {
		    		document.cookie = authCookie + '; expires=' + new Date(0).toGMTString();
		    	} else {
		    		cfc.auth.logout();
		    	}
		    }

		    return success;
		},

		/**
		 * Login to the website
		 */
		loginuser: function() {
			var contextPath = document.forms['login'].contextPath.value;
		    var user = document.forms['login'].usr.value;
		    var pass = document.forms['login'].pwd.value;
		    var resource = document.forms['login'].resource.value;
		    
		    // if no user is given, avoid login request
		    if (!user) {
		        return false;
		    }

		    // send user/id password to check and persist
		    if (cfc.auth.sendRequest(contextPath, user, pass)) {

		        var u = resource;
		        if (window.location.hash) {
		            u = u + window.location.hash;
		        }
		        document.location = u;

		    } else {

		        alert("Username and Password do not match");

		    }

		    return false;
		}
}