/** CONF - the name of this file, with relative path
  *
  * It will be useful to find dynamically the domain where the javascript is executed
  * For example, if the src of javascript is "http://authent.idby.supermandarine.com/rubics/v1/js/authent.js?123"
  * the name of the javascript is "/js/authent.js"
  * while the domain we want to put in the var "authServer" is "http://authent.idby.supermandarine.com/rubics/v1"
  */

var jsname = '/js/authent.js';

/** END CONF */

// check service and lang parameters
if (typeof service == 'undefined' || !service || typeof lang == 'undefined' || !lang)
    alert('undefined service parameter or lang parameter');

// find the server where we are 
for (var i=0; i < document.getElementsByTagName('script').length; i++)
{
    j = document.getElementsByTagName('script')[i].src.indexOf(jsname);
    // if jsname is found in src attribute of script tag
    if (j != -1)
    {
        authServer = document.getElementsByTagName('script')[i].src.substring(0, j);
    }
}

// variables needed in the script, define them
var size = new Array;
var playOverlayEffect = true;
if (typeof color == 'undefined') var color = '';
if (typeof bd_color == 'undefined') var bd_color = '';
if (typeof opacity == 'undefined') var opacity = '';
if (typeof border_width == 'undefined') var border_width = '';
if (typeof libPrototypeOn == 'undefined') var libPrototypeOn = true;

if (typeof signin_width == 'undefined') var signin_width = '';
if (typeof signin_height == 'undefined') var signin_height = '';
if (typeof signup_width == 'undefined') var signup_width = '';
if (typeof signup_height == 'undefined') var signup_height = '';
if (typeof position_table_resize_iframe_left == 'undefined') var position_table_resize_iframe_left = '';
if (typeof position_table_resize_iframe_top == 'undefined') var position_table_resize_iframe_top = '';

// add style

    document.write("<link rel='stylesheet' type='text/css' href='"+authServer+"/css/rubics_main.css'/>");
    document.write("<!--[if IE]><link rel='stylesheet' type='text/css' href='"+authServer+"/css/rubics_main_ie.css'/><![endif]-->");


// add scripts if libPrototypeOn variable is true
if (libPrototypeOn)
{
    document.write("<script type='text/javascript' src='"+authServer+"/js/prototype.js'></script>");
    document.write("<script type='text/javascript' src='"+authServer+"/js/scriptaculous.js?load=effects'></script>");
}
else
{
    function switch_visibility(div)
    {
        var style = document.getElementById(div).style;
        if (style.display != 'block')
        {
            style.display='block';
            style.visibility='visible'; 
            style.zIndex='999';	
        }
        else
        {
            style.display='none';
            style.visibility='hidden';
            style.zIndex='0'; 	
        }
    }

    function setOpacity(element, opacity)
    {
        var style = element.style;
        style.opacity = opacity;
        style.MozOpacity = opacity;
        style.KHTMLOpacity = opacity;
        style.filter = 'alpha(opacity=' + (opacity*100) + ')';
    }
}

// creation of the div for the overlay layer : must be the first div loaded
var backOverlay = document.createElement('div'), frontOverlay = document.createElement('div');
backOverlay.id = 'overlay';
backOverlay.style.position = 'absolute';
backOverlay.style.display  = 'none';
backOverlay.style.left     = '0';
backOverlay.style.top      = '0';

// creation of the div for the authent iframe : must be the second div
frontOverlay.id = 'authent';
frontOverlay.style.position = 'absolute';
frontOverlay.style.display  = 'none';
frontOverlay.style.zIndex   = '999';
frontOverlay.style.backgroundColor = '#FFFFFF';
// frontOverlay.style.padding  = '6px';

// get first child of body tag
firstChild = document.body.firstChild;

// add authent div before first child of body tag
document.body.insertBefore(frontOverlay, firstChild)

// add overlay div before authent div
document.body.insertBefore(backOverlay, frontOverlay)

/**
 * put the overlay in the middle of the screen
 * and put the size of overlay
 */
function setMidPosition()
{
    var backOverlay = document.getElementById('overlay'), 
        frontOverlay = document.getElementById('authent'),
        Ws = size.w, Hs = size.h;

    var innerWidth, innerHeight;

    if (typeof window.innerWidth != 'undefined')
    {
        innerWidth = window.innerWidth;
        innerHeight = window.innerHeight;
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }
    else
    {
        var D = document.documentElement.clientWidth ? document.documentElement : document.body;
        if (D)
        {
            innerWidth = D.clientWidth;
            innerHeight = D.clientHeight;
            scrollX = D.scrollLeft
            scrollY = D.scrollTop
        }
    }

    if (innerWidth > Ws)
        posX = scrollX + (innerWidth - Ws) / 2 - 15;
    else posX = 0;

    if (innerHeight > Hs)
        posY = scrollY + (innerHeight - Hs) / 2 - 50;
    else posY = 0;

    var style1 = frontOverlay.style, style2 = backOverlay.style;
    style1.left = posX + 'px';
    style1.top  = posY + 'px';
    style2.width  = innerWidth + 'px';
    style2.height = innerHeight + 'px';

    style2.left = scrollX + 'px';
    style2.top  = scrollY + 'px';
}

