function dbg(str) {
	if (typeof(console) == "undefined") return;
	else console.log(str);
}

function loadPrices() {
	$.ajax({
		type: "GET",
		url: "http://www.textildruckerei.net/bop/preise.xml",
		dataType: "xml",
		success: function(xml) {
			XMLPrices = xml;
			initPrices(); }
	});
}

function fillXML(cat) {
	$(XMLProducts).find('productfactors > ' + cat).each(function(){
	ProductFactors[cat] = new Array();
	$(this).find('quantity').each(function(){
		ProductFactors[cat][$(this).attr('value')] = $(this).text();
		});
	});
}

function loadProducts() {
    $.ajax({
        type: "GET",
        url: "http://www.textildruckerei.net/bop/produkte.xml",
        dataType: "xml",
        success: function(xml) {
            XMLProducts = xml;
            fillXML('tshirt');
            fillXML('polo');
            fillXML('sweater');
            fillXML('hoodiezip');
            fillXML('hoodie');
            CategoryButtonClicked('tshirts');
        }
    });
}

function initPrices() {
    SetupPrice = parseFloat($(XMLPrices).find('setup').text());
    FilmSetupPrice = parseFloat($(XMLPrices).find('filmsetup').text());

    $(XMLPrices).find('row').each(function() {
        var ccprices = new Array();
        ccprices['factor'] = $(this).find('factor').text();
        $(this).find('cell').each( function(){
            ccprices[$(this).attr('colorcount')] = $(this).text();
        })
        PrintColorPriceList[$(this).attr('quantity')] = ccprices;
    });
}

function createBasketEltHtml(htmlproduct, count) {
    ////dbg("createBasketEltHtml()");
    var nm     = htmlproduct.find('span[@name=name]').text();
    var artnum = htmlproduct.find('span[@name=artnum]').text();
    var prod = getProductByArtnum(artnum);
    var bd = prod.find('brand').text();
    ////dbg("Brand: " + bd);
    var md = prod.find('model').text();

    var baskethtml = '&nbsp;';
    baskethtml += '<input type="text" name="elt_count" value="'+count+'" size="5" >';
    baskethtml += '<br/>';
    baskethtml += '<span class="BasketEltName">' + nm + '</span>';
    baskethtml += ', ';
    baskethtml += '<span class="BasketEltBrand">' + bd + '</span>';
    baskethtml += ' - ';
    baskethtml += '<span class="BasketEltModel">' + md + '</span>';
    baskethtml += '<span name="articlenum" style="display:none;">' + artnum + '</span>';
    baskethtml += '<div class="BasketEltBorder"></div>';

    $('<div class="BasketElt">')
        .append($('<button class="delete" alt="Dieses Produkt entfernen." title="Dieses Produkt entfernen."/>').click( function() {
                                $(this).parent().fadeOut(400, function() {
                                    $(this).remove();
                                });
                                textileCountChanged();
                                if($('.BasketElt').length == 0)
                                    showEmptyBasket();
                                }))
        .append(baskethtml)
        .appendTo('#Basket');
}

function createCarouselElement(xmlproduct) {
    var articlenum   = xmlproduct.find('articlenum').text();
    var nm = xmlproduct.find('name').text();
    var smallimg = articlenum.replace('.', '_') + '_small.jpg';
    var smallimgurl = "http://www.textildruckerei.net/bop/images/" + smallimg;

    var p = $('<li style="text-align:center">'); // $('<li class="ProductElt">');
    var img_small = '<img src="' + smallimgurl + '">';
    var sp_name   = '<span name="name">' + nm + '</span>';
    var a_details = '<a href="bop/getdetails.php5?height=465&width=720&articlenum='+articlenum+'" class="ShowProductDetails">Details</a>';
    var sp_artnum = '<span name="artnum" style="display:none;">' + articlenum + '</span>';

    p.append( img_small +  '<br/>' )
        .append(sp_name  + '<br/>' + a_details)
        .append(sp_artnum)
        .append('<br/>')
        ;

    $('button[@name=addproduct]').attr('disabled', 'true');
    p.click(function() {
        var wasactive = $(this).hasClass('active');
        $('.active').removeClass('active');

        if (wasactive) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
        if ($('.active').length > 0)
            $('button[@name=addproduct]').removeAttr('disabled');
        else
            $('button[@name=addproduct]').attr('disabled', true);

    });

    return p;
}

