
if(!Prototype) {
    throw("shopWise requires the Prototype JavaScript framework");
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        radioGroup = $(el).name;
        el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

Object.extend(Number.prototype, {
    numberFormat : function(decimals) {
        var pow, nStr, x, x1, x2;
        var dot = '';
        var rgx = /(\d+)(\d{3})/;
       
        decimals = decimals || 0;
        pow = Math.pow(10, decimals);
        nStr = (parseFloat(Math.round(this*pow)) / pow).toString();
        
        if(decimals > 0) {
            dot = '.';
        }
        
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? x[1] : '';
        
        while(x2.length < decimals) {
            x2 += '0';
        }
        x2 = dot + x2;

        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;

    }
});

var lang = {
    current : 'en',
    get: function(what) {
        what = what || 'en';
        var str = this[this.current] ? this[this.current][what] : '['+what+']';
        if(typeof arguments[1] != 'undefined') {
            str = str.replace(/%s/gi, arguments[1]);
        }
        return str;
    },

    en : {

        add_to_cart:        "Add to cart",
        remove_from_cart:   "Remove from cart",
        update_cart:        "Update cart",

        added_to_cart:      "%s added to cart",
        removed_from_cart:  "Removed from cart",
        updated_cart:       "Updated cart",

        adding_to_cart:      "Adding to cart",
        removing_from_cart:  "Removing from cart",
        updating_cart:       "Updating cart",

        update_quantity:     "Update Quantity",

        mand_fields:        "Mandatory fields are marked with a *",

        please_wait:        "Please wait...",

        no_items_in_cart:   "There are no items in your cart",
        minimum_quantity:   "Minimum Quantity",
        quantity_too_low:   "Sorry, this product has a minimum order quantity of %s",
        quantity_error:     "Quantity Error",
        invalid_quantity:   "You have entered an invalid quantity, please check your entry",

        maximum_quantity:   "Stock Level Exceeded",
        quantity_too_high:  "We currently only have %s of this item in stock. Please reduce the quantity to %s or less.<br/>If you require more, use the <strong>'Need More?'</strong> button.",
		
        information:		"Information",
        message:			"Message"
    
    },
    fr : {
        add_to_cart:        "Ajoutez \ufffd votre demande",
        remove_from_cart:   "Retirez votre demande",

        added_to_cart:      "Ajout\ufffd � votre demande",
        removed_from_cart:  "Retir\ufffd de votre demande",

        adding_to_cart:     "S'ajouter \ufffd votre demande",
        removing_from_cart: "\ufffdlimination de votre demande",

        mand_fields:        "Les champs marqu\ufffds * sont obligatoires",

        please_wait:        "Attendez svp...",

        no_items_in_cart:   "Il n'y a aucun article dans votre demande",
        minimum_quantity:   "Quantit\ufffd minimale",
        quantity_too_low:   "D\ufffdsol�, pour cet article, il faut une quantit� minimale de"
    }

}

var Shop = function() {

    var ret = {
        //- -----------------------------------------------------------------------------------
        //- General Conf... may bust this out into a separtate 'conf' object at some point...

        autoAdd: 			true,  //- Should items be:
        //- true: added to the cart on change of quantity
        //- false: only when the 'Add to cart' button it pressed

        zeroQtyAddsMinQty: 	true,


        fadeSpeed: 0.5,    //- Duration of the fade on the open/close of the lightbox and info pop ups

        //- icons:
        iconAdd:    '/shop/img/icon_add.png',
        iconRm:     '/shop/img/icon_remove_item.png',
        iconQty:    '../shop/img/icon_update_quantity.png',

        iconSpinner:'../images/ajax-loader.gif',
        iconClose:  '../images/close.png',

        showMessages: true,
        messageBoxDuration: 30,
        useAnimation: true,
        shadowWidth: 5,

        //- ----------------- Cart Methods --------------------------------

        copyDetails : function() {
            if($("same_add").checked) {
                $("order_shipname").value = $("order_title").value + " " + $("order_firstname").value + " " + $("order_lastname").value;
                $("order_shipstreetaddress").value = $("order_streetaddress").value;
                $("order_shipstreetaddress2").value = $("order_streetaddress2").value;
                $("order_shipstreetaddress3").value = $("order_streetaddress3").value;
                $("order_shipcity").value = $("order_city").value;
                $("order_shipcounty").value = $("order_county").value;
                $("order_shippostcode").value = $("order_postcode").value;
                $("order_shipcountry").value = $("order_country").value;
            } else {
                $("order_shipname").value = "";
                $("order_shipstreetaddress").value = "";
                $("order_shipstreetaddress2").value = "";
                $("order_shipstreetaddress3").value = "";
                $("order_shipcity").value = "";
                $("order_shipcounty").value = "";
                $("order_shippostcode").value = "";
                $("order_shipcountry").value = "";
            }
        },

        togCartSummary : function() {


            var cartSummary = $('cart-summary');
            var cartMini = $('mini-cart');
            var cartItems = $('cart-items');
            var cartShadow = $('mini-cart-shadow');

//            alert(cartMini);

            var shadowOffset = 5;
            if(!cartMini.visible()) {

//                alert(cartSummary.cumulativeOffset());
//                alert(cartSummary.offsetHeight);
                this.setCartPosition();
//                var n_t = (cartSummary.cumulativeOffset().top+cartSummary.offsetHeight);
//                var n_l = (cartSummary.cumulativeOffset().left+(parseInt(cartMini.getWidth()) - cartSummary.offsetWidth)*-1);
//
//                //console.log(n_t);
//                //toporig = parseInt(cartMini.getStyle('top'));
//                //if(!toporig) toporig = 0;
//
//                var scrolloffset = document.viewport.getScrollOffsets().top;
//
//                cartMini.setStyle({
//                    'left':n_l+'px'
//                });
//                //                if(cartShadow) cartShadow.setStyle({'left':(n_l+shadowOffset)+'px'});
//
//                if(scrolloffset > n_t) {
//                    cartMini.setStyle({
//                        'top':scrolloffset+'px'
//                    });
//                //                    if(cartShadow) cartShadow.setStyle({'top':(scrolloffset+shadowOffset)+'px'});
//                }
//                else {
//                    cartMini.setStyle({
//                        'top':n_t+'px'
//                    });
//                //                    if(cartShadow) cartShadow.setStyle({'top':(n_t+shadowOffset)+'px'});
//                }

                Event.observe(window, 'scroll', function() {
                    //var cartMini = $('mini-cart');
                    var n_t = (cartSummary.cumulativeOffset().top+cartSummary.offsetHeight);

                    var cartShadow = $('mini-cart-shadow');
                    var scrolloffset = document.viewport.getScrollOffsets().top;

                    if(scrolloffset > n_t) {
                        cartMini.setStyle({
                            'top':scrolloffset+'px'
                        });
                        if(cartShadow) {
                            cartShadow.setStyle({
                                'top':(scrolloffset+shadowOffset)+'px'
                            });
                        }
                    }
                    else {
                        cartMini.setStyle({
                            'top':n_t+'px'
                        });
                        if(cartShadow) {
                            cartShadow.setStyle({
                                'top':(n_t+shadowOffset)+'px'
                            });
                        }
                    }
                });

                cartMini.setStyle({
                    visibility:'hidden'
                });
                cartMini.show();

                this.syncShadow();
                //                cartSize = cartMini.getDimensions();
                //                if(cartShadow) cartShadow.setStyle({height:cartSize['height']+'px',width:cartSize['width']+'px'});
                //                console.log(cartSize);
                
                if(cartItems.scrollHeight <= cartItems.offsetHeight) {
                //                    cartItems.setStyle({
                //                        padding:'7px'
                //                    });
                }
                else {
                    cartItems.scrollTop = cartItems.scrollHeight - cartItems.offsetHeight
                }
                cartMini.hide();
                cartMini.setStyle({
                    visibility:''
                });

            }
            else {
                if(cartItems.scrollHeight > cartItems.offsetHeight) {
                    $('cart-items').setStyle({
                        overflow:'',
                        padding:''
                    });

                }
                this.togTimeout = null;
            }

            if(navigator.userAgent.indexOf('Safari/4') == -1) {
                Effect.toggle(cartMini, 'slide', {
                    duration: 0.5,
                    afterFinish: function(ef) {
                        //console.log(ef);
                        if(cartMini.visible() && cartItems.scrollHeight > cartItems.offsetHeight) {
                            cartItems.setStyle({
                                overflow:'auto',
                                padding:'7px'
                            });
                            cartItems.scrollTop = cartItems.scrollHeight - cartItems.offsetHeight;
                        }
                    },
                    queue:'end'
                });
                //                cartShadow.toggle();
//                if(cartShadow) {
//                    Effect.toggle(cartShadow, 'slide', {
//                        duration: 0.5
//                    });
//                }
            }
            else {
                cartMini.toggle();
//                if(cartShadow) {
//                    cartShadow.toggle();
//                }
            }

        },
        setCartPosition: function() {
            var cartSummary = $('cart-summary');
            var cartMini = $('mini-cart');
            
            var n_t = (cartSummary.cumulativeOffset().top+cartSummary.offsetHeight);
            var n_l = (cartSummary.cumulativeOffset().left+(parseInt(cartMini.getWidth()) - cartSummary.offsetWidth)*-1);

            var scrolloffset = document.viewport.getScrollOffsets().top;

            cartMini.setStyle({
                'left':(n_l+this.shadowWidth)+'px'
            });
            if(scrolloffset > n_t) {
                cartMini.setStyle({
                    'top':scrolloffset+'px'
                });
            }
            else {
                cartMini.setStyle({
                    'top':n_t+'px'
                });
            }
        },
        syncShadow: function() {
            if($('mini-cart-shadow')) {
                var cartShadow = $('mini-cart-shadow'),
                cartSize = $('mini-cart-inner').getDimensions();
                if(cartShadow) {
                    cartShadow.setStyle({
                        height:cartSize['height']+'px',
                        width:cartSize['width']+'px'
                    });
                }
            }
        },
        isInCart: function(id) {
            if($("cart-link-"+id).rel == "rm") {
                return true;
            } else {
                return false;
            }
        },
	
        addToCart : function(event, itemId, min_qty) {

            //- get number to add
            var qty = 0;
            var page_qty_el = $$('#row'+itemId+ ' input.quantity');
            if(page_qty_el[0]) {
                qty = page_qty_el[0].value;
            }

            qty = this.validateQuantity(qty, min_qty, page_qty_el[0]);
            if(qty === false) {
                return;
            }

            /*if(isNaN(qty)) {
                var page_qty_el; // = $$('#row'+itemId+ ' input.quantity');
                var cart_qty_el = $$('#cartitem'+itemId+ ' input.quantity');
                var qty_el;

                if(cart_qty_el[0] && cart_qty_el[0].hasFocus) {
                    qty_el = cart_qty_el[0];
                }
                else if(page_qty_el[0]) {
                    qty_el = page_qty_el[0];
                }

                if(qty_el) {
                    this.showMessage({
                            title:    lang.get('quantity_error'),
                            msg:      lang.get('invalid_quantity'),
                            duration: 0,
                            position: qty_el
                    });
                }
                return;
                //alert('NAN');
            }
            else {
                this.hideMessage(lang.get('quantity_error'));
            }*/

            //qty = Math.max(1, parseInt(qty));
            qty = Math.max(this.zeroQtyAddsMinQty ? 1 : 0, parseInt(qty));

            if(this.togTimeout) {
                window.clearTimeout(this.togTimeout);
                this.togTimeout = window.setTimeout(function() {
                    this.togCartSummary();
                }.bind(this), 3000);
            }

            this.loadingTimeout = window.setTimeout(function() {
                this.showMessage({
                    title:lang.get('adding_to_cart'),
                    msg:lang.get('please_wait'),
                    duration:0,
                    position:$('cart-link-'+itemId)
                });
            }.bind(this), 500);




            new Ajax.Request( '../shop/xhr_cart.php', {
                method:     'post',
                parameters: 'mode=add&product_id='+itemId + '&qty=' + qty,
                onSuccess: function(t) {
                    var json = t.responseText.evalJSON();

                    window.clearTimeout(this.loadingTimeout);
                    this.loadingTimeout = null;
                    window.setTimeout(function() {
                        this.hideMessage( lang.get('adding_to_cart') );
                    }.bind(this), 500);

                    //if(!$('mini-cart').visible()) {
                    //    this.togCartSummary();
                    //}

                    //this.togTimeout = window.setTimeout('this.togCartSummary()', 3000);
                    this.updatePage(json);

                }.bind(this)
            });

        },

        rmFromCart: function(event, itemId, callback) {
            //if(confirm("Are you sure you want to remove this item from your cart?")) {
            this.loadingTimeout = window.setTimeout(function() {
                this.showMessage({
                    title:lang.get('removing_from_cart'),
                    msg:lang.get('please_wait'),
                    duration:0,
                    position: event ? Event.element(event) : $('cart-link-'+itemId)
                });
            }.bind(this), 500);

            this._rmFromCart(itemId, callback);
        //}
        },
        _rmFromCart: function(itemId, callback) {
            new Ajax.Request( '../shop/xhr_cart.php', {
                method:     'POST',
                parameters: 'mode=rm&product_id='+itemId,
                onSuccess: function(t) {
                    window.clearTimeout(this.loadingTimeout);
                    this.loadingTimeout = null;
                    window.setTimeout(function() {
                        this.hideMessage(lang.get('removing_from_cart'));
                    }.bind(this), 500);

                    var json = t.responseText.evalJSON();
                    this.updatePage(json,"rm");
                    $("delegatesTable-"+itemId).previous("h3").remove();
                    $("delegatesTable-"+itemId).remove();
                    if($('disabledPaymentMethods') && json.webOnly == 0) {
                        $('disabledPaymentMethods').removeClassName("disabled");
                        $('radios-payment-method').onclick = CandF.savePaymentMethod.bind(CandF);
                        $('radios-payment-method-2').onclick = CandF.savePaymentMethod.bind(CandF);
                    }

                    if(callback && typeof callback == 'function') {
                        callback();
                    }
                }.bind(this)
            });
        },

        validateQuantity: function(qty, min_qty, qty_el) {
            if(isNaN(qty)) {
                if(qty_el) {
                    this.showMessage({
                        title:    lang.get('quantity_error'),
                        msg:      lang.get('invalid_quantity'),
                        duration: 0,
                        position: qty_el
                    });
                }
                return false;
            }
            else {
                this.hideMessage(lang.get('quantity_error'));
            }

            var current_qty;
            if(qty_el){
                current_qty = parseInt(qty_el.getValue() ? qty_el.getValue() : 0);
            }
            else {
                current_qty = 0;
            }
            //            console.log('passed:'+qty +', min_qty:'+min_qty+', current:'+current_qty);

            if(typeof qty == 'string') {
                if(qty.substring(0,1) == '+') {
                    qty = current_qty + parseInt(qty.substring(1));
                    if(qty < 0) {
                        qty = 0;
                    }
                }
                else if(qty.substring(0,1) == '-') {
                    if(current_qty == 0) return false;
                    qty = current_qty - parseInt(qty.substring(1));
                    if(qty < 0) {
                        qty = 0;
                    }
                }
            }

            if(Math.floor(qty / min_qty) != qty / min_qty) {
                var	multiplier = Math.ceil(qty / min_qty);
                qty = min_qty * multiplier;
            }

            //qty = qty.replace(/[A-Za-z]+/, '');

            qty = Math.floor(qty);

            //            console.log(qty);

            return qty;

        },

        updateQuantity: function(event, itemId, qty, min_qty) {
            if(qty === '') {
                return;
            }

            //- only send request if quantity is value
            if(!min_qty) min_qty = 1;


            var page_qty_el = $$('#row'+itemId+ ' input.quantity');
            var cart_qty_el = $$('#cartitem'+itemId+ ' input.quantity');
            var qty_el;
            if(cart_qty_el[0] && cart_qty_el[0].hasFocus) {
                qty_el = cart_qty_el[0];
            }
            else if(page_qty_el[0]) {
                qty_el = page_qty_el[0];
            }
            else if(cart_qty_el[0]) {
                qty_el = cart_qty_el[0];
            }

            qty = this.validateQuantity(qty, min_qty, qty_el);
            if(qty === false) {
                return;
            }


            if(qty == 0 || min_qty <= qty) {

                var pos_el = event ? Event.element(event) : $('cart-link-'+itemId);

                this.loadingTimeout = window.setTimeout(function() {
                    this.showMessage({
                        title:lang.get('updating_cart'),
                        msg:lang.get('please_wait'),
                        duration:0,
                        position:pos_el
                    });
                }.bind(this), 500);



                new Ajax.Request('../shop/xhr_cart.php', {
                    method:     'POST',
                    parameters: 'mode=upd&product_id='+itemId+'&qty='+qty,
                    onSuccess: function(t) {
                        window.clearTimeout(this.loadingTimeout);
                        this.loadingTimeout = null;
                        window.setTimeout(function() {
                            this.hideMessage(lang.get('updating_cart'));
                        }.bind(this), 500);

                        var json = t.responseText.evalJSON();
                        json.messageAnchor = pos_el;
                        this.updatePage(json);
//                        console.log(qty+" "+itemId);
                        var table = "<tr><td>&nbsp;</td><td>Name</td><td>Job title</td><td>Email</td><td>Dietary Requirements</td></tr>";
                        for(var i = 1; i <= qty; i++) {
                            table += "<tr>";
                            table += "<td width=\"100\">#"+i+"</td>";
							table += "<td><select name=\"delegates["+itemId+"]["+i+"][title]\"><option value=\"\"></option><option value=\"Mr\">Mr</option><option value=\"Mrs\">Mrs</option><option value=\"Miss\">Miss</option><option value=\"Ms\">Ms</option></select></td>";
                            table += "<td><input type=\"text\" name=\"delegates["+itemId+"]["+i+"][name]\" value=\"\" style=\"width:160px\" /></td>";
                            table += "<td><input type=\"text\" name=\"delegates["+itemId+"]["+i+"][jobtitle]\" value=\"\" style=\"width:160px\"  /></td>";
                            table += "<td><input type=\"text\" name=\"delegates["+itemId+"]["+i+"][email]\" value=\"\" style=\"width:160px\"  /></td>";
                            table += "<td><input type=\"text\" name=\"delegates["+itemId+"]["+i+"][dietry]\" value=\"\" style=\"width:160px\"  /></td>";
                            table += "</tr>";
                        }
                        $("delegatesTable-"+itemId).update(table);
                        CandF.saveDelegatesToOrder();
                    }.bind(this)
                });
            }
            else {

                if(qty_el) {

                    //var qty_el = $$('#cartitem'+itemId+ ' input.quantity');

                    this.showMessage({
                        title:    lang.get('minimum_quantity'),
                        msg:      lang.get('quantity_too_low', min_qty.numberFormat(0)),
                        duration: 0,
                        position: qty_el
                    });
                }
            }
        },

        reColourRows: function(id) {
            //            var el = $(id),
            //            j = 0,
            //            childs = el.down("form") ? el.down("form").childElements() : el.childElements();
            //            childs.each(function(c) {
            //                if(c.nodeName=='DIV' && /cartitem.+/.test(c.id)) {
            //                    j&1 ? c.removeClassName('alt-row').style.backgroundColor = ''
            //                    : c.addClassName('alt-row').style.backgroundColor = '';
            //                    j++;
            //                }
            //            });
            $$('.cart-item').each(function(el, i) {
                if(el.id=='no-items') return;
                //console.log(el);
                if(i+1&1) el.removeClassName('alt-row').style.backgroundColor = '';
                else el.addClassName('alt-row').style.backgroundColor = '';
            });

        },

        updatePage: function(details, mode) {

            //- Intelligent (ha!) page update
            
            var messageAnchor;
            var page_qty_el = $$('#row'+details['itemId']+ ' input.quantity');
            var cart_qty_el = $$('#cartitem'+details['itemId']+ ' input.quantity');

            if(details.messageAnchor) {
                messageAnchor = details.messageAnchor
            }
            else if(cart_qty_el[0] && cart_qty_el[0].hasFocus) {
                messageAnchor = cart_qty_el[0];
            }
            else if(page_qty_el[0]) {
                messageAnchor = page_qty_el[0];
            }
            else if(cart_qty_el[0]) {
                messageAnchor = cart_qty_el[0];
            }
            else {
                messageAnchor = 'center'
            }

            //- if adding more than the MaxQuantity, do nothing but display error
            if(typeof details['itemMaxQuantity'] == 'number' && details['itemMaxQuantity'] != 0) {

                if(details['itemQuantity'] > details['itemMaxQuantity']) {

                    this.showMessage({
                        title:    lang.get('maximum_quantity'),
                        msg:      lang.get('quantity_too_high', details['itemMaxQuantity'].numberFormat(0)),
                        duration: 0,
                        position: messageAnchor
                    });

                    return;

                }
                else {
                    this.hideMessage(lang.get('maximum_quantity'));
                }

            }


            //- when a quantity is updated, ensure any quantity inputs for that item are updated
            if(typeof details['itemQuantity'] == 'number') {
                //- requirements for a match:
                //-    class of 'quantity'
                //-    attr 'id' of contains item ID

                $$('input.quantity-'+details['itemId']).each(function(el,ind) {
                    if(!el.hasFocus) {
                        el.value = details['itemQuantity'];
                    }
                });
            }


            //- Modify the 'add to cart' icon of the item as required
            //            if(details['itemQuantity']) {
            //                this.changeIcon('remove', details );
            //            }
            //            else {
            //                this.changeIcon('add', details );
            //            }
            //- Modify the 'add to cart' icon of the item as required
            if(details['itemQuantity'] && details['itemQuantity'] >= details['itemMinQuantity']) { //} && details['htmlFragment']) {
                this.changeIcon('remove', details );
            }
            else {
                this.changeIcon('add', details );
            }

            //var icon = $('cart-icon-' + details['itemId']);
            //if(icon) {
            //    var new_icon_src   = this.autoAdd ? this.iconRm                  : this.iconQty;
            //    var new_title_text = this.autoAdd ? lang.get('remove_from_cart') : lang.get('update_quantity');

            //     icon.src   = details['itemQuantity'] ? new_icon_src   : this.iconAdd;
            //     icon.title = details['itemQuantity'] ? new_title_text : lang.get('add_to_cart');
            // }
            var dalink = $('cart-link-' + details['itemId']);
            if(dalink) {
                //- pop message on remove
                if(!details['itemQuantity'] && details['mode'] != 'add') {
                    this.showMessage({
                        title:    lang.get('message'), //lang.get('removed_from_cart'),
                        msg:      lang.get('removed_from_cart'),
                        duration: 1.5,
                        position: dalink
                    });
                }
                //dalink.itemId = details['itemId'];
                dalink.itemMinQuantity = details['itemMinQuantity'];

            //var new_onclick_func = this.autoAdd
            //                     ? function(e) { products.rmFromCart(this.itemId); }
            //                     : function(e) {
            //                            var _qty = $$('#row' + this.itemId + ' input.quantity')[0].value;
            //                            //_qty = _qty[0] ? _qty[0].value : 0;
            //                            products.updateQuantity(this.itemId, _qty, this.itemMinQuantity);
            //                       }

            //dalink.onclick = details['itemQuantity']
            //            ? new_onclick_func
            //            : function(e) { products.addToCart(this.itemId); }

            //if(!icon) {
            //    dalink.update(details['itemQuantity'] ? lang.get('remove_from_cart') : lang.get('add_to_cart'));
            //}
            }

            //-if zero quantity, remove any cart rows associated with that item
            if(typeof details['itemQuantity'] == 'number' && details['itemQuantity'] == 0 && details['mode'] != 'add') {

                var el = $('cartitem' + details['itemId']);

                if(el) {
                    //- pretty fade if row is visible
                    if(!$('mini-cart') || $('mini-cart').visible()) {


                        var afterfade = function() {
                            el.remove();
                            if($('full-cart')) {
                                this.reColourRows('full-cart');
                            }
                            else if($('cart-items')) {
                                this.reColourRows('cart-items');
                            }
                            if(details['cartCount']==0 && $('no-items')) {
                                $('no-items').show();
                                if($('terms')) $('terms').hide();
                            }
                            this.syncShadow();
                            
                        }.bind(this);

                        if(this.useAnimation){
                            new Effect.Fade(el, {
                                duration:1,
                                afterFinish: afterfade
                            });
                        }
                        else {
                            el.hide();
                            afterfade();

                        //                        el.remove();
                        //                        if($('full-cart')) {
                        //                        products.reColourRows('full-cart');
                        //                        }
                        //                        else if($('cart-items')) {
                        //                        products.reColourRows('cart-items');
                        //                        }
                        //                        console.log("count:"+details['cartCount']);
                        //                        if(details['cartCount']==0 && $('no-items')) {
                        //                        console.log("show");
                        //                        $('no-items').show();
                        //                        }
                        }
                    }
                    //- else just DESTROY!! Muahaha
                    else {
                        el.remove();
                        if($('full-cart')) {
                            this.reColourRows('full-cart');
                        }
                    }
                }
            }
            else if(typeof details['itemMinQuantity'] == 'number') {
                if(details['itemQuantity'] < details['itemMinQuantity']) {
                    //var qty_el = $$('#cartitem'+details['itemId']+ ' input.quantity');

                    this.showMessage({
                        title:    lang.get('minimum_quantity'),
                        msg:      lang.get('quantity_too_low', details['itemMinQuantity'].numberFormat(0)),
                        duration: 0,
                        position: messageAnchor
                    });
                }
                else if(!details['htmlFragment']) {
                    this.hideMessage(lang.get('minimum_quantity'));
                }
            }




            //- Update item sub total in mini-cart
            if($('cartitemtotal'+details['itemId'])) {
                $('cartitemtotal'+details['itemId']).update(details['itemTotal']);
            }
            if($('cartitemdiscount'+details['itemId'])) {
                if(details.itemDiscount) {
                    $('cartitemdiscount'+details['itemId']).update((details.itemDiscount*100) + '%');
                }
                else {
                    $('cartitemdiscount'+details['itemId']).update('<span style="color:#aaaaaa">n/a</span>');
                }
            }


            //- Update total quantity
            if($('myCartCount')) {
                $('myCartCount').update(details['cartCount'] + ' item' + (details['cartCount']==1?'':'s'));
            }

            //- Update cart total cost
            if($('myCartSum')) {
                $('myCartSum').update(parseFloat(details['totalCost']).numberFormat(2));
            }
			
            //- Update cart vat cost
            if($('myCartVat') && details['totalVat']) {
                $('myCartVat').update(parseFloat(details['totalVat']).numberFormat(2));
            }
			
			//- Update cart grand total
            if($('myGrandTotal') && details['totalGrand']) {
                $('myGrandTotal').update(parseFloat(details['totalGrand']).numberFormat(2));
            }

            if($('cartDeliveryCost')) {
                $('cartDeliveryCost').update(details['deliveryCost']);
            }
            if (details['htmlFragment']) {
                window.setTimeout(function() {

                    if($('cart-link-' + details['itemId'])) {
                        messageAnchor = $('cart-link-' + details['itemId']);
                    }

                    //this.hideMessage(lang.get('adding_to_cart'))
                    this.showMessage({
                        title: lang.get('message'),//lang.get('added_to_cart'),
                        msg: lang.get('added_to_cart', details['itemQuantity']),
                        duration: 3,
                        position: messageAnchor
                    });
                }.bind(this), 100);
            }

            //- if have we have a cart fragment, add it to the mini-cart
            if(details['htmlFragment'] && $('cart-items')) {

                if($('no-items')) {
                    $('no-items').hide();
                }

                //- drop down the cart
                if(!$('mini-cart').visible()) {
                    this.togCartSummary();
                    this.togTimeout = window.setTimeout(function() {
                        this.togCartSummary()
                    }.bind(this), 3000);

                }
                else {
                    if(this.togTimeout) {
                        window.clearTimeout(this.togTimeout);
                        this.togTimeout = window.setTimeout(function() {
                            this.togCartSummary();
                        }.bind(this), 3000);
                    }
                }


                $('cart-items').insert(details['htmlFragment']);
                
                this.syncShadow();

                var el = $('cartitem'+details['itemId']);
                if(el) {
                    if($('mini-cart').visible()) {
                        var cartItems = $('cart-items');
                        if(cartItems.scrollHeight > cartItems.offsetHeight) {
                            cartItems.setStyle({
                                overflow:'auto',
                                padding:'7px'
                            });
                            cartItems.scrollTop = cartItems.scrollHeight - cartItems.offsetHeight
                        }
                        //el.hide();
                        //new Effect.Appear(el, {duration:1});
                        new Effect.Highlight(el, {
                            duration:   1,
                            startcolor: '#ffcc00',
                            //                            endcolor:   '#ffffff', //b3e8f3',
                            queue:      'end',
                            afterFinish: function(o) {
                                //- sometimes the cart row gets a rouge minus margin... bizarre
                                //- remove this
                                o.element.style.margin = '0';
                                this.reColourRows('cart-items');
                                

                                var qtyid = o.element.id.replace(/cartitem/, 'qty');
                                var cartqty = $(qtyid);
                                if(cartqty) {
                                    cartqty.hasFocus = false;
                                    cartqty.observe('focus', function(event) {
                                        Event.element(event).hasFocus = true;
                                    });
                                    cartqty.observe('blur', function(event) {
                                        Event.element(event).hasFocus = false;
                                    });
                                }
                            }.bind(this)
                        });
                    }
                }
            }
        },

        /*
         * type: add, update, remove
         * details: object containing item details - details['itemId '] is required
         */

        changeIcon : function(type, details) {
            var new_src, new_text, new_func, new_rel;

            var icon = $('cart-icon-' + details['itemId']);
            var dalink = $('cart-link-' + details['itemId']);

            //            console.log(type);
            //            console.log(details);

            if(type == 'update') {
                new_text = lang.get('update_quantity');
                new_src  = this.iconQty;
                new_rel = 'upd';
                new_func = function(e) {
                    var el = Event.element(e);
                    if(el.nodeName != 'A') {
                        el = el.up('a');
                    }
                    var _qty = $$('#row' + el.itemId + ' input.quantity')[0].value;
                    this.updateQuantity(e, el.itemId, _qty, el.itemMinQuantity);
                }.bindAsEventListener(this);
            }
            else if(type == 'add') {
                new_text = lang.get('add_to_cart');
                new_src  = this.iconAdd;
                new_func = function(e) {
                    var el = Event.element(e);
                    if(el.nodeName != 'A') {
                        el = el.up('a');
                    }
                    this.addToCart(e, el.itemId, el.itemMinQuantity);
                }.bindAsEventListener(this);
            }
            else if(type == 'remove') {
                new_text = lang.get('remove_from_cart');
                new_src  = this.iconRm;
                new_func = function(e) {
                    var el = Event.element(e);
                    if(el.nodeName != 'A') {
                        el = el.up('a');
                    }
                    this.rmFromCart(e, el.itemId);
                }.bindAsEventListener(this);
            }

            if(icon) {
                icon.src = new_src
            }

            if(dalink) {
                if(!icon) dalink.update(new_text);

                dalink.iconType = type;
                dalink.itemId = details['itemId'];
                dalink.itemMinQuantity = details['itemMinQuantity'] || 1;
                dalink.title = new_text;
                dalink.setAttribute('rel', new_rel);
                dalink.onclick = new_func;

            }

        },
        iconType : function(itemId) {
            var dalink = $('cart-link-' + itemId);
            var ret;
            if(!dalink) return ret;
            if(dalink.iconType) {
                ret = dalink.iconType;
            }
            else {
                if(dalink.title.indexOf('Remove') > -1) {
                    ret = 'remove';
                }
                else if(dalink.title.indexOf('Add') > -1) {
                    ret = 'add';
                }
                else if(dalink.title.indexOf('Update') > -1) {
                    ret = 'update';
                }
            }
            return ret;
        },

        //- ----------------- Favourites Methods --------------------------------

        addToFav : function(prd_id, obj) {

            //e.stop();
            var icon = obj.getElementsByTagName('IMG')[0];

            new Ajax.Updater( 'myFavCount', '../shop/xhr_fav.php', {
                method:     'post',
                parameters: 'mode=add&product_id='+prd_id,
                onComplete: function() {
                    icon.src = '../images/icon_star_block.png'
                    icon.title = 'Remove from My Favourites';
                    obj.prd_id = prd_id;
                    obj.onclick = function(e) {
                        this.rmFav(Event.element(e).prd_id, this);
                        return false;
                    }.bindAsEventListener(this);

                    new Effect.Highlight($('myFavCount').up(), {
                        restorecolor:'#ffffff'
                    });
                    this.showMessage({
                        title:      'Item Added',
                        msg:        'Added to your favourites list!',
                        duration:   1.5,
                        position:   obj
                    });
                }.bind(this)
            });
        },

        rmFav : function(itemId, obj) {

            //e.stop();
            var icon = obj.getElementsByTagName('IMG')[0];

            new Ajax.Updater( 'myFavCount', '../shop/xhr_fav.php', {
                method:     'post',
                parameters: 'mode=rm&product_id='+itemId,
                onComplete: function() {
                    icon.src = '../images/icon_star_outline.png'
                    icon.title = "Add to My Favourites";
                    obj.itemId = itemId;
                    obj.onclick = function(e) {
                        this.addToFav(Event.element(e).itemId, this);
                        return false;
                    }.bindAsEventListener(this);

                    new Effect.Highlight($($('myFavCount').parentNode), {
                        restorecolor:'#ffffff'
                    });

                    if($('myproduct-'+itemId)) {

                        if(Prototype.Browser.IE) {
                            var nodes = $('myproduct-'+itemId).childNodes;
                            for(var k=0; k<nodes.length; k++) {
                                if(nodes[k].nodeName == 'TD') {
                                    new Effect.Fade(nodes[k], {
                                        duration: 1.5
                                    });
                                }
                            }
                            window.setTimeout('$(\'myproduct-'+itemId+'\').remove();location.reload();', 1750);
                        }
                        else {
                            new Effect.Fade($('myproduct-'+itemId),
                            {
                                duration: 1.5,
                                afterFinish: function() {
                                    $('myproduct-'+itemId).remove();
                                    location.reload();
                                }
                            });

                        }
                    }
                    else {
                        this.showMessage({
                            title:  'Item Removed',
                            msg:    'Removed from your favourites list!',
                            duration:1.5,
                            position:   obj
                        });
                    }
                }.bind(this)
            }
            );

        },


        /* --------------------------- Currency methods ------------------------*/

        currency: {
            menuId: 'currency-selector-menu',
            togMenu: function () {
                $(this.menuId).toggle()
            }
        },
        changeCurrency : function(currency) {
            new Ajax.Request('../shop/xhr_cart.php', {
                method:     'POST',
                parameters: 'currency='+currency+'&mode=changeCurrency',
                onSuccess: function(t) {
                    this.updateMiniCart();

                }.bind(this)
            });
        },

        /* ------------------- Tooltop Popup Methods and properties ------------*/

        boxId : 'messageBox',
        showMessageTO : null,
        showMessage : function(options) {

            //check to see if messages are allowed
            if(this.showMessages == false) {
                return;
            }

            if(typeof options == 'string') {
                options = {
                    msg:options
                }
            }

            options = Object.extend({
                title:      'Message Alert',
                msg:        '<em>No message given</em>',
                duration:   5,
                position:   'center'
            }, options || {});

            /*options.title    = options.title    || 'Message Alert';
            options.msg      = options.msg      || '<em>No message given</em>';
            options.duration = options.duration || 0;
            options.position = options.position || 'center';*/

            var boxTimeout = function() {}
            if(options.duration) {
                boxTimeout = function() {
                    this.showMessageTO = setTimeout(function() {
                        this.hideMessage(options.title);
                    }.bind(this), options.duration*1000);
                }.bind(this);
            }
            //html = '<div><h3 id="'+this.boxId+'Title">'+options.title+'</h3><p>'+options.msg+'</p></div>';
            //box_id = 'messageBox';
            /*if(!box) {
                return;
                box = new Element('DIV', {id:this.boxId, style:'display:none'});
                document.body.appendChild(box);
            }*/
            //if(html) box.update(html);


            var box = $(this.boxId);
            $('messageTitle').update('<img src="/shop/img/close_small.png" id="messageClose" style="width:10px;height:10px" onclick="Shop.hideMessage()" />'
                + options.title);
            $('messageText').update(options.msg);


            this.positionBox(box, {
                position: options.position
            });

            if(!box.visible()) {
                if(Prototype.Browser.IE) {
                    box.show();
                    boxTimeout();
                }
                else {
                    new Effect.Appear(box, {
                        duration:0.3,
                        afterFinish:boxTimeout
                    });
                }
            }
            else {
                //- if bubble already visible, reset the timeout
                if(this.showMessageTO) {
                    window.clearTimeout(this.showMessageTO);
                    this.showMessageTO = null;
                }
                boxTimeout();
            }

        /*Event.observe(window, 'scroll', function() {
                if($(products.boxId).visible()) products.centerBox($(products.boxId));
            });*/


        },
        hideMessage : function(title) {
            //- if title is set only hide if the message titles matches

            //console.log('hideMessage fired');
            if($('messageTitle') && title) {

                var current_title = $('messageTitle').innerHTML.stripTags();
                //console.log('current: \'' + current_title + '\' - passed: \'' + title+ '\'');
                if(title != current_title) {
                    //console.log('hide request ignored');
                    return;
                }
            }

            if(this.showMessageTO) {
                window.clearTimeout(this.showMessageTO);
                this.showMessageTO = null;
            }
            if($(this.boxId) && $(this.boxId).visible()) {
                if(Prototype.Browser.IE) {
                    $(this.boxId).hide();
                }
                else {
                    new Effect.Fade(this.boxId, {
                        duration:0.3
                    });
                }
            }
        },
        positionBox : function(o, options) {
            options = Object.extend({
                position: 'center',
                postionElement: null
            }, options || {});

            var offs = document.viewport.getScrollOffsets();

            if(options.position == 'center') {
                if(!o.visible()) o.show();
                var new_top  = Math.round(document.viewport.getHeight() / 2);
                new_top -= Math.round(parseInt(o.getStyle('height')) / 2);
                new_top += offs['top'];
                var new_left = Math.round(document.viewport.getWidth() / 2);
                new_left -= Math.round(parseInt(o.getStyle('width')) / 2);
                if(o.visible()) o.hide();

            }
            else if(Object.isElement(options.position)) {

                var el = $(options.position);
                var o_w = o.getWidth();

                new_top = el.cumulativeOffset().top - (o.getHeight() - 5);
                new_left = (el.cumulativeOffset().left+Math.round(el.getWidth()/2)) + 5;
                //new_left = new_left - Math.round(o_w/2);
                new_left = new_left - (o_w - 35);

            //console.log('newtop:'+new_top+'   newleft:'+new_+left);
            //box.setStyle({'top':newtop+'px','left':newleft+'px'});
            }

            //if(console) console.log('top:'+offs['top']+', left:'+offs['left']);

            o.setStyle({
                top:new_top+'px',
                left:new_left+'px'
            });
        },
        updateMiniCart : function() {
            //$$("#cart-items .cart-item").each(function(e){
                //if(e.id != "no-items") {
                //    e.remove();
                //}

                new Ajax.Request('../shop/xhr_cart.php', {
                    method:     'POST',
                    parameters: 'mode=getNewMiniCartItems',
                    onSuccess: function(t) {
                        $("mini-cart").remove();
                        if($("mini-cart-shadow")) $("mini-cart-shadow").remove();

                        $(document.body).insert(t.responseText);
//                        var initCart = function() {

//                            var div = new Element('div',{id:'mini-cart'});
//                            alert(t.responseText);

//                            div.update(t.responseText);


//                            alert($("mini-cart"))

//                            $("mini-cart").setStyle({
//                                overflow: 'hidden',
//                                left: '838px',
//                                top: '201px'
//                            });

                            this.setCartPosition();
                            this.syncShadow();
                            
                            $("mini-cart").show();
                            if($("mini-cart-shadow")) $("mini-cart-shadow").show();

                            
                            $$('#currency-selector a').invoke("observe","click",function(e) {
                                if(e.element().readAttribute("alt") == null) {
                                    var cur = e.element().readAttribute("title");
                                } else {
                                    var cur = e.element().readAttribute("alt");
                                }
                                this.changeCurrency(cur);
                            }.bind(this));
//                        }

//                        initCart.defer(100, this);


                    }.bind(this)

                    
                });

            //});
        }
    }

    return ret;
}();

var Checkout = function () {

    var ret = {
        iconSpinner: '../shop/img/spinner_16px.gif',

        savePersonalDetails: function(nextpage) {

            //validation
            var valid = 1;
            var output = "";
            var requiredFields = "order_title,order_firstname,order_lastname,order_company,order_job_title,order_email,order_phone,order_streetaddress,order_city,order_county,order_postcode,order_country,order_shipname,order_shipstreetaddress,order_shipcity,order_shipcounty,order_shippostcode,order_shipcountry,order_vat_status";
            requiredFields = requiredFields.split(",");
			
			var emailFields = "order_email";
            emailFields = emailFields.split(",");

            $$("#details-form input,#details-form select,#order_vat_status").invoke("removeClassName","invalidField");
			$$(".validationText").invoke("remove");

            for(var i = 0; i < requiredFields.length; i++) {
                output = output+requiredFields[i]+":"+$(requiredFields[i]).value+"\n";
                if($(requiredFields[i]).value == "") {
                    $(requiredFields[i]).addClassName("invalidField");
                    valid = 0;
                }
            }
			
			for(var i = 0; i < emailFields.length; i++) {
                output = output+emailFields[i]+":"+$(emailFields[i]).value+"\n";
                if(!$(emailFields[i]).value.match(/^[^@]*@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/) && $(emailFields[i]).value != "") {
                    $(emailFields[i]).addClassName("invalidField");
					$(emailFields[i]).insert({'after':'<div class="validationText">Input valid email address</div>'});
                    valid = 0;
                }
            }
            
            if(valid == 1) { 
                $("panel-x-details").down("h2").update("Your Details");
                $('details-form').request({
                   parameters:  {mode:'saveDetails'}
                });
                tabs.change('panel-x-delegates', $('tab-x-delegates'));
            } else {
                $("panel-x-details").down("h2").update("Your Details - <span style='color:#ff585f'>Please fill in fields marked red</span>");
            }
        },

        setDelivery: function( delivery_id ) {

            $$('.delivery-method-rows').each(function(el) {

                el.setStyle({
                    backgroundColor:'transparent'
                });

            });
            $('delivery-method-row-'+delivery_id).setStyle({
                backgroundColor:'#ffffcc'
            });

            new Ajax.Request('../shop/xhr_checkout.php', {
                method: 'post',
                parameters: 'mode=delvmeth&dlvid=' + delivery_id,
                onSuccess: function(t) {

                    var json = t.responseJSON;
                    if(json.requestStatus == 'OK') {

                        var grandTotal = parseFloat(json['deliveryCost'])
                        + parseFloat(json['vatCost'])
                        + parseFloat(json['subtotalCost']);

                        $('cartGrandTotal').update(grandTotal.numberFormat(2));

                        if($('cartDeliveryCost')) {
                            $('cartDeliveryCost').update(json['deliveryCost'].numberFormat(2));
                        }

                        if($('cartVatCost')) {
                            $('cartVatCost').update(json['vatCost'].numberFormat(2));
                        }


                    //setTimeout('products.orderCompleted();', 9000);
                    }
                }
            });

        },

        getDeliveryOptionsTable: function(id, postcode) {

            postcode = postcode || '';

            $(id).update('<div style="background-color:#FFFFCC;color:#000000;width:130px;padding:10px;margin:15px auto;text-align:center;border:1px solid #FF9933">Getting list... <img src="' + this.iconSpinner + '" style="vertical-align:-4px;height:16px;width:16px" /></div>');

            new Ajax.Updater(id, '../shop/xhr_checkout.php', {
                method: 'post',
                parameters: 'mode=getdeliveryoptions&postcode=' + postcode
            });


        },

        setPaymentMethod: function( paymentMethod ) {


            new Ajax.Request('../shop/xhr_checkout.php', {
                method: 'post',
                parameters: 'mode=paymeth&paymeth=' + paymentMethod,
                onSuccess: function(t) {

                /*if(t.responseJSON.requestStatus == 'OK') {

                        grandTotal = parseFloat(t.responseJSON.deliveryCost) + parseFloat(t.responseJSON.subtotalCost);
                        $('cartGrandTotal').update(grandTotal.numberFormat(2));
                        //setTimeout('products.orderCompleted();', 9000);
                    }*/
                }
            });

        },
        setDeliveryInstructions: function( str ) {


            new Ajax.Request('../shop/xhr_checkout.php', {
                method: 'post',
                parameters: 'mode=delvtext&delvtext=' + str,
                onSuccess: function(t) {

                }
            });

        },

        processBoxId : 'orderProcessBox',
        processOrder : function() {


            var pm = $('payment-method');

            var theForm = document.forms['frmCheckout'];
            var sFlg_delivery = false;
            var sFlg_payment_method = false;
            var sFlg_delivery_address = false;
            var errMsg = "";
            var setfocus = "";

            for(var s2=0;s2<theForm['payment_method'].length;s2++){
                if(theForm['payment_method'].options[s2].selected){
                    if(theForm['payment_method'].options[s2].text==theForm['payment_method'].options[0].text)sFlg_payment_method=true;
                }
            }
            for(var s1=0;s1<theForm['delivery_address'].length;s1++){
                if(theForm['delivery_address'].options[s1].selected){
                    if(theForm['delivery_address'].options[s1].text==theForm['delivery_address'].options[0].text)sFlg_delivery_address=true;
                }
            }

            if(theForm['delivery']) {
                if(theForm['delivery'].length) {
                    for(var s3=0;s3<theForm['delivery'].length;s3++){
                        if(theForm['delivery'][s3].checked) {
                            sFlg_delivery = true;
                            break;
                        }
                    }
                }
                else {
                    if(theForm['delivery'].checked) {
                        sFlg_delivery = true;
                    }
                }
            }

            if (!sFlg_delivery){
                errMsg = "Please select delivery method";
                setfocus = "['delivery']";
            }
            if (sFlg_payment_method){
                errMsg = "Please select a payment method";
                setfocus = "['payment_method']";
            }
            if (sFlg_delivery_address){
                errMsg = "Please select a delivery address";
                setfocus = "['delivery_address']";
            }
            if (errMsg != ""){
                alert(errMsg);
                eval("if(theForm" + setfocus + ".focus) theForm" + setfocus + ".focus()");
                return;
            }

            if(!confirm('Your order is ready to be processed.\n\nPlease confirm that you want to place this order\n')) {
                return;
            }

            var el = $(this.processBoxId);
            if(el) {

                var w = 400;
                var h = 250;

                this.dimmerShow();
                this.setLightBoxPosition(el, w, h);
                $(this.processBoxId+'Inner').setStyle({
                    width:w+'px',
                    height:h+'px'
                });
                el.appear({
                    duration:1
                    ,
                    afterFinish: function() {
                        new Ajax.Request('../shop/xhr_checkout.php', {
                            method: 'post',
                            parameters: 'mode=placeorder',
                            onSuccess: function(t) {
                                setTimeout('checkout.orderCompleted();', 9000);
                            }
                        });
                    }
                });

            }

        },

        orderCompleted : function() {

            var icon = $(this.processBoxId+'Icon');
            var txt  = $(this.processBoxId+'Text');
            var pm =   $('payment-method');

            var msg;

            if(pm.options[pm.selectedIndex].value == 'cc') {
                msg = 'We will charge your credit card associated with your account, if we do not have it we will contact your shortly. We will dispatch your goods as soon as payment clears';
            }
            else if(pm.options[pm.selectedIndex].value == 'dd') {
                msg = 'We will invoice your account and dispatch your goods as soon as payment clears';
            }
            else if(pm.options[pm.selectedIndex].value == 'cc_call') {
                msg = 'We will contact you shortly for your payment information';
            }

            icon.src = '../shop/img/checkout_complete.png';
            txt.update('<h1 style="text-align:center">Order Complete</h1>'
                +'<p style="font-weight:bold">Thank you your order is complete.</p><p>'+msg+'</p>');
            $('checkout-exit').show();

        }
    }
	return ret;
}();



document.observe('dom:loaded', function() {

    $$('input.quantity').each(function(el,ind) {

        el.hasFocus = false;

        el.observe('focus', function(event) {
            Event.element(event).hasFocus = true;
        });
    
        el.observe('blur', function(event) {
            Event.element(event).hasFocus = false;
        });
    });
	
    $$('#currency-selector a').invoke("observe","click",function(e) {
		if(e.element().readAttribute("alt") == null) {
			var cur = e.element().readAttribute("title");
		} else {
			var cur = e.element().readAttribute("alt");
		}
		Shop.changeCurrency(cur);
	});

});