var pricelist, services, servicesSelectCount, allow_rush, rushOrderRate;
var discount = 0, discountType = 'amount';

function orderform_addSelect()
{
	$("#tr_discount_code").before(
		'<tr id="tr_service_' + servicesSelectCount + '" class="tr_service">' +
			'<th></th>' +
			'<td>' +
				'<select class="services" name="services[' + servicesSelectCount + ']" id="s' + servicesSelectCount + '" rel="service" onfocus="this.onmousewheel=function(){return false}">' +
				services +
				'</select> ' +
				'<span class="price" id="prices' + servicesSelectCount + '"></span> ' +
                                '<span class="rush" id="rush_s' + servicesSelectCount + '" style="display: none"> ' +
                                    '<input class="checkbox" type="checkbox" id="chk_rush_s' + servicesSelectCount + '" name="services_rush[' + servicesSelectCount + ']" onclick="orderform_calculatePrice();" onchange="orderform_calculatePrice();" /> ' +
                                    '<label for="chk_rush_s' + servicesSelectCount + '">Rush Order (+' + rushOrderRate + ' %)</label> ' +
                                '</span> ' +
                                '<span class="remove" id="span_remove_s' + servicesSelectCount + '" style="display: none"><a title="remove" href="#" onclick="orderform_removeService(' + servicesSelectCount + '); return false;">&times;</a></span>' +
			'</td>' +
		'</tr>'
	);
	$("#s" + servicesSelectCount).change(function () {orderForm_onChange(this)});
	
	// custom-form-elements
	var input = $("#s" + servicesSelectCount + "")[0];
	
	option = input.getElementsByTagName("option");
	active = option[0].childNodes[0].nodeValue;
	textnode = document.createTextNode(active);
	for(b = 0; b < option.length; b++) {
		if(option[b].selected == true) {
			textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
		}
	}
	
	servicesSelectCount++;
}

function orderform_removeService(i)
{
    var tr = $("#tr_service_" + i);
    var first_tr = $('#table_orderform tr:first');

    if(tr.attr('id') != first_tr.attr('id') || $('.tr_service').length > 1)
    {
        tr.remove();
    }
    else
    {
        tr.find('select').val(0).change();
    }

    $('#table_orderform tr:first th').text('Select the desired service:');

    orderform_calculatePrice();
}

function orderForm_onChange(select)
{
    if(select.value > 0)
    {
        // add new selectbox if necessary
        if(select.id == 's' + (servicesSelectCount - 1))
            orderform_addSelect(select);

        $('#price' + select.id).text('$' + pricelist[select.value]);

        var chk_rush = $('#rush_' + select.id);
        chk_rush.find('input').attr('checked', false);
        if(allow_rush[select.value])
            chk_rush.show();
        else
            chk_rush.hide();

        $('#span_remove_' + select.id).show();
    }
    else
    {
        $('#price' + select.id).text('');
    }

    // recalculate price
    orderform_calculatePrice();
}

function orderform_calculatePrice()
{
    var totalprice = 0;
    $('select[rel=service]').each(function()
    {
        var rush = $('#chk_rush_' + this.id).attr('checked');
        var price = pricelist[this.value] * (rush ? 1 + rushOrderRate/100 : 1);
        totalprice += price;
        $('#price' + this.id).text('$' + price.toFixed(2));
    });

    if(discountType == 'amount')
    {
        totalprice -= discount;
    }
    else
    {
        totalprice *= 1 - discount / 100;
    }

    totalprice = Math.max(0, totalprice);

    $('#totalprice').text('$' + totalprice.toFixed(2));
}

function orderform_validateDiscountCode()
{
    var code = $('#tr_discount_code input').val();

    $.getJSON('', {'do': 'validateDiscount', 'code': code}, function(payload)
    {
        if(!payload.ok)
        {
            alert('Discount code is not valid.');
        }
        else
        {
            $('#tr_discount_code th label').text('Discount:');

            discount = payload.discount;
            discountType = payload.type;

            $('#tr_discount_code td *').hide();

            if(discountType == 'amount')
            {
                $('#tr_discount_code td').append($('<span class="discount_size">').text('− $' + discount));
            }
            else
            {
                $('#tr_discount_code td').append($('<span class="discount_size">').text('−' + discount + ' %'));
            }

            var a_remove = $('<a href="#" class="discount_edit">').text('remove').click(function(e)
            {
                $('#tr_discount_code input').val('');
                $('#tr_discount_code td').find('a, span.discount_size').remove();
                $('#tr_discount_code td *').show();
            });

            $('#tr_discount_code td').append(a_remove);

            orderform_calculatePrice();
        }
    });
}