function CategoryButtonClicked(cmd) {
    dbg("Category Button: " + cmd);
    var products;
    switch(cmd)
    {
        case 'all':
            products = $(XMLProducts).find('product');
            break;
        case 'formen':
            products = $(XMLProducts).find('product[@gender=m]');
            break;
        case 'forwomen':
            products = $(XMLProducts).find('product[@gender=w]');
            break;
        case 'forkids':
            products = $(XMLProducts).find('product[@gender=k]');
            break;
        case 'tshirts':
            products = $(XMLProducts).find('product[@type=tshirt]');
            break;
        case 'polos':
            products = $(XMLProducts).find('product[@type=polo]');
            break;
        case 'sweater':
            products = $(XMLProducts).find('product[@type=sweater]');
            break;
        case 'hoodiezips':
            products = $(XMLProducts).find('product[@type=hoodiezip]');
            break;
        case 'hoodies':
            products = $(XMLProducts).find('product[@type=hoodie]');
            break;
        default:
            alert('No Command Given to "productSelectionChanged(cmd);"');
            break;
    }

    dbg("Found: " + products.length + " Elements");
    $('#ProductList').empty();
    products.each(function() {
            createCarouselElement($(this)).appendTo('#ProductList');
    });

    // Activate ThickBox for productDetails
    tb_init('a.ShowProductDetails');

    $("#Carousel").unbind();
    $("#Carousel").jCarouselLite({
        btnNext: ".right",
        btnPrev: ".left",
        circular:false,
        visible:5
    });
};

function textileCountChanged() {
	////dbg("textileCountChanged()");
	var textilecount=0;
	$('input[@name="elt_count"]').each(function(){
		var c = parseInt($(this).val());
		if (c > 10000)
			err('COUNTTOOHIGH');
		textilecount = textilecount + c;
	});

	TotalTextileCount = textilecount;
	////dbg("\tTotalTextileCount: " + TotalTextileCount);
	calculatePrice();
};

function err(code) {
	switch (code)
	{
		case 'NOPRODSELECTED':
			alert("Sie haben noch kein Produkt ausgewählt.");
			break;
		case 'ALREADYSELECTED':
			alert("Dieses Produkt befindet sich bereits in Ihrer Auswahl.");
			break;
		case 'COUNTTOOHIGH':
			alert("Bitte wenden Sie sich bei Anfragen über 10.000 Stück direkt an uns.")
			break;
		case 'COUNTTOOLOW':
			alert("Sie müssen eine Anzahl größer 0 eingeben.")
			break;
		case 'NOTANUM':
			alert("Bitte geben Sie eine Zahl ein.");
			break;
		case 'INVALIDPRINTCOLOR':
			alert ("Druckfarbenanzahl muss zwischen 1 und 10 liegen.");
			break;
		case 'BASKETEMPTY':
			alert ("Sie haben noch keinen Artikel ausgewählt. Ein Angebot kann nicht erstellt werden.");
			break;
		case 'ILLEGALPRINTFACTOR':
			alert ("Illegal Count value in getPrintFactorIndex()");
			break;
		case 'ILLEGALPRODUCTFACTOR':
			alert ("Illegal Count value in getProductFactorIndex()");
			break;
		default:
			alert ("An Erroroccured - Code: " + code);
			break;
	}
}

