'Returns JavaScript that:
#.  Triggers the ``options.onLoginComplete(result, closer)``
handler set with the :ref:`authomatic.setup() <js_setup>`
function of :ref:`javascript.js <js>`.
#.  Calls the JavasScript callback specified by :data:`callback_name`
on the opener of the *login handler popup* and passes it the
*login result* JSON object as first argument and the `closer`
function which you should call in your callback to close the popup.
:param str callback_name:
The name of the javascript callback e.g ``foo.bar.loginCallback``
will result in ``window.opener.foo.bar.loginCallback(result);``
in the HTML.
:param int indent:
The number of spaces to indent the JSON result object.
If ``0`` or negative, only newlines are added.
If ``None``, no newlines are added.
:param custom:
Any JSON serializable object that will be passed to the
``result.custom`` attribute.
:param str stay_open:
If ``True``, the popup will stay open.
:returns:
:class:`str` with JavaScript.'

def popup_js(self, callback_name=None, indent=None, custom=None, stay_open=False):

    custom_callback = ('\n                                try    {{    window.opener.{cb}(result,    closer);    }}    catch(e)    {{}}\n                                '.format(cb=callback_name) if callback_name else '')
    return '\n                                (function(){{\n\n                                                closer    =    function(){{\n                                                                window.close();\n                                                }};\n\n                                                var    result    =    {result};\n                                                result.custom    =    {custom};\n\n                                                {custom_callback}\n\n                                                try    {{\n                                                                window.opener.authomatic.loginComplete(result,    closer);\n                                                }}    catch(e)    {{}}\n\n                                }})();\n\n                                '.format(result=self.to_json(indent), custom=json.dumps(custom), custom_callback=custom_callback, stay_open=('//    ' if stay_open else ''))
