Array.prototype.shuffle = function(n) {
    if (n > this.length || n == undefined) {
        n = this.length;
    }
    
    indices = []
    while(indices.length < n) {
        rand_index = Math.round(Math.random() * (this.length - 1));
        if (indices.indexOf(rand_index) == -1) {
            indices.push(rand_index)
        }
    }
    
    new_array = []
    for(i = 0; i < indices.length; i++) {
        new_array.push(this[indices[i]]);
    }
    
    return new_array
}

Event.observe(window, 'load', function() {
    lnks = document.getElementsByTagName('a');
    for(i = 0; i < lnks.length; i++) {
        lnk = lnks[i]
        if (is_external_url(lnk.href)) {
            lnk.target = '_blank';
            Event.observe(lnk, 'click', function(e) {
                path = strip_protocol(Event.element(e).href)
                
                if (path.charAt(path.length - 1) == '/') {
                    path = path.substring(0, path.length - 1);
                } 
                track_custom('/external/' + path)
            })
        } else if (mail = is_mailto_url(lnk.href)) {
            Event.observe(lnk, 'click', function(e) {
                track_custom('/mail/' + mail)
            })
        }
    }
    
    if (location.pathname == '/') {
        boxes = $$('.vetrina_box');
        for(i = 0; i < boxes.length; i++) {
            box = boxes[i]
            var lnk = box.select('.vetrina_box_dettagli a')[0];
            if (lnk != undefined) {
                box.style.cursor = 'pointer';
                box.onclick = function() {
                    location.href = this.href;
                }.bind(lnk);
            }
        }
    }
    
    if (document.referrer != undefined) {
        ext = is_external_url(document.referrer)
        if (ext) {
            track_custom('/referrals/' + strip_protocol(document.referrer))
        }
    }
    
    $$('select.paypal-quantity').each(function(sel) {
        Event.observe(sel, 'change', on_quantity_change);
    })
})

function on_quantity_change(e) {
    sel = Event.element(e)
    val = sel.options[sel.selectedIndex].value
    if (val == '...') {
        ask_for_quantity(sel);
    }
}

function is_valid_quantity(q) {
    if ((r != null) && r.match(/^[0-9]+$/) && (parseInt(r) > 0)) {
        return true;
    }
    return false;
}

function ask_for_quantity(sel) {
    r = prompt('Digita quantità', '');
    if (!is_valid_quantity(r)) {
        sel.selectedIndex = 0;
        return;
    }
    
    n = parseInt(r);
    
    $$('select.paypal-quantity').each(function(s) {
       s.insertBefore(tag('option', {value: n}, n + ''), s.select('option').pop());
    })
    sel.selectedIndex = sel.options.length - 2;

}

function track_custom(path) {
    pageTracker._trackPageview(path)    
}

function log(msg) {
    try {
        console.log(msg);
    } catch(e) {}
}

function get_movie(el_id) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[el_id]
    } else {
        return document[el_id]
    }
}

GalleryManager = {
    '_galleries': {},
    '_ids': [],
    '_sizes': [],
    '_data': {},
    '_dom_loaded': false,
    'add': function(el_id, width, height) {
        width = width != undefined?width:710
        height = height != undefined?height:260
        
        swf_id = el_id + "_swf";
        
        this._ids.push(el_id);
        this._sizes[el_id] = {width: width, height: height}
        this._galleries[el_id] = swf_id;
        if (this._dom_loaded) {
            this._doAdd();
        }
    },
    '_doAdd': function() {
        old_ids = this._ids;
        this._ids = [];
        for(i = 0; i < old_ids.length; i++) {
            el_id = old_ids[i];
            dataArray = this._data[el_id]
            if (dataArray != undefined){
                setTimeout(function() {
                    GalleryManager.populate(el_id, dataArray);
                }, 1000)
            }            
            
            
            swf_id = this._galleries[el_id];
            width = this._sizes[el_id].width;
            height = this._sizes[el_id].height;
            
            flashvars = {}
            params = {'AllowScriptAccess': 'always', 'scale': 'noscale', 'menu': 'false', 'align': 'top', 'wmode': 'transparent'}
            attributes = {};
            swfobject.embedSWF("/swf/presentazioni.swf",
                               el_id,
                               width,
                               height,
                               '9',
                               'expressInstall.swf',
                               flashvars,
                               params,
                               attributes);            
       
        }
        this._dom_loaded = true;        
    },
    'onDomReady': function() {
      this._doAdd();
    },
    'populate': function(el_id, dataArray) {
        get_movie(el_id).create_from_data(dataArray);
    },
    'build': function(dataArray, el_id, width, height) {
        this.add(el_id, width, height);
        this._data[el_id] = dataArray;
    }
}
document.observe('dom:loaded', function() {
  GalleryManager.onDomReady()
});


