﻿var webRoot = 'http://www.renishawdirect.com/en/';


function addItemsToShoppingCart(productQuantity, user, containerId) {
    var $j = jQuery.noConflict();

    // show working image
    IndicateUpdating(containerId);

    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/AddItemsToShoppingCart',
        data: 'productQuantity=' + productQuantity + '&userId=' + user,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var problemXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(problemXml);

            if (jsonU.values != undefined) {
                for (var i=0;i<jsonU.values.length;i++) {
                    var ProductCode = jsonU.products[i].product[0].Text;
                    var QuantityText = jsonU.products[i].productquantity[0].Text;
                    var ProductCost = jsonU.products[i].producttotal[0].Text;
                    
                    if (jsonU.values[i].result[0].Text == 'success') {
                        // check if new row needed
                        var rowAddId = $('ShoppingCart_' + ProductCode);

                        // add a new row and fade it in if new item in basket
                        if (rowAddId == null) {
                            var newRow = "<tr id=\"ShoppingCart_" + ProductCode + "\" class=\"cartItemRow\"><td><input type=\"submit\" name=\"ShoppingCart$remProd" + ProductCode + "\" value=\"x\" onclick=\"removeItemFromShoppingCart('" + ProductCode + "', '" + user + "', 'ShoppingCart_tblCartSmall'); return false;\" id=\"ShoppingCart_remProd" + ProductCode + "\" class=\"cartRemoveItem\" /></td><td>" + ProductCode + "</td><td id=\"ShoppingCart_ItemQty_" + ProductCode + "\">" + QuantityText + "&nbsp;</td><td id=\"ShoppingCart_ItemTotalCost_" + ProductCode + "\" class=\"cartTotalColumn\">" + ProductCost +"</td></tr>";
                            new Insertion.Before('ShoppingCart_spacerRow', newRow)
                        }
                        // show the basket updated label
                        showHideUpdatedLabel(true, true, ProductCode, QuantityText);
                    } else {
                        // show the basket updated label
                        showHideUpdatedLabel(false, true, '', '');
                    }
                }

                // update the individual item totals
                updateCartItemsTotals(jsonU, true, containerId);
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst removing the item.');
        }
    });
}


function addItemToShoppingCart(ProductCode, QuantityText, user, containerId)
{
    var $j = jQuery.noConflict();
	var quantity = $(QuantityText);
    
    // show working image
    IndicateUpdating(containerId);

    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/AddItemToShoppingCart',
        data: 'productCode='+ProductCode+'&quantityString='+quantity.value+'&userId='+user,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var problemXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(problemXml);

            if (jsonU.values != undefined) {
                if (jsonU.values[0].result[0].Text == 'success') {
                    // check if new row needed
                    var rowAddId = $('ShoppingCart_' + ProductCode);
                    
                    // add a new row and fade it in if new item in basket
                    if (rowAddId == null) {
                        var newRow = "<tr id=\"ShoppingCart_"+ProductCode+"\" class=\"cartItemRow\"><td><input type=\"submit\" name=\"ShoppingCart$remProd"+ProductCode+"\" value=\"x\" onclick=\"removeItemFromShoppingCart('"+ProductCode+"', '"+user+"', 'ShoppingCart_tblCartSmall'); return false;\" id=\"ShoppingCart_remProd"+ProductCode+"\" class=\"cartRemoveItem\" /></td><td>"+ProductCode+"</td><td id=\"ShoppingCart_ItemQty_"+ProductCode+"\">"+QuantityText+"&nbsp;</td><td id=\"ShoppingCart_ItemTotalCost_"+ProductCode+"\" class=\"cartTotalColumn\">&#163;2.64</td></tr>";
	                    new Insertion.Before('ShoppingCart_spacerRow', newRow)
                    }
                    // show the basket updated label
                    showHideUpdatedLabel(true, true, ProductCode, quantity.value);
                } else {
                    // show the basket updated label
                    showHideUpdatedLabel(false, true, '', '');
                }

                // update the individual item totals
                updateCartItemsTotals(jsonU, true, containerId);
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst removing the item.');
        }
    });
}