function printColorCountChanged() {
	//dbg("printColorCountChanged()");
	PrintColorError = false;
	var cc = parseInt(0);
	var tc  = parseInt($('select[@name=TextileColor]').val());

	// PrintColorFront
	if ($('input[@name=hasPrintColorFront]').is(':checked')) {
		PrintColorCountFront = parseInt($('select[@name=PrintColorFront]').val()) + tc
		//dbg("\tDruckfarbenanzahl Front: " + PrintColorCountFront);
	} else PrintColorCountFront = 0;

	// PrintColorBack
	if ($('input[@name=hasPrintColorBack]').is(':checked')) {
		PrintColorCountBack = parseInt($('select[@name=PrintColorBack]').val()) + tc;
		//dbg("\tDruckfarbenanzahl Back: " + PrintColorCountBack);
	} else PrintColorCountBack = 0;

	calculatePrice();
}

function getProductFactorIndex(c) {
	if (c >= 0 && c <20)
		return 0
	else if (c >= 20 && c <50)
		return 20;
	else if(c >= 50 && c <100)
		return 50;
	else if(c >= 100 && c <500)
		return 100;
	else if(c >= 500 && c <1000)
		return 500;
	else if(c >= 1000 && c <2500)
		return 1000;
	else if(c >= 2500 && c <5000)
		return 2500;
	else if(c >= 5000)
		return 5000;
	else
		err('ILLEGALPRODUCTFACTOR');
}

function getPrintFactorIndex(c) {
	if (c >= 0 && c <20)
		return 10;
	else if (c >= 20 && c <50)
		return 20;
	else if(c >= 50 && c <100)
		return 50;
	else if(c >= 100 && c <300)
		return 100;
	else if(c >= 300 && c <500)
		return 300;
	else if(c >= 500 && c <1000)
		return 500;
	else if(c >= 1000 && c < 2500)
		return 1000;
	else if(c >= 2500 && c < 5000)
		return 2500;
	else if(c >= 5000 && c < 10000)
		return 5000;
	else if(c >= 10000 )
		return 10000;
	else
		err('ILLEGALPRINTFACTOR');
}

/** Returns the XML Element which has the given 'artnum'.
 */
function getProductByArtnum(artnum){
	return $(XMLProducts).find('product:has(articlenum:contains('+artnum+'))');
}

/** Calculates the Overall Price of the currently selected Elements.
 * To Calucale a Price there have to be at least 20 textiles overall and at least one printcolor
 * selected.
 */