// add listeners in case of resizing
if (document.all)
{
    document.body.onresize = setMidPosition;
    document.body.onscroll = setMidPosition;
}
else
{
    if (window.addEventListener)
    {
        window.addEventListener("resize", setMidPosition, false);
        window.addEventListener("scroll", setMidPosition, false);
    }
    else
    {
        window.attachEvent("resize", setMidPosition);
        window.attachEvent("scroll", setMidPosition);
    }
}

/**
 * close div element
 * 
 * @param {element} the div to close
 * @param {number} opacity of the div to close
 */
function close_d(div, opacity_from)
{
    if (libPrototypeOn)
    {
        new Effect.Appear(div, {
            duration:0.3, from:opacity_from, to:0.0, afterFinish: function() {
                var style = parent.document.getElementById(div).style;
                style.display = 'none';
                style.visibility = 'hidden';
            }
        });
    }
    else
    {
        var style = parent.document.getElementById(div).style;
        style.display = 'none';
        style.visibility = 'hidden';
    }
}

/**
 * displaying the div containing an iframe
 *
 * @param {string} url the url of iframe src
 * @param {string} name the iframe name
 */
function get_display_form(url, name) {

    // set default size width if undefined
    if (!size.w || size.w == 'undefined') size['w'] = 780;
    // set default size height if undefined
    if (!size.h || size.h == 'undefined') size['h'] = 340;

    var style_iframe = '';

    /** 
     * ADD 20/05/09
     * Patch for custom the iframe's dimensions.
     */
    if (name == 'ifr_signin')
    {
        style_iframe = 'scrolling="no"';
        if (typeof signin_width != 'undefined' && signin_width)
            size['w'] = signin_width;
        if (typeof signin_height != 'undefined' && signin_height)
            size['h'] = signin_height;
    } 
    else if (name == 'ifr_signup')
    {
        style_iframe = 'style="overflow:auto;"';
        if (typeof signup_width != 'undefined' && signup_width)
            size['w'] = signup_width;
        if (typeof signup_height != 'undefined' && signup_height)
            size['h'] = signup_height;
    }
    else if (name == 'ifr_resetpwd')
    {
        style_iframe = 'scrolling="no"';
    }

    /** 
     * ADD 23/12/08 
     * Patch for return url given by the PFS in javascript
     */
    if (typeof pfsurl != 'undefined' && pfsurl)
    {
        url += '&pfsurl=' + escape(pfsurl);
    }

    var backOverlay = document.getElementById('overlay'), 
        frontOverlay = document.getElementById('authent'),
        opacity_f = opacity / 100;

    // nb : All parameters are set in XML files and transformed in javascript variables
    // by the call of xml2js.php in the end of this file

    // set the style of the dark overlay
    backOverlay.style.backgroundColor = color;

    // show the dark overlay
    if (playOverlayEffect != false)
    {
        if (libPrototypeOn)
        {
            new Effect.Appear('overlay', {duration:0.5, fps:50, from:0.0, to:opacity_f, beforeUpdate:function()
            {backOverlay.style.display='block';backOverlay.style.visibility='visible';backOverlay.style.zIndex='900';}});
        }
        else
        {
            setOpacity(document.getElementById('overlay'), opacity_f);	
            switch_visibility('overlay');
        }
    }


    // prepare the content of the iframe
    if (name == "ifr_signup" && service == "healthwellness")
    {
        var innerBuffer = 
        '<div id="close" name="close" style="right:17px; top:20px;" onclick="javascript:close_d(\'overlay\','+opacity_f+');close_d(\'authent\',1);"></div>';
    }
    else if (name == "ifr_signin" && service == "healthwellness")
    {
    	var innerBuffer = 
        '<div id="close" name="close" style="right:17px; top:25px;" onclick="javascript:close_d(\'overlay\','+opacity_f+');close_d(\'authent\',1);"></div>';
    }
    else
    {
        var innerBuffer = 
        '<div id="close" name="close" onclick="javascript:close_d(\'overlay\','+opacity_f+');close_d(\'authent\',1);"></div>';
    }

    innerBuffer += '<iframe id="' + name + '" name="' + name + '" width="' + size.w + '" height="' + size.h + '" frameborder="0" ' +
    'marginwidth="0" scrolling="overflow-x:hidden" marginheight="0" ' + style_iframe + ' src="' + url + '"></iframe>';

    
    if (name == "ifr_signin" && service == "healthwellness")
    {
        innerBuffer += '<div id="switchToSignup" name="switchToSignup" onclick="javascript:switchToSignup();"></div>';
    }

    // set content in authent div
    frontOverlay.innerHTML = innerBuffer;

    // put the iframe on the middle
    setMidPosition();

    // set border width
    if (typeof border_width != 'undefined' && border_width)
    {
        var bd_width = border_width;
    }
    else
    {
        var bd_width = '1';
    }

    // set the border of authent div
    frontOverlay.style.border = bd_width + 'px solid ' + bd_color;
    frontOverlay.style.width  = size.w + 'px';
    frontOverlay.style.height = size.h + 'px';

    if (playOverlayEffect != false)
    {
        // show the authent div
        if (libPrototypeOn)
        {
            new Effect.Appear('authent', {duration:0.5, fps:75, from:0.0, to:1.0, beforeUpdate:function()
            {frontOverlay.style.display='block';frontOverlay.style.visibility='visible';frontOverlay.style.zIndex='999';}});
        }
        else
        {
            switch_visibility('authent');
        }
    }
}