function removeItemFromShoppingCart(ProductCode, user, containerId)
{
    var $j = jQuery.noConflict();
    
    // show working image
    IndicateUpdating(containerId);

    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/RemoveItemFromShoppingCart',
        data: 'productCode='+ProductCode+'&userId='+user,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var problemXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(problemXml);

            if (jsonU.values != undefined) {
                // show the basket updated label
                showHideUpdatedLabel(true, false, '', '');
                
                // update cart items
                updateCartItemsTotals(jsonU, false, containerId);
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst removing the item.');
        }
    });
}


function updateItemQuantity(user, containerId)
{
    var $j = jQuery.noConflict();
    
    // show working image
    IndicateUpdating(containerId);
    
    var productQuantity='';
    
    var allproducts = document.getElementById('tblCart').getElementsByTagName('INPUT');
    for (i=0;i<allproducts.length;i++) {
        if(allproducts[i].id != '' && allproducts[i].id.substring(0,17)=='cartItemQtyInput_') {
            var productCode = allproducts[i].id.substring(17);
            productQuantity += productCode+':'+document.getElementById(allproducts[i].id).value+';';
        }
    }
    
    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/UpdateProductQuantity',
        data: 'productQuantity='+productQuantity+'&userId='+user,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var problemXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(problemXml);

            if (jsonU.values != undefined) {
                // update the individual item totals
                updateCartItemsTotals(jsonU, false, containerId);
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst updating your cart.');
        }
    });
}


function addVoucherToCart(voucherId, user, containerId)
{
    var $j = jQuery.noConflict();
    
    // show working image
    IndicateUpdating(containerId);
    
    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/AddVoucherToCart',
        data: 'voucherId='+voucherId+'&userId='+user,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var problemXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(problemXml);

            if (jsonU.values != undefined) {
                updateVoucherTable(jsonU.voucher[0].message[0].Text, jsonU.values[0].result[0].Text);
                // update the cart totals (no need to do individual items)
                updateCartTotal(jsonU.values[0].newtotal[0].Text, jsonU.values[0].newshipping[0].Text, jsonU.values[0].newvoucher[0].Text, jsonU.values[0].newsavings[0].Text, jsonU.values[0].newtaxvalue[0].Text, jsonU.values[0].itemcount[0].Text, containerId)
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst updating your cart.');
        }
    });
}


/* Avalara validate address AJAX call */
function validateAddress(addressLine1, addressLine2, city, region, zipCode, country, containerId, addressType)
{
    var $j = jQuery.noConflict();
    
    // show working image
    IndicateUpdating(containerId);
    
    $j.ajax({
        type: 'POST',
        url: webRoot +'WebService/CartService.asmx/ValidateAddress',
        data: 'addressLine1='+addressLine1+'&addressLine2='+addressLine2+'&city='+city+'&region='+region+'&zipCode='+zipCode+'&country='+country,
        success: function(transport) {
            var reply = $j(transport).find('string').text();
            var addressXml = $j.textToXML(reply);
            var jsonU = $j.xmlToJSON(addressXml);

            if (jsonU.address != undefined) {
                if (jsonU.address.length==1) {
                    updateAddressValues(jsonU, addressType);
                }
                IndicateUpdateDone(containerId, 'Done');
            } else if (jsonU.error != undefined) {
                // set help to let customer know something wasn't right!
                DisplayMessages(jsonU);
                // stop working image
                IndicateUpdateDone(containerId, 'Error');

                var validation = new Validation('frmShippingDetails'); //, {useTitles:true});
                validation.validate()
            } else {
                // stop working image
                IndicateUpdateDone(containerId, 'Error');

                var validation = new Validation('frmShippingDetails'); //, {useTitles:true});
                validation.validate()
            }
        },
        error: function(xml) {
            // stop working image
            IndicateUpdateDone(containerId, 'Error: There was an error whilst updating your cart.');
        }
    });
    return false;
}


