﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

$.Calculation.setDefaults({
    // a regular expression for detecting European-style formatted numbers

    reNumbers: /(-|-\$)?(\d+(\.\d{3})*(\,\d{1,})?|\,\d{1,})/g
    // define a procedure to convert the string number into an actual usable number
  , cleanseNumber: function (v) {
      // cleanse the number one more time to remove extra data (like commas and dollar signs)
      // use this for European numbers: v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".")

      return v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
  }
})

function lookupContacts(name) {
    var webMethod = '../WebServices/ContactService.asmx/LookupContacts';
    var parameters = "{'name':'" + name + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#contacttable tr').remove();
            if (msg.d.length == 0) {
                $('#contacttable tbody:last').append('<tr><td>Ingen funnet!</td></tr>');
            }
            else {
                $('#contacttable tbody:last').append('<tr><td><b>Navn</b></td><td><b>OrgNr</b></td></tr>');
                for (var i = 0; i < msg.d.length; i++) {
                    $('#contacttable tr:last').after('<tr><td><a href="#" title="klikk for å velge" onclick="getExternalContact(' + msg.d[i].OrgNr + ')">' + msg.d[i].Name + '</a></td><td><a href="#" title="klikk for å velge" onclick="getExternalContact(' + msg.d[i].OrgNr + ')">' + msg.d[i].OrgNr + '</a></td></tr>');
                }
            }
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");

            // Display the specific error raised by the server (e.g. not a
            //   valid value for Int32, or attempted to divide by zero).
            alert(err.Message);
        }
    });
}

function getContact(id) {
    if (id == '') return false;

    var divToBeWorkedOn = '#AjaxPlaceHolder';
    var webMethod = '../WebServices/ContactService.asmx/GetContact';
    var parameters = "{'contactId':'" + id + "'}";

    $.ajax({ type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var contact = msg.d;
            $('#tbName').val(contact.Name);
            $('#tbContactPerson').val(contact.ContactPerson);
            $('#tbAddress').val(contact.Address.AddressLine1);
            $('#tbZip').val(contact.Address.Zip);
            $('#tbCity').val(contact.Address.City);
            $('#tbEmail').val(contact.Email);

            $('#lbBetaltAv').html(contact.Name + '<br />' + contact.ContactPerson + '<br />' + contact.Address.AddressLine1 + '<br />' + contact.Address.Zip + ' ' + contact.Address.City)
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");

            // Display the specific error raised by the server (e.g. not a
            //   valid value for Int32, or attempted to divide by zero).
            alert(err.Message);
        }
    });
}

$(function () {
    $("#lookup").live('click', function (event) {
        $(".pop").slideFadeToggle();
        lookupContacts($('#tbName').val());
        return false;
    });
});

$.fn.slideFadeToggle = function (easing, callback) {
    return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
};

$(function () {
    $('#closemessagepop').live('click', function () {
        $('#contactlookup').hide();
    });
});

function getExternalContact(orgnr) {
    var webMethod = '../WebServices/ContactService.asmx/GetExternalContact';
    var parameters = "{'orgnr':'" + orgnr + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("#contactlookup").hide();
            fillfields(msg.d);
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");

            // Display the specific error raised by the server (e.g. not a
            //   valid value for Int32, or attempted to divide by zero).
            alert(err.Message);
        }
    });
}

function fillfields(contact) {
    if (contact.Name) $('#tbName').val(decode(contact.Name));
    if (contact.Website) $('#tbWebpage').val(contact.Website);
    if (contact.Fax) $('#tbFax').val(contact.Fax);
    if (contact.Email) $('#tbEmail').val(contact.Email);
    if (contact.Address.AddressLine1) {
        $('#tbAddress1').val(decode(contact.Address.AddressLine1));
        $('#tbAddress').val(decode(contact.Address.AddressLine1));
    }
    if (contact.Address.AddressLine1) $('#tbAddress2').val(decode(contact.Address.AddressLine2));
    if (contact.Address.Zip) $('#tbZip').val(contact.Address.Zip);
    if (contact.Address.City) {
        $('#tbCity').val(decode(contact.Address.City));
        $('#tbPostSted').val(decode(contact.Address.City));
    }
    if (contact.Address.Country) $('#tbCountry').val(contact.Address.Country);
    if (contact.Telephone) $('#tbPhone').val(contact.Telephone);
    if (contact.Mobile) $('#tbMobile').val(contact.Mobile);
    if (contact.OrgNr) $('#tbOrgNr').val(contact.OrgNr);
}

function encode(input) {
    return $('<div/>').text(input).html();
}

function decode(input) {
    return $('<div/>').html(input).text();
}

