function setLanguage( lang ) {
    // set a cookie with the selected language

    if( ! lang ) {
        // if lang isnt passed in, get from the cookie or auto detect
        lang = getLanguage();
    }
    if( lang ) {
        setCookie( 'lang', lang, 28 );
    }
}

function langRedirect( lang ) {
    // redirect to the index page for the selected language
    
    if( ! lang ) {
        // if lang isnt passed in, get from the cookie or auto detect
        lang = getLanguage();   
    }
    // set lang as the preferred language        
    setLanguage( lang );   
    
    var langUrls = {
        'en' : '/en/',   
        'fr' : '/fr/'
    }
    if( langUrls[ lang ] ) {
        // redirect to the appropriate url        
        window.location = langUrls[ lang ];
    }
}

function setLanguage( lang ) {
    // set a cookie with the selected language

    if( ! lang ) {
        // if lang isnt passed in, get from the cookie or auto detect
        lang = getLanguage();
    }
    if( lang ) {
        setCookie( 'lang', lang, 28 );
    }
}
function getLanguage() {    
    // return the selected language
    
    var lang = '';
    var cookies = getCookie();

    if( cookies[ 'lang' ] ) {
        // if set, use the language stored in the cookie
        lang = cookies[ 'lang' ];               
    } else {
        // otherwise, attempt to detect the language automatically
        if( navigator.userLanguage ) {
            lang = navigator.userLanguage;
        } else if( navigator.language ) {
            lang = navigator.language;
        } else if( navigator.browserLanguage ) {
            lang = navigator.browserLanguage;
        }
        if( lang ) {
            lang = lang.substring( 0, 2 ).toLowerCase();
        }
    }
    return lang;
}

function getCookie() {
    // returns an array of cookie values
    
    cookieData = new Array();
    cookieVals = window.document.cookie.split( ';' );

    for( idx in cookieVals ) {
        var parts = cookieVals[ idx ].replace( /^\s*([^\s]*)\s*$/, '$1' );
        parts = parts.split( '=' );
		cookieData[ parts[ 0 ] ] = unescape( parts[ 1 ] );
    }
    return cookieData;
}

function setCookie( idx, val, exp ) {
    // sets a cookie with the passed name and value
    // exp should be the expiry time in days

    var expires = null;
    
    if( exp ) {
       	var today = new Date();
    	var expiry = new Date( today.getTime() + exp * 24 * 60 * 60 * 1000 );
    	expires = expiry.toGMTString();
    }
	if( idx && val ) {
		window.document.cookie = idx + '=' + escape( val ) + ( expires ? ';expires=' + expires : '' ) + ';path=/';
	}
}