function addMultipleItems(user)
{
    // get all products with a quantity of > 0
    var inputCollection = document.getElementsByTagName("INPUT");
    var partsToAdd;
    
    for (var i=0; i<inputCollection.length;i++) {
        if (inputCollection[i].id != null && inputCollection[i].id.substring(0,4)=="qty_") {
            var prodCode = inputCollection[i].id.substring(4, inputCollection[i].id.length);
            var qty = inputCollection[i].value;
            if (qty > 0) {
                if (partsToAdd == undefined) {
                    partsToAdd = prodCode + '#' + qty;
                } else {
                    partsToAdd += ',' + prodCode + '#' + qty;
                }
                document.getElementById(inputCollection[i].id).value = '';
            }
        }
    }

    if (partsToAdd != undefined) {
        // add items to cart
        addItemsToShoppingCart(partsToAdd, user, 'ShoppingCart_tblCartSmall')
    }
}


function updateAddressValues(jsonU, addressType)
{
    var address1 = $('txt'+addressType+'AddressLine1');
    Element.extend(address1);
    if (jsonU.address[0].addressline1[0].Text!=undefined) {
        address1.value = jsonU.address[0].addressline1[0].Text;
    } else {
        address1.value = "";
    }

    var address2 = $('txt'+addressType+'AddressLine2');
    Element.extend(address2);
    if (jsonU.address[0].addressline2[0].Text!=undefined) {
        address2.value = jsonU.address[0].addressline2[0].Text;
    } else {
        address2.value = "";
    }

    var city = $('txt'+addressType+'City');
    Element.extend(city);
    if (jsonU.address[0].city[0].Text!=undefined) {
        city.value = jsonU.address[0].city[0].Text;
    } else {
        city.value = "";
    }

    var state = $('txt'+addressType+'State');
    Element.extend(state);
    if (jsonU.address[0].region[0].Text!=undefined) {
        state.value = jsonU.address[0].region[0].Text;
    } else {
        state.value = "";
    }

    var zipcode = $('txt'+addressType+'PostCode');
    Element.extend(zipcode);
    if (jsonU.address[0].zipcode[0].Text!=undefined) {
        zipcode.value = jsonU.address[0].zipcode[0].Text;
    } else {
        zipcode.value = "";
    }

    var validation = new Validation('frmShippingDetails'); //, {useTitles:true});
    if (validation.validate()) {
        $('btnNextStep').onclick = '';
        var submitButton = $('btnNextStep');
        submitButton.click();
    }
}


function validateAddressGB()
{
    var validation = new Validation('frmShippingDetails'); //, {useTitles:true});
    return validation.validate()
}


function DisplayMessages(jsonU)
{
    var displayElement = $('ValidationMessagesDiv');
    Element.extend(displayElement);
    
    displayElement.innerHTML = '<ul>';
    for (var i=0;i<jsonU.error.length;i++) {
        displayElement.innerHTML += '<li>'+jsonU.error[i].message[0].Text+'</li>';
    }
    displayElement.innerHTML += '</ul>';
    
    showHideElement(displayElement.id,true);
}


function showHideElement(elementName, show)
{
    var displayElement = $(elementName);
    Element.extend(displayElement);
    
    if (show) {
        new Effect.Appear(displayElement);
    } else {
        new Effect.Fade(displayElement);
    }
}