/**
 * sign in, by displaying the div containing an iframe
 */
function signin()
{
    playOverlayEffect = true;
    get_display_form(authServer + '/?action=signin&lang=' + escape(lang) + '&service=' + escape(service), 'ifr_signin');
}

/**
 * sign up, by displaying the div containing an iframe
 */
function signup(choice)
{
    playOverlayEffect = true;
    var url = authServer + '/?action=signup&lang=' + escape(lang) + '&service=' + escape(service);
    if (choice)
        url += "&choice=new_account";
    get_display_form(url, 'ifr_signup');
}

/**
 * sign out
 */
function signout()
{
    url = authServer + '/signout_control.php?step=authent&lang=' + escape(lang) + '&service=' + escape(service);
    if (typeof pfsurl != 'undefined' && pfsurl)
        url += '&pfsurl=' + escape(pfsurl);
    document.getElementById('authent').innerHTML = '<iframe src="' + url + '"></iframe>';
}

/**
 * reset password
 */
function resetPwd(token)
{
    get_display_form(authServer + '/forgot_pwd_control.php?step=authent_on_reset_pwd&lang=' + escape(lang) + 
    '&service=' + escape(service) + '&token=' + escape(token), 'ifr_resetpwd');
}

/**
 * confirm the account registration with the token
 */
function confirmNSRU(confirm)
{
    get_display_form(authServer + '/signup_control.php?step=confirm&lang=' + escape(lang) + 
    '&service=' + escape(service) + '&confirm=' + escape(confirm), 'ifr_confirm');
}

/**
 * switch to signup view
 */
function switchToSignup()
{
    playOverlayEffect = false;
    get_display_form(authServer + '/?action=signup&choice=new_account&lang=' + escape(lang) + '&service=' + escape(service), 'ifr_signup');
    if (document.getElementById('switchToSignup'))
    {
        document.getElementById('switchToSignup').style.display = 'none';
    }
    //switch_visibility('authent');
}

/*
 * class AJAST
 * Allowing for cross-domain calls.
 */
if (typeof(OX) === 'undefined') OX = {};
OX.AJAST = 
{
    /**
     * call a service
     * 
     * @param {string} url the url to call
     * @param {function} callbackfunction function that will be called when the AJAST request completes
     */
    call: function(url, callbackfunction)
    {
        // create script tag for the call
        var tag = OX.AJAST.createScriptTag(url),

        // get the head of the document
        head = document.getElementsByTagName('head').item(0),

        // create a timeout function  
        timedout = function()
        {
            if (typeof callbackjson != 'undefined') // if the callback still exists...
            {
                // replace original wrapped callback with a dummy that just deletes itself
                callbackjson = function(){ delete callbackjson; };
                // signal that the call timed out
                callbackfunction(false, 'time out');
                // remove the script tag (timed out)
                script = document.getElementById('ajast');
                script.removeAttribute('src');

                try
                {
                    head.removeChild(tag); 
                }
                catch(e)
                {
                    alert('could not remove script ajast tag'+ e);
                }
            }
        },

        // create timer for the timeout function (2s)
        timer = setTimeout(timedout, 15000);
          
        // create the callback function
        callbackjson = function(data)
        {
            // clear the timeout
            clearTimeout(timer);

            if (typeof(data) === 'undefined')
            {
                callbackfunction(false); // callback with nothing
            }
            else
            {
                callbackfunction(true, data);
            }

            // replace original callback with a dummy function 
            delete callbackjson;

            // remove the script tag (finished)
            try
            {
                head.removeChild(tag);
            }
            catch(e)
            {
                alert('could not remove script ajast tag ' + e);
            }
        };
    
        // inject the call
        head.appendChild(tag);
    },

    /**
     * Create script tag with url in src attribute
     */
    createScriptTag: function(url)
    {
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('defer', 'defer');
        s.setAttribute('src', url);
        s.setAttribute('id', 'ajast');
        return s;
    }
};

/**
 * callback function called when xml file is read
 * 
 * @param {boolean} success the call success
 * @param {string} data string to evaluate
 */
function callCompleted(success, data)
{
    if (success)
    {
        eval(data);
    }
    else
    {
        alert("xml configuration file not read :: " + data);
    }
    return false;
}

// read xml parameters settings
OX.AJAST.call(authServer + '/xml2js.php?service=' + service, callCompleted);