function addNewFakturaRow(row) {

    if (row == undefined) {
        row = new Object();
        row.Price = '0,00';
        row.Description = '';
        row.Discount = '0';
        row.Count = '1,00';
        row.VatPercent = '0,25';
    }

    var rowCount = $('#invoice-lines tr').size();
    var productOptions;
    $.each(products, function (intIndex) {
        productOptions += '<option value="' + products[intIndex].ID + '">' + products[intIndex].Name + '</option>';
    });

    var fakturaRow = '<tr><td><a onclick="$(this).parent().parent().remove(); recalculateFaktura(); return false;" href="#" title="Slett denne linjen">Slett</a></td>';
    fakturaRow += '<td><select onchange="setProduct(this, this.selectedIndex)" name="product"><option value="">Velg produkt</option>' + productOptions + '</select></td>';
    fakturaRow += '<td><input class="linetext" name="description" type="text" value="' + row.Description + '" /></td>';
    fakturaRow += '<td><input name="price" class="unitprice number" type="text" value="' + row.Price + '" /></td>';
    fakturaRow += '<td><input name="antall" class="count number" type="text" value="' + row.Count + '" /></td>';
    fakturaRow += '<td id="total_umva_item"></td>';
    fakturaRow += '<td><input name="rabatt" class="discountpercent number" type="text" value="' + row.Discount + '" /></td>';
    fakturaRow += '<td><select name="mva">';
    fakturaRow += AddOption('0,25', '25%', row.VatPercent == '0,25');
    fakturaRow += AddOption('0,14', '14%', row.VatPercent == '0,14');
    fakturaRow += AddOption('0,08', '8%', row.VatPercent == '0,08');
    fakturaRow += AddOption('0,00', '0%', row.VatPercent == '0,00');
    fakturaRow += '</select></td>';
    fakturaRow += '<td id="total_mmva_item"></td>';
    fakturaRow += '<td style="display:none" id="total_mumva_item2"></td>';
    fakturaRow += '</tr>';

    if (rowCount > 0) {
        $('#invoice-lines tr:last').after(fakturaRow);
    }
    else {
        $('#invoice-lines').append(fakturaRow);
    }

    $("input[name^=antall]").bind("keyup", recalculateFaktura);
    $("input[name^=price]").bind("keyup", recalculateFaktura);
    $("input[name^=rabatt]").bind("keyup", recalculateFaktura);
    $("select[name^=mva]").bind("change", recalculateFaktura);
}

function AddOption(val, text, isSelected){
    var string = '<option ';
    if (isSelected)
        string += 'selected';
    string += ' value="' + val + '">' + text + '</option>';
    return string;
}

function recalculateFaktura() {
    $("[id^=total_umva_item]").calc(
    // the equation to use for the calculation
	        "qty * price",
    // define the variables used in the equation, these can be a jQuery object
	        {
	        qty: $("input[name^=antall]"),
	        price: $("input[name^=price]")
	    },
    // define the formatting callback, the results of the calculation are passed to this function
	        function (s) {
	            // return the number as a dollar amount
	            return "kr " + s.toFixed(2).toString().replace(".", ",");
	        },
    // define the finish callback, this runs after the calculation has been complete
	        function ($this) {
	            var sum = $this.sum();
	        }
        );

	    $("[id^=total_mumva_item2]").calc(
	        // the equation to use for the calculation
	        "qty * price * (1.00 - (rabatt / 100.00))",
	        // define the variables used in the equation, these can be a jQuery object
	        {
	        qty: $("input[name^=antall]"),
	        price: $("input[name^=price]"),
	        rabatt: $("input[name^=rabatt]")
	    },
	    // define the formatting callback, the results of the calculation are passed to this function
	        function (s) {
	            // return the number as a dollar amount
	            return "kr " + s.toFixed(2).toString().replace(".", ",")
	        },
	    // define the finish callback, this runs after the calculation has been complete
	        function ($this) {
	            // sum the total of the $("[id^=total_item]") selector
	            var sum = $this.sum();

	            $("#invoice-totals-net").text(
			        "kr " + sum.toFixed(2).toString().replace(".", ",")
		        );
	        }
        );

	    $("[id^=total_mmva_item]").calc(
	        // the equation to use for the calculation
	        "qty * price * (1.00 - (rabatt / 100.00)) * (1.00 + mva)",
	        // define the variables used in the equation, these can be a jQuery object
	        {
	        qty: $("input[name^=antall]"),
	        price: $("input[name^=price]"),
	        rabatt: $("input[name^=rabatt]"),
	        mva: $("select[name^=mva]")
	    },
	    // define the formatting callback, the results of the calculation are passed to this function
	        function (s) {
	            // return the number as a dollar amount
	            return "kr " + s.toFixed(2).toString().replace(".", ",")
	        },
	    // define the finish callback, this runs after the calculation has been complete
	        function ($this) {
	            // sum the total of the $("[id^=total_item]") selector
	            var sum = $this.sum();

	            $("#invoice-totals-gross").text(
			        "kr " + sum.toFixed(2).toString().replace(".", ",")
		        );

	            $("#invoice-totals-vat").text(
			        "kr " + (sum - $("#invoice-totals-net").parseNumber()).toFixed(2).toString().replace(".", ",")
		        );

	            $('#lbBelop').text(
			        "kr " + sum.toFixed(2).toString().replace(".", ",")
		        );

	            $('#lbKroner').text(
	                Math.floor(sum)
		        );

	            $('#lbOre').text(
	                (sum.toFixed(2) - Math.floor(sum)).toFixed(2) * 100
		        );

	            var jsonObj = getJsonFakturaLinesFromDOM();
	            $('#fakturalines').val(JSON.stringify(jsonObj));
	        }
        );
    return true;
}

function getJsonFakturaLinesFromDOM() {
    var jsonObj = new Array();
    $('#invoice-lines tr').each(function () {
        var description = $(this).find("[name=description]").val();
        var price = $(this).find("[name=price]").parseNumber().toString();
        var count = $(this).find("[name=antall]").parseNumber().toString();
        var discount = $(this).find("[name=rabatt]").parseNumber().toString();
        var vat = $(this).find("[name=mva]").parseNumber().toString();
        jsonObj.push({ Description: description, Price: price, Count: count, Discount: discount, VatPercent: vat });
    });
    return jsonObj;
}

function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

function localize(num) {
    return num.toFixed(2).toString().replace(".", ",");
}

function setProduct(row, productindex) {
    var product = products[productindex - 1];
    if (product != undefined) {
        $(row).parent().parent().find("[name=description]").val(product.Name);
        $(row).parent().parent().find("[name=price]").val(localize(product.Price));
        $(row).parent().parent().find("[name=antall]").val("1,00");
        $(row).parent().parent().find("[name=mva]").val(localize(product.Vat));
    }

    recalculateFaktura();
}
        