function showHideUpdatedLabel(success, show, productCode, qty)
{
    var itemList = $('jsListAddedToBasket');
    if (itemList!=null && itemList.childNodes.length!=0) {
        itemList.removeChild(document.getElementById('item1'));
    }
    
    if (success) {
        var basketUpdatedSuccessLabel = $('StyliProduct_pnlBasketUpdateSuccess');
        Element.extend(basketUpdatedSuccessLabel);
        if (show && basketUpdatedSuccessLabel!=null) {
            var itemList = $('jsListAddedToBasket');
            Element.extend(itemList);
            var bullet = document.createElement("LI");
            bullet.id = 'item1';
            bullet.innerHTML = productCode+' (Qty '+qty+')';
            itemList.appendChild(bullet);
            if (basketUpdatedSuccessLabel.style.display=='none') {
                new Effect.Appear(basketUpdatedSuccessLabel);
            }
        } else if (!show && basketUpdatedSuccessLabel!=null && basketUpdatedSuccessLabel.style.display!='none') {
            new Effect.Fade(basketUpdatedSuccessLabel);
        }
    } else {
        var basketUpdatedFailLabel = $('StyliProduct_pnlBasketUpdateFail');
        Element.extend(basketUpdatedFailLabel);
        if (show && basketUpdatedFailLabel.style.display=='none') {
            new Effect.Appear(basketUpdatedFailLabel);
        } else if (!show && basketUpdatedFailLabel.style.display!='none'){
            new Effect.Fade(basketUpdatedFailLabel);
        }
    }
}


function updateCartTotal(newTotal, newShipping, newVoucher, newSavings, newTax, itemsInCart, containerId)
{
    if (itemsInCart=='0') {
	    var table = $(containerId);
	    new Effect.Fade(table);
	    
		// hide voucher panel if visible
		if (containerId=='tblCart') {
	        var voucherPanel = $('pnlVoucher');
		    new Effect.Fade(voucherPanel);
	        var voucherPanel = $('carNavDiv');
		    new Effect.Fade(voucherPanel);
		} else {
		    new Effect.Fade($('ShoppingCart_ViewCartDiv'));
		    new Effect.Fade($('ShoppingCart_CheckOutDiv'));
		}
		new Effect.Appear($('ShoppingCart_lblCartIsEmpty'));
    } else {
        // if basket was empty fade it in
        var table = $(containerId);
        if (table.style.display=='none') {
            new Effect.Fade($('ShoppingCart_lblCartIsEmpty'));
            new Effect.Appear(table);
            new Effect.Appear($('ShoppingCart_ViewCartDiv'));
            new Effect.Appear($('ShoppingCart_CheckOutDiv'));
        }
    
	    var basketTotal = $('ShoppingCart_tdTotalValue');
	    Element.extend(basketTotal);
	    basketTotal.innerHTML = newTotal;
	    
	    var shippingCost = $('ShoppingCart_tdShippingValue');
	    Element.extend(shippingCost);
	    if (newShipping != "&#163;-1.00") {
	        shippingCost.innerHTML = newShipping;
	    } else {
	        shippingCost.innerHTML = "<a href=\"/en/Checkout/ShippingDetails.aspx\">check</a>";
	    }
    	
	    var basketVoucher = $('ShoppingCart_tdVoucherValue');
    	if (newVoucher!='0') {
	        Element.extend(basketVoucher);
	        basketVoucher.innerHTML = newVoucher;
	        if ($('ShoppingCart_trVoucherRow').style.display=='none') {
	            new Effect.Appear($('ShoppingCart_trVoucherRow'));
	        }
	    } else if(containerId!='tblCart') {
		    new Effect.Fade($('ShoppingCart_trVoucherRow'));
	    }
    	
	    var basketSavings = $('ShoppingCart_tdSavingsValue');
    	if (newSavings!='0') {
	        Element.extend(basketSavings);
	        basketSavings.innerHTML = newSavings;
	        if ($('ShoppingCart_trSavingsRow').style.display=='none') {
	            new Effect.Appear($('ShoppingCart_trSavingsRow'));
	        }
	    } else {
		    new Effect.Fade($('ShoppingCart_trSavingsRow'));
	    }
    	
	    var basketTax = $('ShoppingCart_tdTaxValue');
	    Element.extend(basketTax);
	    basketTax.innerHTML = newTax;
	}
	
    // stop working image
    IndicateUpdateDone(containerId, 'Done');
}


