Array.prototype.sum = function(){
	for(var i = 0, sum = 0; i < this.length; sum += this[i++]);
	return sum;
}
Array.prototype.max = function() {
	return Math.max.apply({}, this);
}
Array.prototype.min = function() {
	return Math.min.apply({}, this);
}

/**
 * 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('');
}

document.observe('dom:loaded', function() {   
    $$('.toggle').each(function(elm) {
    	if( elm.value == "" ) {
    		elm.value = elm.title;
    	}
        elm.observe('focus', function() {
            if (elm.value == elm.title) {
                elm.value = '';
            }
        }).observe('blur', function() {
            if (elm.value == '') {
                elm.value = elm.title;
            }
        });
    });

    $$('.rel-tooltip').each(function(elm) {
        new Tooltip(elm, elm.readAttribute('rel'));
    });
    
    $$('.change').each(function(elm) {
    	elm.observe('focus', function() {
    		this.next('button').addClassName('change');
    	}).observe('blur', function() {
    		this.next('button').removeClassName('change');
    	});
    });

    $$('a.arrow-down').each( function(elm) {
    	
		var button = elm.previous('button');
		var link = elm.previous('a.button');
		var addTo = elm.up().next();
		
		addTo.observe("mouseover", this.show ).observe("mouseout", function(event) {
			var target  = event.relatedTarget || event.toElement;
			if(target) {
				if( target == this || target.descendantOf(this) ) {
					return;
				}
			}
		});
		
    	elm.observe("click", function(event) {
    		this.toggleClassName('open');
    		if(link) {link.toggleClassName('open open-submit');}
    		if(button) {button.toggleClassName('open');}
    		addTo.toggle();
    	});
    	
    });
    
	$(document.body).observe('click', function(event) {
		
		var elm = event.element();
		
		if (elm.up('.add-to')) {
			return;
		}
		
		$$('.add-to-wrap').invoke('hide');
		$$('.open').invoke('removeClassName', 'open');
		$$('.open-submit').invoke('removeClassName', 'open-submit');
		
	});    
    
    $$('a.add-to-cart', 'a.add-to-wishlist').each( function(elm) {
    	elm.observe("click", function(event) {
            event.stop();
    		var submitForm = elm.up('form.add-to');

    		if(elm.hasClassName('related-items')) {
    			$$('.add-to-wrap').invoke('hide');
    			$$('.open').invoke('removeClassName', 'open');
    			$$('.open-submit').invoke('removeClassName', 'open-submit');
	            Modalbox.show( elm.href, {
	                title: 'Selecteaza nuante',
	                width: 544,
	                overlayClose: false
	            });
    		} else {
	    		submitForm.action = this.href;
	    		submitForm.submit();
    		}
    	});
    });
    
    $$('a.show-desc').each(function(elm) {
        var descriptionLong = elm.previous('div.desc-full');
        var descriptionShort = elm.previous('div.desc-short');
        var on = elm.down('img.on');
        var off = elm.down('img.off');
        elm.observe('click', function (event) {
            if (descriptionLong.visible()) {
            	descriptionLong.hide();
            	off.hide();
            	descriptionShort.show();
            	on.show();
            } else {
            	descriptionShort.hide();
            	on.hide();
            	descriptionLong.show();
            	off.show();
            }
            event.stop();
        })
    });
    
    $$('#register_form h3 a').each(function (item){
        item.observe('click', function (event) {
            var box = item.up().next('div.step');
            if (!box.visible()) {
                $$('#register_form h3').invoke('removeClassName', 'active');
                item.up('h3').addClassName('active');
                $$('#register_form div.step').invoke('hide');
                box.show();
            }
        });
    });
    
    $$('a.print').invoke('observe', 'click', function (event) {
        event.stop();
        window.print();
    });
    
    $$('a.history-back').invoke('observe', 'click', function(event) {
    	event.stop();
    	history.go(-1);
    });
    
    $$('form.focusable').invoke('observe', 'submit', function(event) {
    	var input = this.down('input');
    	if (input.value == input.title) {
    		event.stop();
    		input.focus();
        }
    });
    
    $$('a[rel="external"]').each(function(link){
		if(link.readAttribute('href') != '' && link.readAttribute('href') != '#'){
				link.writeAttribute('target','_blank');
	    }
    }); 
    
    $$('#nav_category-wrap li ul li a img', 'ul.pagination li a', 'a.history-back','div.product', '#footer', '.flow #content', '.flow div.finalize-wrap').invoke('addClassName', 'cr');
    $$('.box-head', '.flow div.wide', '.flow div.already-registered').invoke('addClassName', 'tr');
    $$('.box-head', '.flow div.wide', '.flow div.register').invoke('addClassName', 'tl');
    $$('.box-content', 'p.tags', 'div.block-info', 'table.cart tfoot tr.actions tddiv.block-info', '#footer-newsletter', '.flow div.register', '.flow div.already-registered', 'table.cart tfoot tr.actions td').invoke('addClassName', 'br');
    $$('.box-content', 'p.tags', 'div.block-info', 'table.cart tfoot tr.actions tddiv.block-info', '#footer-newsletter', '.flow div.register', 'table.cart tfoot tr.actions td').invoke('addClassName', 'bl');
    
});