// DLV shop functionality
// Copyrights 2009, Loco (Loohuis Consulting)

// application initialization
document.observe('dom:loaded', function() {new DLVApp();});

var DLVApp = Class.create({
    // default search term content
    staticTerm: 'type een zoekterm',

    initialize: function()
    {
        // open/close faqs
        $$('.toggleview a.toggle').each(function(a)
        {
            a.observe('click', function(e)
            {
                var elm = Event.element(e);
                elm.up('div.toggleview').down('div.togglecontent').toggle();
                elm.scrollTo();
                Event.stop(e);
            });
        });

        // search functions
        if ($('productsearch'))
            this.initSearch();
        // show cart status
        if ($('status')) {
            new Ajax.Updater($('status'), '/store/cart.php', {
                parameters: {status: 1},
                onCreate: function() {$('throbber').show()},
                onComplete: function() {$('throbber').hide()}
            });
        }
        $$('a.bestellen').each(function(a) {a.observe('click', this.addOrder.bindAsEventListener(this))}, this);
        // cart actions
        $$('a.delorder').each(function(a) {a.observe('click', this.delOrder.bindAsEventListener(this))}, this);
        $$('a.recalc').each(function(a) {a.observe('click', this.recalc.bindAsEventListener(this))}, this);
        $$('a.expand').each(function(a) {a.observe('click', this.toggleExpand.bindAsEventListener(this))}, this);
        // switch delivery status
        $$('.deliveryswitch').each(function(e) {e.observe('change', this.toggleDeliveryDifferent.bindAsEventListener(this))}, this);
        $$('#deliverydifferent').each(function(e) {e.observe('change', this.switchDelivery.bindAsEventListener(this))}, this);

        // transfer address data
        $$('#transfer').each(function(a) {a.observe('click', this.transferAddress.bindAsEventListener(this))}, this);
        // validate user data
        $$('#address').each(function(f) {f.observe('submit', this.validateRegistration.bindAsEventListener(this))}, this);
        // toggle account data elements
        $$('input.payment').each(function(f) {f.observe('click', this.toggleAccount.bindAsEventListener(this))}, this);
        $$('form#payment').each(function(f) {f.observe('submit', this.validatePayment.bindAsEventListener(this))}, this);
        $$('input.deliveryat').each(function(f) {f.observe('click', this.toggleDelivery.bindAsEventListener(this))}, this);

        // tell-a-friend on products
        $$('a.tellafriend').each(function(a) {a.observe('click', this.toggleTAF.bindAsEventListener(this))}, this);
        $$('a.sendtaf').each(function(a) {a.observe('click', this.sendTAF.bindAsEventListener(this))}, this);

        // full order list actions
        this.setupOrderlist();
        $$('form#orderlist').each(function(a) {a.observe('submit', this.submitOrderlist.bindAsEventListener(this))}, this);

        // mailing subscribe
        $$('input.switchcat').each(function(a) {a.observe('click', function()
        {
            if ($('checkcompname').checked)
                $('togglecompname').show();
            else
                $('togglecompname').hide();
        })}, this);

        // Google map
        if ($('gmap'))
            this.loadMap();
    },

    // add an article to the cart
    addOrder: function(e)
    {
        var elm = Event.element(e);
        var form = elm.up('form');
        new Ajax.Updater($('status'), '/store/cart.php', {
            parameters: form.serialize(),
            onComplete: function() {new Effect.Highlight('winkelwagenstatus', {startcolor:'#B4D337', endcolor:'#FFFFFF'})}
        });
    },

    // delete an article from the cart
    delOrder: function(e)
    {
        var elm = Event.element(e);
        var form = elm.up('form');
        form.delorder.value = elm.getAttribute('orderid');
        form.submit();
    },

    // recalulate the cart
    recalc: function(e)
    {
        var elm = Event.element(e);
        var form = elm.up('form');
        form.recalc.value = 1;
        form.submit();
    },

    // show or hide bank account data
    toggleAccount: function(e)
    {
        if ($('accountcheck').checked)
            $('accountdata').show();
        else
            $('accountdata').hide();
    },

    // toggle delivery fields
    toggleDelivery: function(e)
    {
        var elm = Event.element(e);
        if (elm.value == 'afleveren bij buren') {
            $('deliveryatnr').enable();
            $('deliveryatother').disable();
        }
        else {
            $('deliveryatnr').disable();
            $('deliveryatother').enable();
        }
    },

    // validate payment parameters
    validatePayment: function(e)
    {
        var f = Event.element(e);
        if ($('accountcheck').checked) {
            if (!f.accountok.checked || !f.accountnumber.value || !f.accountname.value || !f.accountnbank.value || !f.accountdate.value) {
                Event.stop(e);
                $('paymentincomplete').show();
            }
            else
                $('paymentincomplete').hide();
        }
    },

    // set up search controls
    initSearch: function()
    {
        // initialize fields
        if (!$F('freetext'))
            $('freetext').value = this.staticTerm;
        // form change actions
        $('freetext').observe('focus', function(i)
        {
            $('freetext').activate();
            $$('#productsearch option').each(function(o) {o.selected = false});
            $$('.subregion').each(function(s) {s.disable()});
        });
        $('taste').observe('change', function(s)
        {
            $('freetext').value = this.staticTerm;
            $$('#experience option, .region option').each(function(o) {o.selected = false});
            $$('.subregion').each(function(s) {s.disable()});
        }.bindAsEventListener(this));
        $('experience').observe('change', function(s)
        {
            $('freetext').value = this.staticTerm;
            $$('#taste option, .region option').each(function(o) {o.selected = false});
            $$('.subregion').each(function(s) {s.disable()});
        }.bindAsEventListener(this));
        $$('.region').each(function(s) 
        {
            s.observe('change', function(e)
            {
                $('freetext').value = this.staticTerm;
                $$('#taste option, #experience option').each(function(o) {o.selected = false});
                // update if article type, country or region selection changes
                var mod = Event.element(e).name;
                if (mod == 'country' || mod == 'articletype' || mod == 'region') {
                    new Ajax.Updater('productsearch', '/searchproxy.php', 
                    {
                        parameters: Event.element(e).up('form').serialize(),
                        onComplete: this.initSearch.bind(this)
                    });
                }
            }.bindAsEventListener(this));
        }, this);
        // form submits
        $('search').observe('click', function(e) 
        {
            if ($F('freetext').indexOf(this.staticTerm) > -1)
                $('freetext').value = '';
            $('zoekform').submit();
        }.bindAsEventListener(this));
    },

    // expand order overview
    toggleExpand: function (e)
    {
        var elm = Event.element(e);
        $$('expand').each(function(r)
        {
            if (r.name != elm.name)
                $('orders' + r.name).hide();
        });
        $('orders' + elm.name).toggle();
    },

    // switch delivery display
    toggleDeliveryDifferent: function(e)
    {
        var elm = Event.element(e);
        if (elm.value == 'afhalen') {
            $$('.deliverydifferent').each(function(tr) {tr.hide();});
            $$('.deliver').each(function(tr) {tr.hide();});
        }
        else {
            $$('.deliverydifferent').each(function(tr) {tr.show();});
            if ($('deliverydifferent').checked)
                $$('.deliver').each(function(tr) {tr.show();});
        }
    },

    // switch delivery display
    switchDelivery: function(e)
    {
        var elm = Event.element(e);
        if (elm.checked) {
            $$('.deliver').each(function(tr) {tr.show();});
        }
        else {
            $$('.deliver').each(function(tr) {tr.hide();});
        }
    },

    // transfer address data
    transferAddress: function(e)
    {
        var elm = Event.element(e);
        elm = elm.up('form');
        elm.deliverycompname.value = elm.compname.value;
        elm.deliveryfirstname.value = elm.firstname.value;
        elm.deliverylastname.value = elm.lastname.value;
        elm.deliveryaddress.value = elm.address.value;
        elm.deliverypcode.value = elm.pcode.value;
        elm.deliverycity.value = elm.city.value;
        elm.deliveryphone.value = elm.telwork.value;
        Event.stop(e);
        return false;
    },

    // validate contact data
    validateRegistration: function(e)
    {
        var elm = Event.element(e);
        // check mandatory elements
        var inputs = $$('.mandatory');
        var incomplete = false;
        inputs.each(function(i)
        {
            if (i.value.length == 0) {
                incomplete = true;
                i.up('tr').addClassName('incomplete');
            }
            else
                i.up('tr').removeClassName('incomplete');
        });

        if (incomplete) {
            $('validateerror').show();
            Event.stop(e);
            return false;
        }
        else {
            if (elm.register && elm.register.value && $('user'))
                elm.user.value = elm.email1.value;
            $('validateerror').hide();
        }
    },

    // toggle tell-a-friend function
    toggleTAF: function(e)
    {
        var elm = Event.element(e);
        $(elm.name).toggle();
    },

    // send tell-a-friend message
    sendTAF: function(e)
    {
        var elm = Event.element(e);
        var id = elm.name;
        var f = elm.up('form');
        // validate input
        if (f.sender.value.length && f.recipient.value.length && f.name.value.length) {
            $('missingparms').hide();
            var d = f.parentNode;
            var tmp = new Element('div');
            d.insert(tmp);
            f.product.name = 'url';
            new Ajax.Updater(tmp, '/tafproxy.php', 
            {
                parameters: f.serialize(),
                onSuccess: function() {$$('div.tellafriend').each(function(d) {d.hide()});}
            });
        }
        else {
            $('missingparms').show();
        }
    },

    // set up order list
    setupOrderlist: function(e)
    {
        $$('td.outshortlist a').each(function(a) {a.observe('click', this.removeFromShortlist.bindAsEventListener(this))}, this);
        $$('td.inshortlist a').each(function(a) {a.observe('click', this.addToShortlist.bindAsEventListener(this))}, this);
    },

    // remove product from shortlist
    removeFromShortlist: function(e)
    {
        var elm = Event.element(e);
        var id = elm.up('td').id;
        new Ajax.Updater($('listcontainer'), '/bestellijst.php', 
        {
            parameters: 'profid=31&fulllist=1&shortlist=remove&artid=' + id,
            onComplete: this.setupOrderlist.bind(this)
        });
        Event.stop(e);
    },

    // add product to shortlist
    addToShortlist: function(e)
    {
        var elm = Event.element(e);
        var id = elm.up('td').id;
        new Ajax.Updater($('listcontainer'), '/bestellijst.php', 
        {
            parameters: 'profid=31&fulllist=1&shortlist=add&artid=' + id,
            onComplete: this.setupOrderlist.bind(this)
        });
        Event.stop(e);
    },

    // update orders in orderlist
    submitOrderlist: function(e)
    {
        var elm = Event.element(e);
        new Ajax.Request('/store/cart.php', 
        {
            parameters: elm.serialize(),
            onComplete: this.loadOrderlist.bind(this)
        });
        Event.stop(e);
    },

    // reload orderlist
    loadOrderlist: function(e)
    {
        new Ajax.Updater($('listcontainer'), '/bestellijst.php', 
        {
            parameters: 'profid=31&fulllist=1',
            onComplete: this.setupOrderlist.bind(this)
        });
    },

    // load Google map
    loadMap: function()
    {
        if (GBrowserIsCompatible()) {
            document.observe('unload', GUnload, false);
            // coordinates
            var coords = $('gmap').title.split(',');
//            var point = new GLatLng(52.086670026955864, 5.277961492101894);
            var point = new GLatLng(52.08902, 5.28190);
            // display map
            var map = new GMap2($('gmap'));
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            map.enableScrollWheelZoom();
            map.setCenter(point, 13);
            // add marker
            var myIcon = new GIcon();
            myIcon.image = "/skin/pin_dlv.png";
            myIcon.iconSize = new GSize(57, 58);
            myIcon.iconAnchor = new GPoint(5, 4);
            map.addOverlay(new GMarker(point , myIcon));
            // add directions
            var directions = new GDirections(map, $('gdirections'));
            $('routeform').observe('submit', function(e)
            {
                var elm = Event.element(e);
                directions.load('from: ' 
                    + elm.routefrom.value.replace(/(\d{4})\W+([A-Za-z]{2})/, "$1$2")
                    + ' to: ' + elm.routeto.value, {locale: 'nl_NL'});
                Event.stop(e);
            });
            GEvent.addListener(directions, 'addoverlay', function() {
                var last = directions.getMarker(directions.getNumRoutes());
                map.removeOverlay(last);
            });
        }
    }

});

