
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 your cart",
        remove_from_cart:   "Remove from your cart",
        update_cart:        "Update cart",

        added_to_cart:      "Added to your cart",
        removed_from_cart:  "Removed from your cart",
        updated_cart:       "Updated cart",

        adding_to_cart:      "Adding to your cart",
        removing_from_cart:  "Removing from your 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 quantity of %s",
		quantity_error:     "Quantity Error",
		invalid_quantity:   "You have entered an invalid quantity, please check your entry",

        maximum_quantity:   "Stock Exceed",
        quantity_too_high:  "We currently only have %s of this item stock. Please reduce the quantity to %s or less"
		
    
    },
    fr : {
        add_to_cart:        "Ajoutez � votre demande",
        remove_from_cart:   "Retirez votre demande",

        added_to_cart:      "Ajout� � votre demande",
        removed_from_cart:  "Retir� de votre demande",

        adding_to_cart:     "S'ajouter � votre demande",
        removing_from_cart: "�limination de votre demande",

        mand_fields:        "Les champs marqu�s * sont obligatoires",

        please_wait:        "Attendez svp...",

        no_items_in_cart:   "Il n'y a aucun article dans votre demande",
        minimum_quantity:   "Quantit� minimale",
        quantity_too_low:   "D�sol�, pour cet article, il faut une quantit� minimale de"
    }

}

