/**
 * Toggles the "Show details" on product search.
 * @requires jQuery
 * @param showText Text before show
 * @param hideText Text before hide
 * @param resetDetails Boolean, resets all fields if true
 */
 /* Create NetR namespace */
if (typeof NetR === "undefined") {
    var NetR = {};
}

NetR.selectHasValue = function(el) {
    if (el.jquery != null) { el = el['0']; }
    // alert(el.name + ': ' + el.selectedIndex);
    return (el.selectedIndex > 0);
}

$(document).ready(function() {
    var resetDetails = true;
    var ajaxRequestArray = [];
    var ajaxRequestIsRunning = false;
    var $togglelink = $('<a href="#" class="show-details">' + showText + '</a>');
    /* "Hides" the details temporarily */
    // Only hide if no select has a value selected
    if ($('#product-search:not(class) .details select').filter(function(index) { return NetR.selectHasValue(this); }).length == 0) {
        $("#product-search:not(class) .details").hide().before($togglelink); /* products */
    }
    else {
        $("#product-search:not(class) .details").before($togglelink.html(hideText));
    }
    $("#product-search.alt .details").hide().after($togglelink); /* shop */
    $("#product-search .show-details").toggle(
		function() {
		    if (resetDetails)
		        $resetHtml = $("#product-search .details").html();
		    $("#product-search .details").show();
		    $togglelink.html(hideText);
		},
		function() {
		    if (resetDetails)
		        $("#product-search .details").html($resetHtml);
		    $("#product-search .details").hide();
		    $togglelink.html(showText);
		}
	);
    $("#btn-reset").click(function() {
        $(this).parents("form").find("select").each(function() {
            $(this)[0].selectedIndex = 0;
        }).end().find(".text input").each(function() {
            $(this).val("");
        });
        return false;
    });
    /* Select all checkboxes */
    $("#select-all").html('<img src="/i/select-none.gif" alt="Markera alla" title="Markera alla" />').find("img").click(function() {
        $boxes = $(this).parents("table").find("input:checkbox");
        if ($boxes.attr("checked")) {
            $boxes.removeAttr("checked");
            $(this).attr('src', '/i/select-none.gif');
        } else {
            $boxes.attr("checked", "checked");
            $(this).attr('src', '/i/select-all.gif');
        }
    });

    $('.quantity input').focus(function() {
        $(this).select();
    });
    $('#shop-table .quantity input').keypress(function(e) {
        if (e.keyCode == 13) {
            var button = $('button[value="save"]');
            if (button.length == 0) { button = $('button[value="continue"]') }
            if (button.length > 0) {
                e.preventDefault();
                button.click();
                return false;
            }
        }
    });

    $('.disabled').attr("disabled", "disabled");
    $('.disabled').parents('form').submit(function(e) {
        $('.disabled', this).removeAttr('disabled');
    });

    /* Add "Show details" link and remove it after click */
    //    $('.product-info .stock-info').siblings('table, ul').hide();
    //    $('.product-info .stock-info').before('<a href="#" class="shop-details">' + sDetails + '<\/a>');
    //    $('.product-info .shop-details').click(function() {
    //        $(this).siblings('*:hidden').show().end().remove();
    //        return false;
    //    });
    //    /* Decrease/increase shopping basket inventory */
    $('.decrease').click(function() {
        var self = $(this);
        var curNum = parseFloat(self.next("input").val());
        if (curNum <= 1) {
            if (confirm("Vill du markera artikeln för radering?")) {
                self.parents("tr").find("input:first").attr("checked", "checked");
                self.next("input").val(0);
            }
        } else {
            //updateQtyInArmatecStore(this.id, curNum - 1);
//            var soapEnv =
//            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:netr='http://armatec.Store/'><soapenv:Header/><soapenv:Body><netr:UpdateItemQty>" +
//            "<netr:itemID>" + this.id + "</netr:itemID>" +
//            "<netr:qty>" + eval(curNum - 1) + "</netr:qty>" +
//            "</netr:UpdateItemQty></soapenv:Body></soapenv:Envelope>";

//            ajaxRequestArray.push(soapEnv);

            self.next("input").val(curNum - 1);
            updateSum(self, curNum, false);

//            setTimeout(function() { updateQtyInArmatecStore() }, 1);
        }
        return false;
    });
    $('#item_qty').change(function() {
        var self = $(this);
        var curNum = parseFloat(self.val());
        var itemID = self.prev("a").attr("id");

//        var soapEnv =
//            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:netr='http://armatec.Store/'><soapenv:Header/><soapenv:Body><netr:UpdateItemQty>" +
//            "<netr:itemID>" + itemID + "</netr:itemID>" +
//            "<netr:qty>" + eval(curNum) + "</netr:qty>" +
//            "</netr:UpdateItemQty></soapenv:Body></soapenv:Envelope>";

//        ajaxRequestArray.push(soapEnv);

        updateSum(self, curNum, true);

//        setTimeout(function() { updateQtyInArmatecStore() }, 1);

        return false;
    });
    $('.increase').click(function() {
        var self = $(this);
        var curNum = parseFloat(self.prev("input").val());
//        var soapEnv =
//            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:netr='http://armatec.Store/'><soapenv:Header/><soapenv:Body><netr:UpdateItemQty>" +
//            "<netr:itemID>" + this.id + "</netr:itemID>" +
//            "<netr:qty>" + eval(curNum + 1) + "</netr:qty>" +
//            "</netr:UpdateItemQty></soapenv:Body></soapenv:Envelope>";

//        ajaxRequestArray.push(soapEnv);

        self.prev("input").val(curNum + 1);
        updateSum(self, curNum, true);
        //updateQtyInArmatecStore(this.id, curNum + 1);

//        setTimeout(function() { updateQtyInArmatecStore() }, 1);

        return false;
    });
    function updateQtyInArmatecStore() {
        if (ajaxRequestArray.length <= 0 || ajaxRequestIsRunning)
            return;

        ajaxRequestIsRunning = true;

        var soapEnv = ajaxRequestArray.shift();

        var httpReq = $.ajax({
            type: "POST",
            url: "/Store/WS/Store.asmx",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("SOAPAction",
                "http://armatec.Store/UpdateItemQty");
            },
            data: soapEnv,
            contentType: "text/xml; charset=utf-8",
            dataType: "xml",
            timeout: 15000,
            complete: function(xData, status) {
                setTimeout(function() { updateQtyInArmatecStore() }, 1);
                ajaxRequestIsRunning = false;
            },
            success: function(data) {
            },
            error: function(req, msg, err) {
            }
        });
    }
    function updateSum(elm, num, method) {
        var unitPrice = parseFloat(elm.parent().next().text().replace(",", "."));
        if (method) { // If addition
            var newNum = num;
            var newTotal = (num + 1.0) * unitPrice;
        } else { // If subtraction
            var newNum = num - 1;
            var newTotal = (num - 1.0) * unitPrice;
        }
        elm.parent().siblings("td:last").find(".auto-sum").text(floatToCurrency(newTotal));
        totalSum(unitPrice, method);
    }
    function totalSum(sum, m) {
        var curTotal = parseFloat($('tfoot .auto-sum').text().replace(",", "."));
        if (m) { // If addition
            $('tfoot .auto-sum').text(floatToCurrency(curTotal + sum));
        } else { // If subtraction
            $('tfoot .auto-sum').text(floatToCurrency(curTotal - sum));
        }
    }
    function floatToCurrency(f) {
        return f.toFixed(2).replace(".", ",");
    }
    /* Prompt for obligatory product information where needed */
    $('.additional-input').each(function() {
        var btn = $(this).parent().find('input[name="btn-1"]');
        var cbtn = $(btn).clone();
        var heading = $(this).parent().parent().find('h4').clone();
        var cancelLink = $('<a />').attr('href', '#').addClass('cancel').html('Avbryt').click(function() {
            $(this).parent().parent().hide();
            return false;
        });
        $(this).hide().addClass('prompt').find('div').append(cancelLink);
        $(this).find('div').prepend(heading).append(cbtn).append(cancelLink);
        $(btn).click(function() {
            var top = $(document).scrollTop() + 100;
            $(this).parent().find('.prompt').css('top', top + 'px').show().find('input:first').focus();
            return false;
        });
    });
    /* Get delivery address with ajax */
    $('#selDeliveryAddress').change(function() {
        $('.ajax-addr').remove();
        var box = $('<div id="ajax-addr" />').addClass('ajax-addr');
        var value = $(this).find('option:selected').text();

        var soapEnv =
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:arm=\"http://armatec.Store/\"> \
            <soapenv:Header/> \
            <soapenv:Body> \
            <arm:GetDeliveryAddress> \
            <arm:title>" + value + "</arm:title> \
            </arm:GetDeliveryAddress> \
            </soapenv:Body> \
            </soapenv:Envelope>";

        var httpReq = $.ajax({
            type: "POST",
            url: "/Store/WS/Store.asmx",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("SOAPAction",
                "http://armatec.Store/GetDeliveryAddress");
            },
            data: soapEnv,
            contentType: "text/xml; charset=\"utf-8\"",
            dataType: "xml",
            timeout: 15000,
            complete: function(xData, status) {
                if (status != 'success') {
                    alert('Ett fel uppstod. Försök igen.')
                }
                else {
                    $(xData.responseXML).find("GetDeliveryAddressResult").each(function() {
                        var html = "<table> \
    	                    <tbody> \
    		                    <tr> \
    			                    <th scope=\"row\">Namn</th> \
    			                    <td>" + $(this).find('Name').text() + "</td> \
    		                    </tr> \
    		                    <tr> \
    			                    <th scope=\"row\">Gatuadress 1</th> \
    			                    <td>" + $(this).find('Street').text() + "</td> \
    		                    </tr> \
    		                    <tr> \
    			                    <th scope=\"row\">Postnummer</th> \
    			                    <td>" + $(this).find('Zip').text() + "</td> \
    		                    </tr> \
    		                    <tr> \
    			                    <th scope=\"row\">Ort</th> \
    			                    <td>" + $(this).find('City').text() + "</td> \
    		                    </tr> \
    		                    <tr> \
    			                    <th scope=\"row\">Land</th> \
    			                    <td>" + $(this).find('Country').text() + "</td> \
    		                    </tr> \
    	                    </tbody> \
                        </table> \
                        ";
                        $("#ajax-addr").append(html);
                    });
                }
            },
            success: function(xData, status) {
            },
            error: function(req, msg, err) {
                alert("Ett fel uppstod försök igen.");
            }
        });

        $(this).after(box);
    });
});

