var AUTH_COOKIE_NAME       = 'auth_tkt';
var PERSISTENT_COOKIE_NAME = 'ARCOS_PERSISTENT_LOGIN';
var BLOG_USER_COOKIE_NAME  = 'civitas_user_info';

/////////////////////////////////////////////////////////////////////////////
// getBlogUserData()
// returns a Javascript hash (object) containing the data that the blog
// gives for this user.
/////////////////////////////////////////////////////////////////////////////
function getBlogUserData() {
    var json_value = getCookieValue(BLOG_USER_COOKIE_NAME);
    if( json_value ) {
        return eval( '(' + json_value + ')' );
    } else {
        return {};
    }
}

/////////////////////////////////////////////////////////////////////////////
// get_username()
// Returns the username of the user. If the user is not logged in, it will return
// false
/////////////////////////////////////////////////////////////////////////////
function get_username() {
    var params = getBlogUserData();
    if (params.nickname) return params.nickname;

    // sometimes on IE we can't pick up BLOG_USER_COOKIE_NAME, so resort to getting username from other cookies
    params = _ourCookieParams();
    if (params.username) {
        end = params.username.indexOf( '@' );
        if (end == -1) end = params.username.length;
        return params.username.substring(0,end);
    }
        
    return null;
}

/////////////////////////////////////////////////////////////////////////////
// showUsername(elementId)
// shows the user's name (retrieved from the cookie) in the <element> with 
// the id 'divId' if no <element> is specified, it will try to use one with 
// the id of 'username' 
/////////////////////////////////////////////////////////////////////////////
function showUsername(elementId) {
    var username = get_username();
    /*if( username ) {*/
    // check for auth_tkt instead just like we do for become member/my profile chunk
    if( vanilla.hasAuthCookie() ) {
        // default value
        if( elementId == null ) 
            elementId = 'username'

        var element = document.getElementById(elementId);

        if( element != null ) {
            element.innerHTML = username;
        }
    }
}


/////////////////////////////////////////////////////////////////////////////
// setBackURL(backId)
// Will set the hidden input with the id 'backId' to the URL of the current 
// page. If no backId is specified, it will try to use one with the id of
// 'back'
/////////////////////////////////////////////////////////////////////////////
function setBackURL(backId) {
    if( backId == null ) 
        backId = 'back';

    var back = document.getElementById(backId);
    if( back != null ) {
        back.value = window.location;
    }
}

/////////////////////////////////////////////////////////////////////////////
// showLoginLogout(loginId, logoutId)
// shows or hides the <element>'s with the id's 'loginId' and 'logoutId'. 
// if no <element>s are specified, it will try to use the id's 'login' and 
// 'logout' 
/////////////////////////////////////////////////////////////////////////////
function showLoginLogout(loginId, logoutId) {
    var username = get_username();

    // set the defaults
    if( loginId == null )
        loginId = 'login';
    if( logoutId == null )
        logoutId = 'logout';

    var login  = document.getElementById(loginId);
    var logout = document.getElementById(logoutId);

    // if we have a username, then we are logged in
    //if( username ) {
    // check for auth_tkt instead just like we do for become member/my profile chunk
    if ( vanilla.hasAuthCookie() ) {
        if( login != null )
            login.style.display = 'none';
        if( logout != null )
            logout.style.display = '';
    }
    else {
        if( login != null )
            login.style.display = '';
        if( logout != null )
            logout.style.display = 'none';
    }
}


/////////////////////////////////////////////////////////////////////////////
// getCookieValue(cookieName)
// returns the value for the cookie named. This string will be url-decoded
// before being returned.
/////////////////////////////////////////////////////////////////////////////
function getCookieValue(name) {
    var value  = null;
    var cookie = document.cookie;
    var start, end;

    if ( cookie.length > 0 ) {
        start = cookie.indexOf( name + '=' );

        // if the cookie exists
        if ( start != -1 )  {
          start += name.length + 1; // need to account for the '='

          // set index of beginning of value
          end = cookie.indexOf( ';', start );

          if ( end == -1 ) end = cookie.length;

          value = decodeURIComponent( cookie.substring( start, end ) );
        }
    }
            
    return value;
}

/////////////////////////////////////////////////////////////////////////////
// getLastActionData()
// returns a Javascript hash (object) containing the data that the user
// filled in on the last action before being redirected to a Goto-Story
// page.
/////////////////////////////////////////////////////////////////////////////
function getLastActionData() {
    var json_value = getCookieValue('arcos_last_action_data');
    return eval('(' + json_value + ')');
}

var params;
function _ourCookieParams() {
    if( params != null ) 
        return params;

    var allcookies = document.cookie;
    if( allcookies == null || allcookies == '' ) {
        params = {};
        return params;
    }

    // first look for the auth cookie, which is base64 encoded
    var value = getCookieValue(AUTH_COOKIE_NAME);
    if( value ) {
        
        // Base64 decode the value
        value = decodeBase64(value); 
        
        // now just get the DATA portion of the mod_auth_tkt cookie
        value = value.substr(40);       // this removes the digest and
                                        // timestamp
        var bits = value.split('!');    // breaks up the uid, tokens
                                        // and user data
        value = bits[bits.length -1];
    }        
    
    // if that failed, look for the persistent cookie, which is not
    // base64 encoded
    if (value == null) {
        value = getCookieValue(PERSISTENT_COOKIE_NAME);
        if( value ) {
            // break off the hash and UID
            var bits = value.split('!');    
            value = bits[bits.length -1];
        }
    }

    // if after all that we found something, break it up into pairs
    // for param
    params = {};
    if (value != null) {
        // split it into name-value pairs and put into the params hash
        var pairs = value.split('&');
        for (var i = 0; i < pairs.length; i++) {
            var splitPair = pairs[i].split('=');
            params[decodeURIComponent(splitPair[0])] = 
                decodeURIComponent(splitPair[1]);
        }
    }

    return params;
}


/////////////////////////////////////////////////////////////////////////////
// Base64 decoding
// Adapted from the GPL code found at http://ostermiller.org/calc/encode.html
/////////////////////////////////////////////////////////////////////////////
var END_OF_INPUT = -1;
var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}
var base64Str;
var base64Count;
function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readReverseBase64(){   
    if (!base64Str) return END_OF_INPUT;
    while (true){      
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
    return END_OF_INPUT;
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}