
$(document).ready(function () {

    //-- triggers when clear button is clicked on ---//
    $(".clearButton").click(function() {

        $(".productRow").each(function(){
            var chosenRow;

            chosenRow = this.id.substring(10, this.id.length);
            $('tr.extraRow' + chosenRow).remove();
            $('div#productDescription' + chosenRow).html(' ');
            $('#productCode' + chosenRow).val('');
            $('#productQuantity' + chosenRow).val('');
            $('#validDescription' + chosenRow).val(0);
        });
        return false;
    });

    //-- triggers when 'Add All To Basket' button is clicked on ---//
    $("a.addAllToBasketButton").click(function() {

        var errorCount = 0

        //--- validate if any product code entered ---//
        var validDescriptionCount = 0

        $(".validDescription").each(function(){
            if($(this).val() == 1) {
                validDescriptionCount = validDescriptionCount + 1
            }
        });

        if(validDescriptionCount == 0) {
		    alert('Por favor, introduzca al menos un código de producto y una cantidad válida a añadir a su carrito')
		    errorCount++;
            return false;
        }

        //--- validate if correct qty entered for product codes ---//
        $(".validDescription").each(function(){
            var chosenRow
            chosenRow = this.id.substring(16, this.id.length);

            if($(this).val() == 1) {
                var qtyValue

                qtyValue = $.trim($("#productQuantity" + chosenRow).val());

                if(qtyValue == ''){
		            alert('No todos los productos tienen una cantidad. Por favor, verifique su pedido')
		            errorCount++;
	                return false;
                }

                if(isNaN(qtyValue)){
		            alert('No todas las cantidades son válidas. Por favor, verifique su pedido')
		            errorCount++;
   	                return false;
                }
            }
        });

        if(errorCount == 0){
            document.MultipleAddToBasket.submit();
            return true;
        }
        else{
            return false;
        }

    });


    //-- triggers when 'Close' button is clicked on (redundant) ---//
    $("a.closeButton").live("click", function(){
        var chosenRow, parentRow, childCount, startingPoint;

	startingPoint = "closeButton".length

        chosenRow = this.id.substring(startingPoint, this.id.length);
        parentRow = this.id.substring(startingPoint, this.id.lastIndexOf("_"));
        childCount = 0

        $('tr.extraRow' + parentRow).each(function(){
            childCount = childCount + 1;
        });

        if(childCount == 1){
            $('div#productDescription' + parentRow).html(' ');
            $('#productCode' + parentRow).val('');
            $('#productQuantity' + parentRow).val('');
            $('#validDescription' + parentRow).val(0);
        }

        $('#productRow' + chosenRow).remove();

        return false;
    });


    //-- triggers when 'Close' button is clicked on ---//
    $("a.addButton").live("click", function(){
        var chosenRow, parentRow, startingPoint;
        var thisProductCode, thisQty, thisDescription

	startingPoint = "addButton".length

        chosenRow = this.id.substring(startingPoint, this.id.length);
        parentRow = this.id.substring(startingPoint, this.id.lastIndexOf("_"));

    $('div#productDescription' + chosenRow + ' .addButton').remove();
	thisDescription = $('div#productDescription' + chosenRow).html();

	thisQty = $('#productQuantity' + chosenRow).val();
	thisProductCode = $('#productCode' + chosenRow).val();

	$('div#productDescription' + parentRow).html(thisDescription);
	$('#productCode' + parentRow).val(thisProductCode);
	$('#productQuantity' + parentRow).val(thisQty);
	$('#validDescription' + parentRow).val(1);

        $('tr.extraRow' + parentRow).each(function(){
            $(this).remove();
        });



        return false;
    });


    //-- triggers when product code input box is on blur ---//
    $("input.fastOrderCode").blur(function(){

         var thisForm, chosenRow, strProductCode;

         chosenRow = this.id.substring(11, this.id.length);
         strProductCode = $.trim(this.value);

         if (strProductCode != ''){

            var intCount = 0;
            var numRows, sProductCode, sProductDescription, sMediaCode, sProductLink, newRow, numberOfSuggestions

            $.get("/products/FastOrderCheckProduct.asp", {productCode:strProductCode}, function(xml){

               numRows = $("Root",xml).attr("numRows");
               numberOfSuggestions = $("Product[IsSuggestion='true']",xml).length;

                if (numRows == 0) {
                    $('tr.extraRow' + chosenRow).remove();
                    $('div#productDescription' + chosenRow).empty().text('Lo sentimos, pero ha introducido un código de producto no válido. Por favor, inténtelo de nuevo.');
                    $("input#validDescription" + chosenRow).val(0);
                }
                else if (numRows == 1  && numberOfSuggestions == 0) {
                    $("Product",xml).each(function() {
                        sProductCode = $(this).attr("ProductCode");
                        sProductDescription = $(this).attr("Description");
                        sMediaCode = $(this).attr("MediaCode");

                        if (sMediaCode != ''){
                            sProductLink = $("<a>").attr("href","/products/productDetail.asp?productCode=" + sProductCode + "&mediaCode=" + sMediaCode).append(sProductDescription);
                        }
                        else {
                            sProductLink = $("<a>").attr("href","/products/productDetail.asp?productCode=" + sProductCode).append(sProductDescription);
                        }

                        $('tr.extraRow' + chosenRow).remove();
                        $('div#productDescription' + chosenRow).empty().append(sProductLink);
                        $("input#validDescription" + chosenRow).val(1);
                    });
                }
                else {

                    $('tr.extraRow' + chosenRow).remove();
                    $('div#productDescription' + chosenRow).empty().text('Código de producto incorrecto. A continuación le mostramos posibles alternativas.');
                    $("input#validDescription" + chosenRow).val(2);

                    $("Product",xml).each(function() {

                        intCount = intCount + 1;
                        sProductCode = $(this).attr("ProductCode");
                        sProductDescription = $(this).attr("Description");
                        sMediaCode = $(this).attr("MediaCode");

                        if (sMediaCode != ''){
                            sProductLink = $("<a>").attr("href","/products/productDetail.asp?productCode=" + sProductCode + "&mediaCode=" + sMediaCode).addClass("productLink").append(sProductDescription);
                        }
                        else {
                            sProductLink = $("<a>").attr("href","/products/productDetail.asp?productCode=" + sProductCode).addClass("productLink").append(sProductDescription);
                        }

                        newRow = $("<tr>").attr("id","productRow" + chosenRow + "_" + intCount).addClass("productRow").addClass("extraRow" + chosenRow).append(
                                    $("<td>").attr("height","27").addClass("number firstCol").append("")
                                ).append(
                                    $("<td>").addClass("productCode").append(
                                        $("<input>").attr("type","hidden").attr("name","productCode").attr("value",sMediaCode + sProductCode).attr("id","productCode" + chosenRow + "_" + intCount).addClass("fastOrderCode")
                                    ).append(
                                        sMediaCode + sProductCode
                                    )
                                ).append(
                                    $("<td>").append(
                                        $("<input>").attr("type","text").attr("name","quantity").attr("value","").attr("maxlength","4").attr("id","productQuantity" + chosenRow + "_" + intCount).addClass("fastOrderQty")
                                    )
                                ).append(
                                    $("<td>").append(
                                        $("<div>").attr("id","productDescription" + chosenRow + "_" + intCount).addClass("description").append(
                                            sProductLink
                                        ).append(
                                            $("<a>").attr("href","#").attr("title","Add").attr("id","addButton" + chosenRow + "_" + intCount).addClass("addButton").append(
                                                $("<img>").attr("src","/images/buttons/Fast_Order_Add_button.gif").attr("width","52").attr("height","19").attr("alt","Add").attr("title","Add")
                                            )
                                        )
                                    ).append(
                                        $("<input>").attr("type","hidden").attr("name","validDescription").attr("value","1").attr("id","validDescription" + chosenRow + "_" + intCount).addClass("validDescription")
                                    )
                                )

                        $("tr#productRow" + chosenRow).after(newRow);

                    })
                }

            },"xml");
        }
        else {
            $('tr.extraRow' + chosenRow).remove();
            $('div#productDescription' + chosenRow).html(' ');
            $('#productQuantity' + chosenRow).val('');
            $('#validDescription' + chosenRow).val(0);
        }
    });


});


