// Shortcuts
//
function id(id) {
    return document.getElementById(id);
}


// Make an element fade in and out at a particular rate
//
var OpacityThrobber= PeriodicAnimation.makeSubclass();
OpacityThrobber.prototype._init= function(element, period) {
    PeriodicAnimation.prototype._init.call(this, period);
    this.element= element;
};
OpacityThrobber.prototype.animate= function() {
    var t= new Date().getTime()-this.epoch;
    this.set((Math.cos(t*2*Math.PI/this.period)+1)/2);
};
OpacityThrobber.prototype.set= function(d) {
    if ('opacity' in this.element.style)
        this.element.style.opacity= ''+d;
    else
        this.element.style.filter= 'alpha(opacity='+Math.floor(d*100)+')';
};


// XXX
//
var HoverCarousel= Object.makeSubclass();
HoverCarousel.prototype._init= function(element, slides, period) {
    this.element= element;
    this.spinner= new PeriodicAnimation(period);
};


// Make an element obey `min-height: 100%` in IE6
//
function pageHeightStrut() {
    var page= id('page');
    var viewportheight= document.documentElement.clientHeight;
    page.style.paddingBottom= '0';
    var naturalheight= page.offsetHeight;
    var pad= viewportheight-naturalheight;
    if (pad<0) pad= 0;
    page.style.paddingBottom= pad+'px';
    id('page-w').style.height=id('page-e').style.height= Math.max(viewportheight, naturalheight)+'px';
}


// On contact page, hide the license agreement row when it's not needed
//
function contact_purposeChanged() {
    var select= id('contact-purpose');
    var purpose= select.options[select.selectedIndex].value;
    var license= purpose==='xmlgatewayce' || purpose==='xmlgateway' || purpose==='ssoplugin'
      || purpose==='licensemanager' || purpose==='signup';
    var row= id('row-licensing');
    if (row)
        Element_classList(row)[license? 'remove' : 'add']('hidden');
}


// Popup login box
//
var LoginPopup= SwitchAnimation.makeSubclass();
LoginPopup.prototype._init= function(button, links, popup, shade) {
    SwitchAnimation.prototype._init.call(this, 500, 0);
    this.popup= popup;
    this.shade= shade;
    this.status= Node_getElementsByClassName(this.popup, 'status')[0].firstChild;
    button.onclick= this.clicked.bind(this, null);
    Node_getElementsByClassName(popup, 'cancel')[0].onclick= this.set.bind(this, 0);
    popup.onsubmit= this.submit.bind(this);
    for (var i= links.length; i-->0;)
        links[i].onclick= this.clicked.bind(this, links[i].href);
    this.href=this.request=this.timeout= null;
};
LoginPopup.prototype.set= function(aim) {
    SwitchAnimation.prototype.set.call(this, aim);
    if (id('mast-close') && aim===1)
        id('mast-close').onclick();
    if ('clientcarousel' in window)
        window.clientcarousel[aim===0? 'start' : 'stop']();
    if ('mastthrobber' in window)
        window.mastthrobber[aim===0? 'start' : 'stop']();
};
LoginPopup.prototype.clicked= function(href) {
    this.href= href;
    this.set(1);
    return false;
};
LoginPopup.prototype.show= function(d) {
    Element_classList(this.shade)[d===0? 'add' : 'remove']('hidden');
    Element_classList(this.popup)[d===0? 'add' : 'remove']('hidden');
    var shaded= Math.min(d*2, 1)*0.8;
    var popupd= Math.max((d-0.5)*2, 0);
    if ('opacity' in this.shade.style) {
        this.shade.style.opacity= shaded+'';
        this.popup.style.opacity= popupd+'';
    } else {
        this.shade.style.filter= 'alpha(opacity='+Math.floor(shaded*100)+')';
        this.popup.style.filter= d===1? '' : 'alpha(opacity='+Math.floor(popupd*100)+')';
    }
    var zoomd= 0.25+popupd*0.75;
    var zooms= zoomd===1? '' : 'scale('+zoomd+', '+(1.0/zoomd)+')';

    if ('transform' in this.popup.style)
        this.popup.style.transform= zooms;
    else if ('MozTransform' in this.popup.style)
        this.popup.style.MozTransform= zooms;
    else if ('webkitTransform' in this.popup.style)
        this.popup.style.webkitTransform= zooms;
    else if ('OTransform' in this.popup.style)
        this.popup.style.OTransform= zooms;
    else {
        this.popup.style.width= Math.floor(50*zoomd)+'%';
        this.popup.style.left= Math.floor(50-25*zoomd)+'%';
        this.popup.style.fontSize= Math.floor(100*zoomd)+'%';
    }

    if (d===1 && this.aim===1)
        this.popup.getElementsByTagName('input')[0].focus();
};

