window.onload = function() {
    setup_add_to_cart_buttons();
    setup_index_buttons();
    setup_remove_buttons();
    setup_add_to_cart_buttons();
    setup_remove_from_cart_buttons();
}

function setup_index_buttons() {
    if ( ! $('index_buttons') ) { return }

    var els = $$('#index_buttons li');
    for ( var i = 0; i < els.length; i++ ) {
        els[i].zof_effect = new Fx.Tween( els[i], {
            property: 'opacity',
            wait: false,
            duration: 400
        });
        els[i].zof_effect.set(1);
        els[i].onmouseover = function() {
            var lis = $$('#index_buttons li');
            for ( var j = 0; j < lis.length; j++ ) {
                if ( lis[j] == this ) { continue }
                lis[j].zof_effect.start(.4);
            }
        }
        els[i].onmouseout = function() {
            var lis = $$('#index_buttons li');
            for ( var j = 0; j < lis.length; j++ ) {
                lis[j].zof_effect.start(1);
            }
        }
    }
}
/*
function setup_add_to_cart_buttons() {
    var els = $$('.add_to_cart_button');
    
    new Image().src = '/pics/add_to_cart_button_hover.png';
    
    for ( var i = 0; i < els.length; i++ ) {
        els[i].onmouseover = function() {
            this.src = '/pics/add_to_cart_button_hover.png';
        }
        els[i].onmouseout = function() {
            this.src = '/pics/add_to_cart_button.png';
        }
    }
}*/

function setup_remove_buttons() {
    var els = $$('.remove_image_input');
    
    new Image().src = '/pics/remove_hover.png';
    
    for ( var i = 0, l = els.length; i < l; i++) {
        els[i].onmouseover = function() {
            this.src = '/pics/remove_hover.png';
        }
        els[i].onmouseout = function() {
            this.src = '/pics/remove.png';
        }
    }
}

function setup_add_to_cart_buttons() {
    var els = $$('.add_to_cart_form');
    
    if ( !els.length ) {
        return;
    }
    
    new Image().src = '/pics/add_to_cart_hover.gif';
    
    for ( var i = 0, l = els.length; i < l; i++ ) {
        els[i].getElement('.add_to_cart_button').onmouseover = function() {
            this.src = '/pics/add_to_cart_button_hover.png';
        }
        els[i].getElement('.add_to_cart_button').onmouseout = function() {
            this.src = '/pics/add_to_cart_button.png';
        }
        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/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() {
                        var cart_total = $('nav_cart_total_number').innerHTML;
                        
                        cart_total = this.zof_quantity.toFloat() * this.zof_price.toFloat() + cart_total.toFloat();
                        cart_total = sprintf("%.2f", cart_total);
                        if ( ! cart_total ) { cart_total = '0.00'; }
                        $('nav_cart_total_number').innerHTML = cart_total;
                    
                        if ( cart_total > 0 ) {
                            $('nav_your_cart').removeClass('nav_your_cart_hidden');
                        }
                    
                        this.zof_message_el.set({
                        'html': 'Added ' + this.zof_quantity + ' into the <a  href="/cart/">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.zof_price = this.getElements('input[name=price]')[0].value;
            req.post(this);
            
            return false;
        }
    }
}

function setup_remove_from_cart_buttons() {
    var els = $$('.view_cart_remove_form');
    for ( var i = 0, l = els.length; i < l; 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, '');

                        var cart_total = $('nav_cart_total_number').innerHTML;

                        cart_total = cart_total.toFloat() - this.zof_quantity.toFloat() * this.zof_price.toFloat();
                        cart_total = sprintf("%.2f", cart_total);
                        
                        if ( ! cart_total ) { cart_total = '0.00'; }
                        $('nav_cart_total_number').innerHTML = cart_total;
                        

                        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="/cart/">cart</a>'
                            });
                        }
                        else {
                            var table = this.zof_form.getParent('table');
                            this.zof_form.getParent('tr').dispose();
                            var left_items = table.getElements('tr');
                            if ( left_items.length <= 1 ) {
                                var container = table.getParent('div');
                                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.zof_price = this.getElements('input[name=price]')[0].value;
            req.post(this);
            return false;
        }
    }
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}
