window.onload = function() {
//     setup_nav();
    setup_form_control_focus();
    setup_submit_buttons();
    setup_login_button();
    setup_confirm_buttons();
    setup_category_ajax_cart_add();
    if ( $('engraving_location') ) {
        change_engraving_location();
    }
    if ( $('view_order_order_comments') ) {
        setup_order_comments_textarea();
    }
//     setup_catalog_scroll();
    setup_completed_orders_scroll();
    setup_engraving_position_notice();
    setup_catalog_category_buttons();
    if ( $$('.remove_from_cart_form').length ) {
        setup_remove_from_cart_buttons();
    }
}

function setup_catalog_category_buttons() {
    if ( ! $('catalog_categories_list') ) return;

    var els = $$('#catalog_categories_list a', '#catalog_categories_list form');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].set({'styles':{'opacity': '1'}});
        els[i].onmouseover = function() {
            var lis = $$('#catalog_categories_list li');
            var id = this.getParent('li').id;
            for ( var j = 0; j < lis.length; j++ ) {
                if ( lis[j].id == id ) continue;
                
                lis[j].tween('opacity', '0.3');
            }
        }
        els[i].onmouseout = function() {
            var lis = $$('#catalog_categories_list li');
            var id = this.getParent('li').id;
            for ( var j = 0; j < lis.length; j++ ) {
                if ( lis[j].id == id ) continue;
                
                lis[j].tween('opacity', '1');
            }
        }
    }
}

function setup_completed_orders_scroll() {
    if ( ! $('completed_orders_jump_nav') ) return;
    
    $('completed_orders_jump_nav').onclick = function() {
        new Fx.Scroll( window, {
            duration: 1000,
            transition: 'expo:in:out',
            onComplete: function() {
                $('completed_orders_table').set('tween', {
                    duration: 800
                });
                $('completed_orders_table').highlight('#5AAAFF');
            }
        }).toElement($('completed-orders'));
        return false;
    }
}

function setup_engraving_position_notice() {
    var el = $('engraving_infromation_urn_name_title');
    if ( !el ) return;

    new Element('p', {
        'html': 'Note: the circle with letter "E" represents the side of the urn on which the engraving will be done.'
    }).inject(el,'after');
}

function setup_catalog_scroll() {
    if ( ! $('title_scroll') ) return;

    new Fx.Scroll( window, {
        duration: 1000,
        transition: 'expo:in:out'
    }).toElement($('title_scroll'));
}

function setup_order_comments_textarea() {
    var el = $('view_order_order_comments');
    el.zof_effect = new Fx.Morph( el, {
        link: 'cancel',
        duration: 200,
        transition: 'back:out'
    });
    
    el.zof_scroll = new Fx.Scroll( window );

    el.onfocus = function() {
        this.zof_size = this.getSize();
        this.zof_effect.removeEvents('complete');
        this.zof_effect.addEvent('complete', function(comment_el) {
                return function() {
                    comment_el.zof_scroll.toElement($('view_order_order_comments_title'));
                    comment_el.zof_effect.removeEvents('complete');
                }
            }(this)
        );
        this.zof_effect.start({
            'width': 500,
            'height': 500
        });
    }
    el.onblur = function() {
        setTimeout(function() {
            var el = $('view_order_order_comments');
            el.zof_effect.start({
                'width': el.zof_size.x,
                'height': el.zof_size.y
            });
        }, 300);
    }
}

function setup_form_control_focus() {
    var els = $$('input[type="text"]', 'textarea', 'input[type="password"]');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onfocus = function() {
            this.addClass('focus');
            return true;
        }
        els[i].onblur = function() {
            this.removeClass('focus');
            return true;
        }
    }
}

function setup_category_ajax_cart_add() {
    var els = $$('.category_buy_form', '#add_to_cart_form');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onsubmit = function() {
            new Element('input', {
                    type: 'hidden',
                    name: 'ajax',
                    value: '1'
                }
            ).inject(this);

            var quantity = this.getElements('[name=quantity]')[0].value;
            if ( !quantity || !quantity.match(/\d/) ) {
                alert("You must specify valid quantity");
                return false;
            }
            
            if ( quantity <= 0 ) {
                alert("Quantity must be greater than zero");
                return false;
            }

            var req = new Request.HTML({
                    url:'/cart/add',
                    onRequest: function() {
                        this.zof_message_el = new Element('p', {
                            'class': 'category_cart_add_message',
                            'html': '<img src="/pics/loading.gif" alt="Loading..." width="60" height="20" style="display: block; margin: 0 auto;">'
                        }).inject(this.zof_form, 'after');
                    },
                    onSuccess: function() {
                        this.zof_message_el.set({
                        'html': 'Added ' + this.zof_quantity + ' into the <a  href="/cart/view">cart</a>'});
                    },
                    onFailure: function(message) {
                        this.zof_message_el.set({
                            'class': 'error category_cart_add_message',
                            'html': "Error: " + message.status + ' ' + message.statusText
                        });
                    }
                }
            );
            req.zof_form = this;
            req.zof_quantity = this.getElements('input[name=quantity]')[0].value;
            req.post(this);
            return false;
        }
    }
}