NewsBoxManager = {
    '_data': [],
    '_titles': [],
    '_source_ids': [],
    '_dom_loaded': false,    
    'extract_data': function(containerNode) {
        data = []
        
        items = containerNode.select('.news-item');
        for(i = 0; i < items.length; i++) {
            _item = items[i];
            ob = {
                title: _item.select('.title')[0].firstChild.innerHTML,
                link: _item.select('a')[0].href,
                icon: _item.select('.icon')[0].src,
                date: _item.select('.date')[0].innerHTML
            }
            data.push(ob)
        }
        
        
        return data;
    },
    'add': function(source_id, title) {
        this._data[source_id] = this.extract_data($(source_id));
        this._source_ids.push(source_id)   
        this._titles[source_id] = title
        if (this._dom_loaded) {
            this._doAdd();
        }
    },
    '_doAdd': function() {
        old_ids = this._source_ids;
        this._source_ids = [];
        for(i = 0; i < old_ids.length; i++) {            
            source_id = old_ids[i]
            flashvars = {'sourceID': source_id}
            params = {'AllowScriptAccess': 'always', 'scale': 'noscale', 'menu': 'false', 'align': 'top', 'wmode': 'transparent'}
            attributes = {}
            swfobject.embedSWF("/swf/news.swf",
                               source_id,
                               215,
                               260,
                               '9',
                               'expressInstall.swf',
                               flashvars,
                               params,
                               attributes);              
            
        }     
        this._dom_loaded = true; 
    },
    'onDomReady': function(e) {
        this._doAdd();
    },
    'get_items': function(source_id) {
        return this._data[source_id]
    }
}

document.observe('dom:loaded', NewsBoxManager.onDomReady.bind(NewsBoxManager))

function get_news_items(source_id) {
    src = NewsBoxManager.get_items(source_id);
    return src;
}

function find_host(str) {
    r = str.match(/^https?:\/\/([^\/]+)\/.*$/);
    if (r) {
        host = r[1]
        if (host.indexOf(':') > -1) {
            host = host.split(':').shift();
        }
        return host
    }
    return false;    
}

function is_mailto_url(str) {
    if (matches = str.match(/^mailto:(.*)$/)) {
        return matches[1]
    }
    return false;
}

function is_external_url(str) {
    host = find_host(str);
    if (host != location.hostname) {
        return true;
    }

    return false;
}

function strip_protocol(str) {
    matches = str.match(/^https?:\/\/(.*)/);
    if (matches) {
        return matches[1]
    }
    return str;
}


function swf_replacement(el_id, str, movie, width, height, varName) {
    var so = new SWFObject(movie, "", width, height, "9");
    so.addVariable(varName, str);
    so.addParam("scale", "noscale");
    so.addParam("menu", "false");
    so.addParam("align", "top");
    so.addParam("wmode", "transparent");
    so.write(el_id);    
}

function clear_error_messages() {
    els = $$('.fieldWithError')
    for(var i = 0; i < els.length; i++) {
        Element.removeClassName(els[i], 'fieldWithError');
    }
    
    msgs = $$('.fieldError')
    for(var i = 0; i < msgs.length; i++) {
        Element.remove(msgs[i]);
    }    
}

function display_form_error(el, message) {
    Element.addClassName(el, 'fieldWithError');
    msg = document.createElement('div');
    msg.className = 'fieldError';
    msg.appendChild(document.createTextNode(message));   
    el.parentNode.appendChild(msg);     
}
function ajax_submit(btn) {
    frm = Element.up(btn, 'form');
    options = {evalJSON: true, method: 'post', parameters: Form.serialize(frm), onSuccess: function(r) {
        clear_error_messages();
        Element.hide($('formMessageDisplay'));
        if (r.responseJSON.log) {
            log(r.responseText);
        }
        if (r.responseJSON.isError) {
            //el = $(r.responseJSON.data.field)
            
            for(i = 0; i < r.responseJSON.data.length; i++) {      
                el = frm[r.responseJSON.data[i].field];
                if (el.length > 0) { // assume its a radio/cb group
                    el = Element.up(el[0], 'div');
                }                
                display_form_error(el, r.responseJSON.data[i].message);
                if (i == 0) {
                    Element.scrollTo(el);
                }
            } 



        } else {
            $('formMessageDisplay').innerHTML = r.responseJSON.data.message
            Element.removeClassName($('formMessageDisplay'), 'error');            
            Element.addClassName($('formMessageDisplay'), 'success');
            Element.show($('formMessageDisplay'));
            Element.remove(btn);
        }
    }}
    r = new Ajax.Request(frm.action, options);
}

function tag(name, attrs, content) {
    el = document.createElement(name);
    for(k in attrs) {
        if (k == 'className') {
            k = 'class';
        }
        el.setAttribute(k, attrs[k]);
    }
    
    if (content) {
        t = txt(content);
        el.appendChild(t)
    }
    return el
}

function txt(str) {
    return document.createTextNode(str);
}

function FormBuilder(action, method) {
    this._form = null;
    
    this._init = function(action, method) {
        this._form = tag('form', {action: action, method: method});
    }
    
    this.add = function(name, value) {
        f = tag('input', {type: 'hidden', name: name, value: value})
        
        this._form.appendChild(f);
    }
    
    this.attach = function(cnt) {
        if (cnt == undefined) {
            cnt = $$('body')[0];
        }
        this._form.style.display = 'none';
        cnt.appendChild(this._form);
    }
    
    this.setAttribute = function(name, value) {
        this._form.setAttribute(name, value)
    }
    
    this.submit = function() {
        this._form.submit()
    }
    
    this._init(action, method)
}

function submit_data(data, url, method, target) {
    form = create_form(data, url, method, target)
    form.attach();
    form.submit();
}

function create_form(data, url, method, target) {
    if (method == undefined) {
        method = 'post'
    }
    form = new FormBuilder(url, method)
    if (target != undefined) {
        form.setAttribute('target', target);
    }
    for(k in data) {
        form.add(k, data[k])
    }    
    return form;
}

function paypal_show_cart() {
    data = {}
    data['cmd'] = '_cart';
    data['business'] = 'AKU9WFHMTDS98';
    data['display'] = '1';
    
    submit_data(data, 'https://www.paypal.com/cgi-bin/webscr', 'post', 'paypal')
}