/*  File Downloadd Authorization, version 1.0.0.2
 *  (c) 2008 Chris Anderson <chris@afterhoursdevelopers.com>
 *
 */
if (Object.isUndefined(Fda)) { var Fda = { } }

Fda = Class.create();
Fda.prototype = {
    initialize: function() {
        var me = this;
        var options = Object.extend({
            filetypes: ['.zip', '.pdf', '.doc', '.ppt', '.jpg', '.png'],
            cookiejar: { expires: 31556926, path: '/' },
            cookiekey: 'fda',
            ondlauthorized: me.onTrackDownload,
            ondlunauthorized: me.onDisplayForm,
            authcontainer: 'fda',
            authformurl: '/fileauthform.htm',
            authformaniopen: function(e) { new Effect.FdaOpen(e) },
            authformaniclose: function(e) { new Effect.FdaClose(e) },
            authformclosebtn: 'a#close'
        }, arguments[0] || {});
        this.options = options;
        this.cookiejar = new CookieJar(this.options.cookiejar);
        this.clicktype = 0;
        this.container = null;
        this.isdd = false;
        this.target = '';
        document.observe('dom:loaded', this.onInit.bindAsEventListener(this));
    },
    onInit: function(e) {
        var me = this;
        this.options.filetypes.each(
            function(e) {
                $$('a:[href*=\'' + e + '\']not([class~=nofda])').each(function(l) {
                    l.observe('click', this.onClick.bindAsEventListener(this));
                    l.observe('contextmenu', this.onClick.bindAsEventListener(this));
                } .bind(this));
            } .bind(this));
    },
    onGetDownload: function() {
    if (this.clicktype || !Prototype.Browser.Gecko) {
            window.location = this.target.href;
			//window.open(this.target.href);
        }
    },
    onClick: function(e) {
        this.clicktype = e.isLeftClick();
        if ((cookie = this.cookiejar.get(this.options.cookiekey)) != null && cookie.auth == 1) {
            this.options.ondlauthorized(Event.findElement(e,'a'), this)
        } else {
            this.options.ondlunauthorized(Event.findElement(e,'a'), this)
            Event.stop(e);
        }
    },
    onTrackDownload: function(e, o) {
        // local cookie
        var item = hash(e.href);
        var items;
        if ((cookie = o.cookiejar.get(o.options.cookiekey)) != null && typeof (cookie.count) != "undefined") {
            items = new Hash(cookie.count);
        } else {
            items = new Hash()
        }
        var count = items.get(item);
        count = (typeof (count) == "undefined") ? 1 : count + 1;
        items.set(item, count);
        o.cookiejar.put(o.options.cookiekey, { auth: 1, count: items });
        // google
        if (typeof (pageTracker) != "undefined") {
            pageTracker._trackPageview(e.href);
        }
    },
    onDisplayForm: function(e, o) {

        o.target = e;
        if (o.isdd) {
            return;
        }

        new Ajax.Request(o.options.authformurl, {
            method: 'get',
            onSuccess: function(transport) {
                // build container
                o.container = $(o.options.authcontainer);

                if (o.container == null) {
                    o.container = Builder.node('div', {
                        id: o.options.authcontainer,
                        style: 'display:hidden;'
                    });
                    $(document.body).insert(o.container);
                }

                o.container.hide();
                o.container.update('<div>' + transport.responseText + '</div>');

                new Effect.Center(o.container);
                Event.observe(window, 'resize', function(e) { new Effect.Center(o.container); });
                Event.observe(window, 'scroll', function(e) { new Effect.Center(o.container); });
                // hook form
                var form = o.container.select('form');
                if (form.length < 1) return;
                form = form[0];
                form.observe('submit', o.onFormSubmit.bindAsEventListener(o));
                var closebtn = o.container.select(o.options.authformclosebtn);
                if (closebtn != null) {
                    closebtn[0].observe('click', function(e) { o.options.authformaniclose(o.container); o.isdd = false; });
                }
                o.isdd = true;
                o.options.authformaniopen(o.container);

            }
        });

    },
    onFormSubmit: function(e) {
		
        Event.stop(e);
        var o = this;
        var form = Event.element(e);
		form.select('input[type=hidden]')[0].value = this.target.href;
		var data = form.serialize();
		if(form.newsletteroptin && !form.newsletteroptin.checked)
			data += "&newsletteroptin=off";   
        document.body.style.cursor = "wait";
        new Ajax.Request(form.action, {
            method: form.method,
            parameters: data,
            onSuccess: function(transport) {
                document.body.style.cursor = "default";
                var response = transport.responseXML.documentElement.childNodes[0].nodeValue.replace('\n', '<br />');
                var msg = o.container.down('p.error');
                if (response == 'OK') {
                    msg.update('Your file download will begin shortly.');
                    msg.removeClassName('error');
                    msg.addClassName('success');
                    setTimeout(function() { o.onGetDownload() }, 1000 * 3);
                    o.onTrackDownload(o.target, o);
                    o.options.authformaniclose(o.container);
                    o.isdd = false;
                } else {
                    msg.update(response);
                }
            },
            onError: function(transport) {
                document.body.style.cursor = "default";
                o.container.down('p.error').update(response);
				alert('here');
            }
        });
    }
}