function updateCartItemsTotals(jsonU, updateQuantity, containerId) {
    var valueToUse = jsonU.values.length - 1;
    if (jsonU.values[valueToUse].result[0].Text == 'success') {
        for (var i=0; i<jsonU.products.length; i++) {
            if (jsonU.products[i].productquantity[0].Text!='0') {
                // update item information
	            var productTotal = $('ShoppingCart_ItemTotalCost_'+jsonU.products[i].product[0].Text);
	            Element.extend(productTotal);
	            productTotal.innerHTML = jsonU.products[i].producttotal[0].Text;
	            if (updateQuantity) {
	                var productQuantity = $('ShoppingCart_ItemQty_'+jsonU.products[i].product[0].Text);
	                Element.extend(productQuantity);
	                productQuantity.innerHTML = jsonU.products[i].productquantity[0].Text+'x&nbsp;';
	            }
	        } else {
	            // need to remove row
                var rowRemoveId = 'ShoppingCart_'+jsonU.products[i].product[0].Text;
                Effect.Fade(rowRemoveId, {duration: 0.7});
                var cmd = '$(\'' + rowRemoveId + '\').remove(\'deletedItem\')';//first remove the item
                window.setTimeout(cmd, 700);
	        }
	    }
    	
	    // update totals
	    updateCartTotal(jsonU.values[valueToUse].newtotal[0].Text, jsonU.values[valueToUse].newshipping[0].Text, jsonU.values[valueToUse].newvoucher[0].Text, jsonU.values[valueToUse].newsavings[0].Text, jsonU.values[valueToUse].newtaxvalue[0].Text, jsonU.values[valueToUse].itemcount[0].Text, containerId)
	} else {
        // stop working image
        IndicateUpdateDone(containerId, 'Done');
	}
}


function updateVoucherTable(voucherComment, additionSuccess)
{
    var voucherLabel = $('lblVoucherResult');
    
    if (voucherLabel.style.display=='none') {
        new Effect.Appear(voucherLabel);
    }
    
    // set the comment
    voucherLabel.innerHTML = voucherComment;
    
    // set the style
    if (additionSuccess=='success') {
        voucherLabel.className='goodResult';
    } else {
        voucherLabel.className='badResult';
    }
}


//Provide visual feedback we are talking to the server - not that the page is not responding
function IndicateUpdating(containerElementId)
{
	//find element
	var container = $(containerElementId);
	
	//create overlay
    var indicator = '<div id="' + containerElementId + '_updating" class="updatingIndicator">working on your request.</div>';
	
    //fade back the cart
    new Effect.Opacity(container,
        { duration: 0.5, 
          transition: Effect.Transitions.linear, 
          to: 0.5 });
	
    //add to the containing element
    new Insertion.After(containerElementId, indicator)
}


//Let the user know we have finished our server calls
function IndicateUpdateDone(containerElementId, feedback)
{
    var feedbackContainer = $(containerElementId + '_updating');
    if (feedback != '')
    {
	    feedbackContainer.innerHTML = feedback;
    }
	
    //fade back in our updated element
    new Effect.Opacity($(containerElementId),
        { duration: 0.5, 
          transition: Effect.Transitions.linear, 
          to: 1.0 });	
		  
    //fade out the indicator
    new Effect.Fade(feedbackContainer);
}



function showUpdateText() {
	var newElement = "<br /><div class='infoMsg'>Due to essential maintenance on our servers, RenshawDirect.com will be unavailable between the hours of  00:00 to 07:00 (BST) on Saturday 19th September.<br />We apologise for any inconvenience this may cause.<br /><br />Regards,<br />Internet development team</div>";
	new Insertion.After('navRenishaw', newElement)
}

//addLoadListener(showUpdateText);