LoginPopup.prototype.submit= function() {
    if (this.request!==null)
        this.abort();
    this.status.data= 'Logging in...';
    this.request= new XMLHttpRequest();
    this.request.onreadystatechange= this.requestupdate.bind(this);
    this.timeout= setTimeout(this.timedout.bind(this), 12000);
    this.request.open('post', '/account/auth', true);
    this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    var email= this.popup.getElementsByTagName('input')[0].value;
    var passphrase= this.popup.getElementsByTagName('input')[1].value;
    this.request.send('email='+encodeURIComponent(email)+'&passphrase0='+encodeURIComponent(passphrase))
    return false;
};
LoginPopup.prototype.timedout= function() {
    this.status.data= 'Timed out';
    this.timeout= null;
    this.abort();
};
LoginPopup.prototype.abort= function() {
    if (this.request!==null) {
        this.request.onreadystatechange= Function.identity;
        this.request.abort();
        this.request= null;
    }
    if (this.timeout!==null) {
        clearTimeout(this.timeout);
        this.timeout= null;
    }
};
LoginPopup.prototype.requestupdate= function() {
    var request= this.request;
    if (request.readyState!==4)
        return;
    this.request= null;
    this.abort();
    if (request.status!==200 || !request.responseText.startsWith('//')) {
        this.status.data= 'Server failure';
        return;
    }
    var resp= JSON_parse(request.responseText.slice(2));
    if (resp.success) {
        setCookie('auth', resp.authkey, resp.duration*1000);
        this.status.data= 'Logged in';
        this.set(0);

        // On non-IE browsers, when login pop was spawned by an authreqd link,
        // follow the link post-login. On IE this can't be done as it will block navigation
        // to a download.
        //
        if (this.href===null || this.href==='/account/login')
            location.href= '/jss/service';
        else if (Element_classList(document.body).contains('ie'))
            location.reload();
        else
            location.href= this.href;
    } else {
        this.status.data= resp.message;
    }
};

function logoutClick() {
    setCookie('auth');
}


// Start throbber and min-height fix
//
(function() {
    var ie6= Element_classList(document.body).contains('ie6');
    var ie8= Element_classList(document.body).contains('ie8');

    // Add contact page folding
    //
    if (id('contact-purpose')) {
        id('contact-purpose').onchange= contact_purposeChanged;
        EventTarget_addEventListener(window, 'load', function () { setTimeout(contact_purposeChanged, 0) });
        contact_purposeChanged();
    }

    // Fix page height on IE6
    //
    if (ie6)
        EventTarget_addEventListener(window, 'resize', function() { setTimeout(pageHeightStrut, 50); } );

    // Add cookie-based login box (if cookies are available)
    //
    if (Element_classList(id('action-login')).contains('action-login')) {
        var t= ''+Math.floor(Math.random()*10000000);
        setCookie('test', t, 50000);
        if (getCookie('test')===t)
            new LoginPopup(
                id('action-login'), Array.fromList(Node_getElementsByClassName(document, 'authrequired')),
                id('login-pop'), id('login-shade')
            );
        setCookie('test');
    } else {
        id('action-login').onclick= logoutClick;
    }

    // Make glow div throb. On IE<9, this requires some contortions to get around its inabilty to
    // apply alpha filters and alpha images to the same element. Actually even this nesting
    // solution doesn't generate "right" results - it does a 'min' of opacities instead of multiplying
    // them, but the effect still looks good. If we could really be bothered to get it "right" a
    // Compositor filter might be usable, but what a shag eh.
    //
    var glow= id('mast-glow');
    if (glow) {
        if (ie8) {
            glow.style.backgroundImage= 'none';
            var backhack= Element_create('div', {id: 'backhack'});
            glow.appendChild(backhack);
        }
        window.mastthrobber= new OpacityThrobber(glow, 2400);
        window.mastthrobber.start();
    }
})();