function calculatePrice() {
	//dbg("calculatePrice()");
	//dbg(TotalTextileCount);
	var inputerror = false;
	// Only Calculate Price if Textile Count is >= 20 and there is a PrintColor chosen.
	if (TotalTextileCount < 20 || (PrintColorCountFront == 0 && PrintColorCountBack == 0)) {
		//dbg("ERROR: Textileanzahl < 20 oder keine Druckfarbenanzahl gewählt");
		$('#ResultsError').show();
		inputerror = true;
		}
	if (PrintColorError) {
		//dbg("ERROR: PrintColorError exists!");
		$('#ResultsError').show();
		inputerror = true;
		}

	if (inputerror) {
		showDummyResults();
		$('input[value="Absenden"]').attr('disabled', true);
		return;
	}
	$('input[value="Absenden"]').attr('disabled', false);

	if ($('#ResultsError').is(':visible'))
		$('#ResultsError').hide();

	//dbg("-----------------\n\n\n Neuer Preis:");
	//dbg("Textilien:");

	// -----------  Textile Price Calculations -----------
	TotalTextilePrice = 0.0;
	TotalTextileCount = 0;
	$('.BasketElt').each(function(){
		var artnum   = $(this).find('span[@name=articlenum]').text();
		var artcount = parseInt($(this).find('input[@name=elt_count]').val());
		var product = getProductByArtnum(artnum);
		var ptype   = product.attr('type');
		//console.log("produkt type: " + ptype);
		var fac = parseFloat(ProductFactors[ptype][getProductFactorIndex(artcount)]);
		var pri = parseFloat(product.find('price').text());
		var psp = (pri*fac).toFixed(2); // psp: Product Single Price
		var ptp = parseFloat(psp)*parseFloat(artcount); // ptp: Product Total Price; (Single Price) * (Count) from input

		TotalTextilePrice += ptp;
 		TotalTextileCount += artcount;

 		//dbg("\tProdukt:" + product.find('name').text());
		//dbg("\t\tAnzahl " + artcount);
 		//dbg("\t\tFaktor " + fac);
 		//dbg("\t\tEK " + pri + "€");
		//dbg("\t\tTextil faktorisiert " + psp + "€");
 		//dbg("\t\tTextil Gesamt " +  ptp + "€");
	});

	TotalTextilePrice = TotalTextilePrice.toFixed(2);
	TotalTextilePrice  = TotalTextilePrice.replace(/^[0]+/g,"");

	//dbg("Textilien Gesamt: " + TotalTextilePrice + " €");
	//dbg("Textilien Anzahl: " + TotalTextileCount);
	//dbg("\n");

	/***************************/
	var TotalPrintPriceFront = 0.0;
	var TotalPrintPriceBack  = 0.0;
	var singlesetupcosts = SetupPrice+FilmSetupPrice;

	//dbg("\n\nDruck:");
	if (PrintColorCountFront > 0) {
		var bpp_f = parseFloat(PrintColorPriceList[getPrintFactorIndex(TotalTextileCount)][PrintColorCountFront]);
		var pf_f  = parseFloat(PrintColorPriceList[getPrintFactorIndex(TotalTextileCount)]['factor']);
		var bfp_f = bpp_f * pf_f;
		var SetupPriceFront  = parseFloat(PrintColorCountFront * singlesetupcosts);
		TotalPrintPriceFront = parseFloat(bfp_f * TotalTextileCount)+SetupPriceFront;

		//dbg("\tFront Druck: ");
		//dbg("\t  Druckfarben: " + PrintColorCountFront);
		//dbg("\t  EK: "+TotalTextileCount+" Textilien mit "+PrintColorCountFront+" Druckfarben " + bpp_f.toFixed(2) + "€");
		//dbg("\t  Faktor: "+ pf_f);
		//dbg("\t  Einzelpreis: " + bfp_f.toFixed(2) + "€");
		//dbg("\t  Einrichtung: ("+PrintColorCountFront+"*"+singlesetupcosts+") " + SetupPriceFront);
		//dbg("\t  Gesamt: " + TotalPrintPriceFront.toFixed(2) + "€");
	}

	if (PrintColorCountBack > 0) {
		var bpp_b = parseFloat(PrintColorPriceList[getPrintFactorIndex(TotalTextileCount)][PrintColorCountBack]);
		var pf_b  = parseFloat(PrintColorPriceList[getPrintFactorIndex(TotalTextileCount)]['factor']);
		var bfp_b = bpp_b * pf_b;
		var SetupPriceBack  = parseFloat(PrintColorCountBack * singlesetupcosts);
		TotalPrintPriceBack = parseFloat(bfp_b * TotalTextileCount)+SetupPriceBack;

		//dbg("\tBack Druck: ");
		//dbg("\t  Druckfarben: " + PrintColorCountBack);
		//dbg("\t  EK: "+TotalTextileCount+" Textilien mit "+PrintColorCountBack+" Druckfarben " + bpp_b.toFixed(2) + "€");
		//dbg("\t  Faktor: "+ pf_b);
		//dbg("\t  Einzelpreis: " + bfp_b.toFixed(2) + "€");
		//dbg("\t  Einrichtung: ("+PrintColorCountBack+"*"+singlesetupcosts+") " + SetupPriceBack);
		//dbg("\t  Gesamt: " + TotalPrintPriceBack.toFixed(2) + "€");
	}

	TotalPrintPrice = parseFloat(TotalPrintPriceFront) + parseFloat(TotalPrintPriceBack);
	//dbg("\n\tGesamt Druck Kosten: " + TotalPrintPrice.toFixed(2) + " €");
	//dbg("\n");
	/**********************************/

	// -----------  Total (Overall) Calculations -----------
	TotalCosts = 0.0;
	TotalCosts += parseFloat(TotalTextilePrice);
	TotalCosts += parseFloat(TotalPrintPrice);
	TotalCosts = TotalCosts.toFixed(2);
	TotalMwSt   = parseFloat(TotalCosts*(0.19)).toFixed(2);
	TotalCostsWithMwSt = parseFloat(TotalCosts) + parseFloat(TotalMwSt);
	TotalCostsWithMwSt = TotalCostsWithMwSt.toFixed(2);
	showResults();

	//dbg("\n\n");
	//dbg("Gesamt Kosten (Textilien + Druck + Einrichtung)*1.19 (MwSt.)")
	//dbg("Gesamt Preis: " + TotalCosts + " (MwSt: " + TotalMwSt + "€)" );
	//dbg("Gesamt Preis (inkl. MwSt.): " + TotalCostsWithMwSt );
	//dbg("-----------------\n\n\n");
}