function setup_confirm_buttons () {
    var els = $$('.clear_cart_button');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onclick = function () { 
            return confirm('Clear the cart? This action is not reversable');
        }
    }

    els = $$('.remove_from_cart_button');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onclick = function () { 
            return confirm('Remove this item from cart?');
        }
    }

    if ( $('view_orders_cancel_order_button') ) {
        $('view_orders_cancel_order_button').onclick = function () {
            return confirm('Cancel this order? This action is not reversable');
        }
    }
}

function change_engraving_location() {
    var loc = $('engraving_location');
    var idx = $('aef_location').selectedIndex;
    var sel_loc = $('aef_location').options[idx].value;
    if ( sel_loc == 'front' ) {
        loc.style.left = engraving_location_offsets.front.x + 'px';
        loc.style.top = engraving_location_offsets.front.y + 'px';
    }
    else if ( sel_loc == 'side' ) {
        loc.style.left = engraving_location_offsets.side.x + 'px';
        loc.style.top = engraving_location_offsets.side.y + 'px';
    }
    else if ( sel_loc == 'top' ) {
        loc.style.left = engraving_location_offsets.top.x + 'px';
        loc.style.top = engraving_location_offsets.top.y + 'px';
    }
}

function setup_login_button() {
    var img = new Image(66, 25);
    img.src = '/pics/login_button_hover.png';
    var img2 = new Image(66, 25);
    img2.src = '/pics/logout_button_hover.png';

    var el = $$('#zofcms_plugin_login input[type="image"]')[0];
    if ( el ) {
        el.onmouseover = function () { this.src = '/pics/login_button_hover.png' }
        el.onmouseout = function () { this.src = '/pics/login_button.png' }
    }
    
    var el2 = $$('#zofcms_plugin_login_logout input[type="image"]')[0];
    if ( el2 ) {
        el2.onmouseover = function () { this.src = '/pics/logout_button_hover.png' }
        el2.onmouseout = function () { this.src = '/pics/logout_button.png' }
    }
    
}

function setup_submit_buttons() {
    var els = $$('.input_submit');
    
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onmouseover = function () {
            this.addClass('hover_submit');
        }
        
        els[i].onmouseout = function() {
            this.removeClass('hover_submit');
        }

    }
}

function setup_nav () {
    var els = $$('#nav a');
    
    for (var i = 0; i < els.length; i++) {
        var eff = new Fx.Tween( document.body, {link: 'cancel', duration: 200, transition: Fx.Transitions.linear,
                onComplete: function(elem){
                    return function(){
                        setTimeout( function(){
                            window.location = elem.href
                        }, 200 )
                    }
                }(els[i])
            }
        );
        eff.set('opacity', 1);
        els[i].onclick = function(el, effect){
            return function(){
                effect.start('opacity', '0');
                return false;
            }
        }(els[i], eff)
    }
}

function setup_remove_from_cart_buttons() {
    var els = $$('.remove_from_cart_form');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onsubmit = function() {

            var quantity = this.getElements('[name=quantity]')[0].value;
            if ( !quantity || !quantity.match(/\d/) ) {
                alert("You must specify valid quantity");
                return false;
            }
            
            if ( quantity <= 0 ) {
                alert("Quantity must be greater than zero");
                return false;
            }

            new Element('input', {
                    type: 'hidden',
                    name: 'ajax',
                    value: '1'
                }
            ).inject(this);

            var req = new Request.HTML({
                    url:'/cart/remove',
                    onRequest: function() {
                        this.zof_message_el = new Element('p', {
                            'class': 'category_cart_add_message',
                            'html': '<img src="/pics/loading.gif" alt="Loading..." width="60" height="20" style="display: block; margin: 0 auto;">'
                        }).inject(this.zof_form, 'after');
                    },
                    onSuccess: function(x,y,quantity_left) {
                        quantity_left = quantity_left.replace(/\D+/g, '');

                        if ( quantity_left > 0 ) {
                            this.zof_form.getElements('[name=quantity]')[0].value = quantity_left; 
                            this.zof_message_el.set({
                                'html': 'Removed ' + this.zof_quantity + ' from the <a  href="/inventory/view_cart">cart</a>'
                            });
                        }
                        else {
                            var table = this.zof_form.getParent('table');
                            this.zof_form.getParent('td').dispose();
                            var left_items = table.getElements('td');
                            if ( left_items.length <= 1 ) {
                                var container = table.getParent('.entry_bottom');
                                var garbage = container.getChildren();
                                for ( var x = 0; x < garbage.length; x++ ) {
                                    garbage[x].dispose();
                                }
                                
                                var message = new Element('p', {
                                        'class': 'error',
                                        'html': 'There are no products in your cart.'
                                    }
                                );
                                message.inject(container);
                            }
                        }
                    },
                    onFailure: function(message) {
                        this.zof_message_el.set({
                            'class': 'error category_cart_add_message',
                            'html': "Error: " + message.status + ' ' + message.statusText
                        });
                    }
                }
            );
            req.zof_form = this;
            req.zof_quantity = this.getElements('input[name=quantity]')[0].value;
            req.post(this);
            return false;
        }
    }
}


