window.onload = function() {
    remove_dotted_border();
    setup_supplies_buttons();
    setup_remove_buttons();
    setup_checkout_flags();
    setup_add_to_cart_buttons();
    setup_remove_from_cart_buttons();
    setup_add_to_cart_hovers();
    setup_search_box();
    setup_product_page_button_hovers();
}

function setup_search_box() {
    var el = $('google_search_textbox');
    if ( ! el ) {
        return;
    }
    
    el.onfocus = function() {
        if ( this.value == 'Search') {
            this.value = '';
        }
    }
    el.onblur = function() {
        if ( this.value == '') {
            this.value = 'Search';
        }
    }
}

function setup_product_page_button_hovers() {
    var els = $$('.product_pages a');
    for ( var i = 0, l = els.length; i < l; i++ ) {
        els[i].zof_ef = new Fx.Tween( els[i], {
                property: 'background-color',
                link:     'cancel',
                duration: 700
            }
        );
        els[i].zof_ef.set('#6685b0');
        
        els[i].onmouseover = function() {
            this.zof_ef.options.duration = 200;
            this.zof_ef.start('#96a5e0');
        }
        els[i].onmouseout = function() {
            this.zof_ef.options.duration = 800;
            this.zof_ef.start('#6685b0');
        }
    }
}

function setup_add_to_cart_hovers() {
    var els = $$('.products tr', '#marketing_supply_files li');
    for ( var i = 0, l = els.length; i < l; i++ ) {
        els[i].zof_ef = new Fx.Tween( els[i], {
                property: 'background-color',
                link:     'cancel',
                duration: 700
            }
        );
        els[i].zof_ef.set('#fff');
        
        els[i].onmouseover = function() {
            this.zof_ef.options.duration = 200;
            this.zof_ef.start('#dadaff');
        }
        els[i].onmouseout = function() {
            this.zof_ef.options.duration = 1000;
            this.zof_ef.start('#fff');
        }
    }
}

function setup_supplies_buttons() {
    var els = $$('#supplies_categories a');
    for ( var i = 0, l = els.length; i < l; i++ ) {
        els[i].zof_ef = new Fx.Tween( els[i], {
                property: 'opacity',
                link:     'cancel',
                duration: 300
            }
        );
        els[i].zof_ef.set(0.5);
        els[i].onmouseover = function() { this.zof_ef.start(1); }
        els[i].onmouseout = function() { this.zof_ef.start(.5); }
        els[i].onclick = function() {
            this.blur();
            var els = $$('#supplies_categories a');
            for ( var i = 0, l = els.length; i < l; i++ ) {
                if ( els[i] != this ) {
                    els[i].zof_ef.start(0);
                }
            }
            this.zof_ef.set(1);
        }
    }
}

function remove_dotted_border() {
    var links = $$('#nav a', '.input_image', '#supplies_categories a');
    for ( var i = 0, l = links.length; i < l; i++ ) {
        links[i].onmousedown = function () {
            this.blur();
            return false;
        }
        links[i].onclick = function() {
            this.blur();
        }
        if ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) ) {
            links[i].onfocus = function() {
                this.blur();
            }
        }
    }
}

function show_checkout_flag_loading () {
    var el = $('content');
    el.addClass('checkout_countries_container_hidden')
    var loading = new Element('img', {
        'class': 'loading_circle',
        'src': '/pics/loading_circle.gif',
        'styles': {
            'display': 'block',
            'margin': '30px auto'
        }
    });
    
    loading.inject(el, 'bottom');
//     el.innerHTML += '<img class="loading_circle" src="/pics/loading_circle.gif" style="display: block; margin: 30px auto;">';
    return true;
}

function setup_checkout_flags() {
    if ( $('checkout_paynow_form') ) {
        new Image().src = '/pics/loading_circle.gif';
    
        $('checkout_paynow_form').onsubmit = show_checkout_flag_loading;
    
        var el = $('paypal_pay_now_button');

        new Image().src = '/pics/pay_now_hover.gif';
    
        el.onmouseover = function() {
            this.src = '/pics/pay_now_hover.gif';
        }
        el.onmouseout = function() {
            this.src = '/pics/pay_now.gif';
        }
    }
}

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

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_hover.gif';
        }
        els[i].getElement('.add_to_cart_button').onmouseout = function() {
            this.src = '/pics/add_to_cart.gif';
        }
        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('');
}