/** Formats a given Price nicely. This Function supposes that the given price is a floating Point
 * Value with a fixed format to 2. (e.g. toFixed(2)). It then just splits the string an add's
 * some chichi to the number. Which is remove the . for the cents and add a , instead. Furthermore
 * '.' are inserted when there are thousands.
 * e.g.: 1234.99 becomes 1.234,99
 */
function formatPrice(price){
	var i = price.indexOf(".");
	var nk = price.substr(i+1, price.length );
	var vk = price.substring(0, i);
	var l = vk.length;
	if (l<4) {
	} else if (l==4) {
		vk = vk.substring(0,1) + "." + vk.substring(1,vk.length)
	} else if (l==5) {
		vk = vk.substring(0,2) + "." + vk.substring(2,vk.length)
	} else if (l==6) {
		vk = vk.substring(0,3) + "." + vk.substring(3,vk.length)
	}
	return vk + "," + nk;
}

/**
 */
function showEmptyBasket(){
	$('#Basket').html('<span name="EmptyBasket">Keine Artikel gewählt</span>');
}

/**
 */
function showDummyResults() {
	$('#ResultsTitle').html("Ihr St&#252;ckpreis");
	var sp = formatPrice(parseFloat(0.0).toFixed(2));
	$('#SinglePrice').html(sp + " €");
	var tcwm = formatPrice(parseFloat(0.0).toFixed(2));
	$('#Price').html("Gesamtbetrag: " + tcwm + " €");
	var tc = formatPrice(parseFloat(0.0).toFixed(2));
	var tm = formatPrice(parseFloat(0.0).toFixed(2));
	$('#PriceExtra').html( '(Netto:' +  tc + ' € zzgl. ' + tm + ' € MwSt.)');
}

/** Show/add the current Price in/to the html.
 */
function showResults() {
	var c = $('.BasketElt').length;
	if (c>1)
		$('#ResultsTitle').html("Durchschnitts-St&#252;ckpreis");
	else
		$('#ResultsTitle').html("Ihr St&#252;ckpreis");
	var s = parseFloat(TotalCostsWithMwSt).toFixed(2) / TotalTextileCount;
	var sp = formatPrice(parseFloat(s).toFixed(2));
	$('#SinglePrice').html(sp + " €");
	var tcwm = formatPrice(parseFloat(TotalCostsWithMwSt).toFixed(2));
	$('#Price').html("Gesamtbetrag: " + tcwm + " €");
	var tc = formatPrice(parseFloat(TotalCosts).toFixed(2));
	var tm = formatPrice(parseFloat(TotalMwSt).toFixed(2));
	$('#PriceExtra').html( '(Netto: ' +  tc + ' € zzgl. ' + tm + ' € MwSt.)');

}