var products = {

    //- -----------------------------------------------------------------------------------
    //- 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
    
    fadeSpeed : 0.5,    //- Duration of the fade on the open/close of the lightbox and info pop ups

    //- icons:
    iconAdd:    '../shop/img/icon_addtocart.png',
    iconRm:     '../shop/img/icon_incart.png',
    iconQty:    '../shop/img/icon_update_quantity.png',

    iconSpinner:'../images/ajax-loader.gif',
    iconClose:  '../images/close.png',



    //- --------------- LightBox image display methods and properties ---------------------
    
    working : false,
    fireNext : '',
    layerId : 'productdetail',
    
    lightBoxId : 'productLightBox',
    lightBox : function(id, w, h) {
        el = $(this.lightBoxId);
        
        this.dimmerShow();
        
        if(!el) { //- init on first use
            el     = new Element('DIV', {id:this.lightBoxId, style:'display:none'});
            xbut   = new Element('IMG', {id:this.lightBoxId+'Close', src:this.iconClose, title:'Close'});
            theimg = new Element('IMG', {id:this.lightBoxId+'Img'});
            loader = new Element('IMG', {id:this.lightBoxId+'Loader', src:this.iconSpinner});
            loader.show();

            //black  = new Element('DIV', {id:this.lightBoxId+'Dimmer',style:'width:'+($(document.body).getWidth())+'px;height:'+($(document.body).getHeight())+'px;'});
            //black.setOpacity(0.6);

            el.observe('click', function() {
                Event.stopObserving(document, 'scroll');
                $(products.lightBoxId).fade({
                    duration:products.fadeSpeed,
                    afterFinish : function() {
                        $(products.lightBoxId+'Img').src = '../shop/img/transpx.gif';
                        products.dimmerHide();
                    }
                });
            });
            
            el.appendChild(theimg);
            el.appendChild(xbut);
            el.appendChild(loader);

            //document.body.appendChild(black);
            document.body.appendChild(el);
        }
        else {
            theimg = $(this.lightBoxId+'Img');
            loader = $(this.lightBoxId+'Loader');
            loader.show();
            //$(this.lightBoxId+'Dimmer').show();
        }

        var miniCart = $('mini-cart');
        if(miniCart && miniCart.visible()) {
            this.togCartSummary();
        }

        this.setLightBoxPosition(el, w, h);

        Event.observe(window, 'scroll', function() {
            products.setLightBoxPosition(el, w, h);
        });
        
        theimg.observe('load', function() {
            $(products.lightBoxId+'Loader').hide();
        });
        theimg.src = id;
        theimg.setStyle({width:w+'px', height:h+'px'});
        
        el.appear({duration:products.fadeSpeed});

    },

    setLightBoxPosition : function(el, w, h) {
        viewport_width  = document.viewport.getWidth();
        viewport_height = document.viewport.getHeight();
        vpscroll_top    = document.viewport.getScrollOffsets()['top'];

        new_top = ((viewport_height - h) / 2) + vpscroll_top;

        el.setStyle({marginLeft:'-'+Math.round(w/2)+'px', left:'50%', top:new_top+'px'});

    },

    dimmerShow : function() {

        if(!$(this.lightBoxId+'Dimmer')) {
        
            var black  = new Element('DIV', {id:this.lightBoxId+'Dimmer',style:'width:'+($(document.body).getWidth())+'px;height:'+($(document.body).getHeight())+'px;display:none'});
            black.setOpacity(0.6);
            document.body.appendChild(black);

        }
        else {
            var black = $(this.lightBoxId+'Dimmer');
        }

        black.show();

    },

    dimmerHide : function() {
        var black = $(this.lightBoxId+'Dimmer');
        if(black) {
            black.hide()
        }
    },


    showDescription : function(id) {
        if($(id+'descr').visible()) {
            Effect.BlindUp($(id+'descr'), {
                duration:0.5,
                afterFinish: function() {
                    if($(id+'title')) $(id+'title').setStyle({borderBottom:'1px solid #9a9a9a'});
                } 
            });
        }
        else {
            Effect.BlindDown($(id+'descr'), {
                duration:0.5,
                beforeStart: function() {
                    if($(id+'title')) $(id+'title').setStyle({borderBottom:'1px solid #eeeeee'});
                }
            });
        }
    },


    //- ----------------- Cart Methods --------------------------------
    
    togCartSummary : function() {
        

        var cartSummary = $('cart-summary');
        var cartMini = $('mini-cart');

        if(!cartMini.visible()) {

            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(scrolloffset > n_t) {
                cartMini.setStyle({'top':scrolloffset+'px'});
            }
            else {
                cartMini.setStyle({'top':n_t+'px'});
            }

            Event.observe(window, 'scroll', function() {
                cartMini = $('mini-cart');
                
                var scrolloffset = document.viewport.getScrollOffsets().top;
                
                if(scrolloffset > n_t) {
                    cartMini.setStyle({'top':scrolloffset+'px'})
                }
                else {
                    cartMini.setStyle({'top':n_t+'px'})
                }
            });
        }
        else {
            this.togTimeout = null;
        }

        if(navigator.userAgent.indexOf('Safari/4') == -1) {
            Effect.toggle(cartMini, 'slide', {duration: 0.5, queue:'end'});
        }
        else {
            cartMini.toggle();
        }

    },
    
    addToCart : function(itemId) {

        //- 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;
        }

        if(isNaN(qty)) {
			var page_qty_el = $$('#row'+itemId+ ' input.quantity');
			var cart_qty_el = $$('#cartitem'+itemId+ ' input.quantity');
			
			
			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) {
				products.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));

        if(this.togTimeout) {
            window.clearTimeout(this.togTimeout);
            this.togTimeout = window.setTimeout('products.togCartSummary()', 3000);
        }

        this.loadingTimeout = window.setTimeout("products.showMessage({title:lang.get('adding_to_cart'),msg:lang.get('please_wait'),duration:0,position:$('cart-link-"+itemId+"')})", 500);
        
        
        
        new Ajax.Request( '../shop/xhr_cart.php'
                        , { method:     'post'
                          , parameters: 'mode=add&product_id='+itemId + '&qty=' + qty
                          , onSuccess: function(t) {

                                window.clearTimeout(products.loadingTimeout);
                                products.loadingTimeout = null;
                                window.setTimeout('products.hideMessage(lang.get(\'adding_to_cart\'))',500);
                                //if(!$('mini-cart').visible()) {
                                //    products.togCartSummary();
                                //}

                                //products.togTimeout = window.setTimeout('products.togCartSummary()', 3000);
                            
                                json = t.responseText.evalJSON();
                                products.updatePage(json);

                            }
                          }
                        );
    
    },

    rmFromCart: function(itemId) {

        this.loadingTimeout = window.setTimeout("products.showMessage({title:lang.get('removing_from_cart'),msg:lang.get('please_wait'),duration:0,position:$('cart-link-"+itemId+"')})", 500);

        new Ajax.Request( '../shop/xhr_cart.php'
                        , { method:     'POST'
                          , parameters: 'mode=rm&product_id='+itemId
                          , onSuccess: function(t) {
                                window.clearTimeout(products.loadingTimeout);
                                products.loadingTimeout = null;
                                window.setTimeout('products.hideMessage(lang.get(\'removing_from_cart\'))',500);
                                
                                json = t.responseText.evalJSON();
                                products.updatePage(json);
                            }
                          }
                        );
    },

    updateQuantity: function(itemId, qty, min_qty) {

		if(qty === '') {
			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) {
				products.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'));
		}

        //- only send request if quantity is value
        if(!min_qty) min_qty = 1;

		//qty = qty.replace(/[A-Za-z]+/, '');
		
		qty = Math.floor(qty);

        if(qty == 0 || min_qty <= qty) {
        
            this.loadingTimeout = window.setTimeout("products.showMessage({title:lang.get('updating_cart'),msg:lang.get('please_wait'),duration:0,position:$('cart-link-"+itemId+"')})", 500);

            
            new Ajax.Request('../shop/xhr_cart.php', {
                                method:     'POST',
                                parameters: 'mode=upd&product_id='+itemId+'&qty='+qty,
                                onSuccess: function(t) {
                                    window.clearTimeout(products.loadingTimeout);
                                    products.loadingTimeout = null;
                                    window.setTimeout('products.hideMessage(lang.get(\'updating_cart\'))',500);

                                    json = t.responseText.evalJSON();
                                    products.updatePage(json);
                                }
                            });
        }
        else {

			var page_qty_el = $$('#row'+itemId+ ' input.quantity');
			var cart_qty_el = $$('#cartitem'+itemId+ ' input.quantity');

			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) {

                //var qty_el = $$('#cartitem'+itemId+ ' input.quantity');

                products.showMessage({
                        title:    lang.get('minimum_quantity'),
                        msg:      lang.get('quantity_too_low', min_qty.numberFormat(0)),
                        duration: 0,
                        position: qty_el
                });
            }
        }
    },

    reColourRows: function(id) {
        ely = $(id);
        j = 0;
        for(i = 0; i<ely.childNodes.length; i++) {
            if(ely.childNodes[i].nodeName=='DIV' && /cartitem.+/.test(ely.childNodes[i].id)) {
                if(j&1) {
                    $(ely.childNodes[i]).removeClassName('alt-row');
                    $(ely.childNodes[i]).style.backgroundColor = '';
                }
                else {
                    $(ely.childNodes[i]).addClassName('alt-row');
                    $(ely.childNodes[i]).style.backgroundColor = '';
                }
                j++;
            }
        }

    },


    updatePage: function(details) {
        //- Intelligent (ha!) page update

        //- if adding more than the MaxQuantity, do nothing but display error
        if(typeof details['itemMaxQuantity'] == 'number' && details['itemMaxQuantity'] != 0) {

            if(details['itemQuantity'] > details['itemMaxQuantity']) {

                var page_qty_el = $$('#row'+details['itemId']+ ' input.quantity');
                var cart_qty_el = $$('#cartitem'+details['itemId']+ ' input.quantity');
                
                
                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];
                }

                this.showMessage({
                        title:    lang.get('maximum_quantity'),
                        msg:      lang.get('quantity_too_high', details['itemMaxQuantity'].numberFormat(0)),
                        duration: 0,
                        position: qty_el
                });
                
                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').each(function(el,ind) {
                if(el.id.indexOf(details['itemId']) > -1 && !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 );
        }
        
        
        //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']) {
                products.showMessage({
                        title:    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) {
            
            el = $('cartitem' + details['itemId']);
            
            if(el) {
                //- pretty fade if row is visible
                if(!$('mini-cart') || $('mini-cart').visible()) {
                    new Effect.Fade(el, { duration:1
                                        , afterFinish: function() { 
                                             el.remove(); 
                                             if($('full-cart')) {
                                                 products.reColourRows('full-cart');
                                             }
                                             else if($('cart-items')) {
                                                 products.reColourRows('cart-items');
                                             }
                                             if(details['cartCount']==0 && $('no-items')) {
                                                $('no-items').show();
                                             }
                                          }
                                        });
                }
                //- else just DESTROY!! Muahaha
                else {
                    el.remove();
                    if($('full-cart')) {
                        products.reColourRows('full-cart');
                    }
                }
            }
        }
        else if(typeof details['itemMinQuantity'] == 'number') {

            if(details['itemQuantity'] < details['itemMinQuantity']) {
                var qty_el = $$('#cartitem'+details['itemId']+ ' input.quantity');

                products.showMessage({
                        title:    lang.get('minimum_quantity'),
                        msg:      lang.get('quantity_too_low', details['itemMinQuantity'].numberFormat(0)),
                        duration: 0,
                        position: qty_el[0]
                });
            }
            else {
                this.hideMessage(lang.get('minimum_quantity'));
            }
        }

        
        //- Update item sub total in mini-cart
        if($('cartitemtotal'+details['itemId'])) {
            $('cartitemtotal'+details['itemId']).update(details['itemTotal']);
        }

        
        //- Update total quantity
        if($('myCartCount')) {
            $('myCartCount').update(details['cartCount'] + ' item' + (details['cartCount']==1?'':'s'));
        }

        //- Update cart total cost
        if($('myCartSum')) {
            $('myCartSum').update(details['totalCost']);
        }
        
        if($('cartDeliveryCost')) {
            $('cartDeliveryCost').update(deatils['deliveryCost']);
        }

        //- 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('products.togCartSummary()', 3000);
            }
            else {
                if(this.togTimeout) {
                    window.clearTimeout(this.togTimeout);
                    this.togTimeout = window.setTimeout('products.togCartSummary()', 3000);
                }
            }


            $('cart-items').insert(details['htmlFragment']);
            el = $('cartitem'+details['itemId']);
            if(el) {
                if($('mini-cart').visible()) {
                    //el.hide();
                    //new Effect.Appear(el, {duration:1});
                    new Effect.Highlight(el, {
                        duration:   1, 
                        startcolor: '#ffcc00', 
                        endcolor:   '#ef4035',
                        queue:      'end',
                        afterFinish: function(o) {
                            //- sometimes the cart row gets a rouge minus margin... bizarre
                            //- remove this
                            o.element.style.margin = '0';
                            products.reColourRows('cart-items');

                            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;
                                });
                            }
                        }
                    });
                }
            }
        }
    },

    changeIcon : function(type, details) {
        var new_src, new_text, new_func;

        var icon = $('cart-icon-' + details['itemId']);
        var dalink = $('cart-link-' + details['itemId']);
        
        if(type == 'update') {
            new_text = lang.get('update_quantity');
            new_src  = this.iconQty;
            new_func = function(e) { 
                var _qty = $$('#row' + this.itemId + ' input.quantity')[0].value;
                products.updateQuantity(this.itemId, _qty, this.itemMinQuantity); 
            }
        }
        else if(type == 'add') {
            new_text = lang.get('add_to_cart');
            new_src  = this.iconAdd;
            new_func = function(e) { products.addToCart(this.itemId); }
        }
        else if(type == 'remove') {
            new_text = lang.get('remove_from_cart');
            new_src  = this.iconRm;
            new_func = function(e) { products.rmFromCart(this.itemId); }
        }

        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.onclick = new_func;
        }

    },
    iconType : function(itemId) {
        var dalink = $('cart-link-' + itemId);
        var 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();
        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) {
                                    products.rmFav(this.prd_id, this);
                                }
                                new Effect.Highlight($($('myFavCount').parentNode), {restorecolor:'#ffffff'});
                                products.showMessage({title:      'Item Added',
                                                      msg:        'Added to your favourites list!',
                                                      duration:   1.5,
                                                      position:   obj                                                    
                                                    });
                            }
                          }
                        );
    },

    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.prd_id = itemId;
                                obj.onclick = function(e) {
                                    products.addToFav(this.itemId, this);
                                }
                                
                                new Effect.Highlight($($('myFavCount').parentNode), {restorecolor:'#ffffff'});
                                
                                if($('myproduct-'+itemId)) {

                                    /*tmp = $('product-'+prd_id).getElementsByTagName('TD');
                                    for(i=0; i<tmp.length; i++) {
                                    }*/

                                    if(Prototype.Browser.IE) {
                                        nodes = $('myproduct-'+itemId).childNodes;
                                        for(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 {
                                    products.showMessage({
                                            title:  'Item Removed',
                                            msg:    'Removed from your favourites list!',
                                            duration:1.5,
                                            position:   obj
                                    });
                                }
                            }
                          }
                        );

    },


    /* --------------------------- Checkout methods ------------------------*/





    /* ------------------- Tooltop Popup Methods and properties ------------*/

    boxId : 'messageBox',
    showMessageTO : null,
    showMessage : function(options) {

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

        boxTimeout = options.duration ? function() { products.showMessageTO = setTimeout('products.hideMessage(\''+options.title+'\')', options.duration*1000); } : function() {};
        
        //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);


        box = $(this.boxId);
        $('messageTitle').update('<img src="../images/close_small.png" id="messageClose" style="width:10px;height:10px" onclick="products.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($(products.boxId) && $(products.boxId).visible()) {
            if(Prototype.Browser.IE) {
                $(products.boxId).hide();
            }
            else {
                new Effect.Fade(this.boxId, {duration:0.3});
            }
        }
    },
    positionBox : function(o, options) {
        options = Object.extend({ 
            position: 'center',
            postionElement: null
        }, options || {});

        offs = document.viewport.getScrollOffsets();

        if(options.position == 'center') {
            if(!o.visible()) o.show();
            new_top  = Math.round(document.viewport.getHeight() / 2);
            new_top -= Math.round(parseInt(o.getStyle('height')) / 2);
            new_top += offs['top'];
            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)) {

            el = $(options.position);
            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'});
    }
}

var checkout = {

    iconSpinner: '../shop/img/spinner_16px.gif',

    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) {

            }
        });
    },
    setOrderNotes: function( str ) {
        new Ajax.Request('../shop/xhr_checkout.php', {
            method: 'post',
            parameters: 'mode=ordernotes&ordernotes=' + 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;
        }

        el = $(this.processBoxId);
        if(el) {

            w = 400;
            h = 250;

            products.dimmerShow();
            products.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();

    }

}

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;
        });
    });

});