function togglePrintColorSelection(checked, container) {
    if (checked) { $(container).attr('disabled', false); printColorCountChanged();}
    else { $(container).attr('disabled', true); printColorCountChanged(); }
}

function isProductInBasket(num) {
	var found = false;
	$('.BasketElt > span[@name="articlenum"]' ).each(function(){
		if($(this).text() == num) {
			found = true;
		}
	});
	return found;
}

function addActiveProductToBasket() {
	//dbg("addActiveProductToBasket()");
	var productcount = parseInt(20);

	if($('span[@name=EmptyBasket]').length > 0)
		$('span[@name=EmptyBasket]').remove();

	if (productcount <= 0 || isNaN(productcount)) { err('COUNTTOOLOW'); return; }
	if (productcount > 10000) { err('COUNTTOOHIGH'); return; }
	if ($('.active').length == 0) { err('NOPRODSELECTED'); return; }

	var x = $('.active > span[@name="artnum"]').text();
	var inb = isProductInBasket(x);
	if (inb) { err('ALREADYSELECTED'); return; }

	$('.active').each(function(){ createBasketEltHtml($(this), productcount); });

	// Call textileCountChanged so it gets newly calculated and bind change event of input elts.
	textileCountChanged();
	$('input[@name="elt_count"]').change(function(){
		textileCountChanged(); })
}

var XMLPrices;
var XMLProducts;
var ProductFactors = new Array();
var SetupPrice=0.0;
var FilmSetupPrice=0.0;
var PrintColorPriceList = new Array();

var TotalTextileCount=0;
var TotalTextilePrice=0.0;

//var TotalPrintColorCount=0;
var PrintColorCountFront=0;
var PrintColorCountBack=0;

var TotalPrintPrice=0.0;

var TotalCosts=0.0;
var TotalMwSt=0.0;
var TotalCostsWithMwSt = 0.0;

var PrintColorError = false;

$(document).ready(function() {

	// $('input[@name="hasPrintColorFront"]').each(function(){ this.checked = false; });
	// $('input[@name="hasPrintColorBack"]').each(function(){ this.checked = false; });
	$('select[name="PrintColorFront"]').val("1");
	$('select[name="PrintColorBack"]').val("1");

	loadPrices();
	loadProducts();

    $("#CategoryButtonsContainer > button").click(function() {
        // TODO: Remove this ugliness and write a nice selector to only select bold elts
        $(".CatBtnActive").each(function() {
            $(this).removeClass('CatBtnActive');
        });
        //productSelectionChanged($(this).val());
        CategoryButtonClicked($(this).val());
        $(this).addClass('CatBtnActive');
    });

	$('#Products').change(function(){
		productSelectionChanged($(this).val()); });

	// Add Product to basket
 	$('button[@name=addproduct]').click(function(){
		addActiveProductToBasket(); });

    $('input[@name=hasPrintColorFront]').click(function(){
        togglePrintColorSelection($(this).is(':checked'), 'select[@name=PrintColorFront]');
    });

    $('input[@name=hasPrintColorBack]').click(function(){
        togglePrintColorSelection($(this).is(':checked'), 'select[@name=PrintColorBack]');
    });

	$('select[@name=PrintColorFront]').change(function(){
		printColorCountChanged(); });

	$('select[@name=PrintColorBack]').change(function(){
		printColorCountChanged(); });

	$('select[@name=TextileColor]').change(function(){
		printColorCountChanged(); });

	showDummyResults();
	showEmptyBasket();
});


/*
    $('html').animate({scrollTop:offtop-120}, 'slow');
    $('body').animate({scrollTop:offtop-120}, 'slow');
    return false;

    $('html').animate({scrollTop:0}, 'slow');
    $('body').animate({scrollTop:0}, 'slow');
    $('#BopContainer').hide();
    $('#BopFormProcessing').show();
*/
















