//<PRICE CLASS>
function Price(cfg) {
	this.packages				= cfg.packages;
	this.targets				= (cfg.targets) ? cfg.targets : null;
	this.currencySuffix			= cfg.currencySuffix ? cfg.currencySuffix : 'kr';
	this.minimumNumOfPackages	= cfg.minimumNumOfPackages ? cfg.minimumNumOfPackages : 1;
	this.VAT					= cfg.VAT ? cfg.VAT : 0;
	this.minPrice				= cfg.minPrice ? cfg.minPrice : .08;
	this.maxPrice				= cfg.maxPrice ? cfg.maxPrice : .085;

	//Define functions
	this.setParam				= setParam;
	this.setParamPackage		= setParamPackage;
	this.setError				= setError;
	this.alertError				= alertError;
	this.calcPrice				= calcPrice;
	this.calcRegularPrice		= calcRegularPrice;
	this.showPrice				= showPrice;
	this.displayPaperInfo		= displayPaperInfo;
	this.calcPricePerShow		= calcPricePerShow;
	this.getReaders				= getReaders;
	this.printPackagesInputs	= printPackagesInputs;
	this.checkForPriceErr		= checkForPriceErr;

	//Define variables
	this.instanceName			= cfg.instanceName;
	this.moduleName				= '';
	this.placement				= null;
	this.priceChange			= 0;
	this.readers				= 0;
	this.maxReaders				= this.getReaders();
	this.minReaders				= this.getReaders(this.minimumNumOfPackages);
	this.price					= 0;
	this.sumRegularPrice		= 0;
	this.regularPrice			= 0;
	this.numOfPackages			= 0;
	this.numOfModules			= 0;
	this.dates					= [];
	this.err					= '';
	this.errlog					= '';
	this.priceErr				= null;

	//Init
	this.printPackagesInputs();
}

function getReaders(stop) {
	stop = (stop !== undefined) ? stop : this.packages.length;

	var arr = new Array();
	for (var i in this.packages)
		arr.push(this.packages[i][2]);
	arr.sort(numericSort);

	var res = 0;
	for (var i = 0; i < arr.length; i++)
		if (i < stop)
			res += arr[i];
		else
			break;
	return res;
}

function calcPricePerShow() {
	var average = (this.maxPrice - this.minPrice) / (this.maxReaders - this.minReaders);
	return this.maxPrice - ((this.readers - this.minReaders) * average);
}

function calcRegularPrice() {
	return this.sumRegularPrice / 4;
}

function calcPrice() {
	var pricePerShow = this.calcPricePerShow();
	res = this.readers * pricePerShow / 4;
	res *= 1 + this.VAT / 100;
	this.price = Math.round(res);

	this.regularPrice = this.calcRegularPrice();

	this.showPrice();
}

function checkForPriceErr() {
	this.priceErr = null;

	if (this.minimumNumOfPackages > this.numOfPackages) {
		setDisplay(this.targets.result_table, 'none');
		this.priceErr = 'Du måste fylla i minst ' + this.minimumNumOfPackages + ' paket för pris.';
	}
	else {
		setDisplay(this.targets.result_table, 'block');
	}
}

function showPrice() {
	this.checkForPriceErr();
	if (this.priceErr) {
		setDisplay(this.targets.priceInfo, 'none');
		setDisplay(this.targets.numOfVisitorsHolder, 'none');
		this.targets.price.className = 'Warning';
		this.targets.VAT.innerHTML = 
		this.targets.numOfVisitors.innerHTML = '';
		
		this.targets.price_error.innerHTML = this.priceErr;
		setDisplay(this.targets.price_error, 'block');
	}
	else {
		setDisplay(this.targets.price_error, 'none');
	
		this.targets.price.className = 'PriceResultPrice';
		priceValue = formatNum(Math.round(this.price / 100) * 100) + ' ' + this.currencySuffix;
	
		if (priceValue != this.targets.price.innerHTML) {
			fadeObj(this.targets.price);
			this.targets.price.innerHTML = priceValue;
			fadeObj(this.targets.VAT);
		}
	
		this.targets.VAT.innerHTML = this.VAT ? 'inkl. ' + this.VAT + '% moms' : 'exkl. moms';
	
		this.targets.regularPrice.innerHTML = formatNum(Math.round(this.regularPrice / 100) * 100) + ' ' + this.currencySuffix;
		
		setDisplay(this.targets.numOfVisitorsHolder, 'block');
		this.targets.numOfVisitors.innerHTML = formatNum(Math.round((this.readers) / 1000) * 1000);
	}
}

function displayPaperInfo(i) {
	this.targets.selected_papers.innerHTML = '<h1>Webbsidor i '+ this.packages[i][1] +'</h1><div class="readers">Besök per vecka: '+ formatNum(Math.round((this.packages[i][2]) / 100) * 100) + ' besök</div>';

	for(var m = 0; m < this.packages[i][5].length; m++)
		this.targets.selected_papers.innerHTML += '- <a href="'+ this.packages[i][5][m].url +'" target="' + this.packages[i][5][m].target + '">'+ this.packages[i][5][m].name +'</a><br />';
	fadeObj(this.targets.selected_papers, undefined, 'block');
}

function setParam(paramName, paramValue, operator, valueFunction) {
	operator = operator ? operator : '';
	valueFunction = valueFunction ? valueFunction : 'Number';
	eval('this.' + paramName + operator + '=' + valueFunction + '(paramValue);');
}

function setParamPackage(packageNum, sel) {
	var curPackage = this.packages[packageNum];
	aPos = [1, '+'];
	aNeg = [0, '-'];
	sel = (sel == null) ? aPos : (!sel) ? aNeg : aPos; //If sel is null = initializing.

	eval('this.numOfPackages' + sel[1] + sel[1] +';'); //Add or subtract from selected packages
	this.setParam('packages[' + packageNum + '][4]', sel[0]); //Set selected or not
	this.setParam('readers', curPackage[2], sel[1]); //Add or subtract from readers
	this.setParam('sumRegularPrice', curPackage[3], sel[1]); //Add or subtract from sumRegularPrice
	this.calcPrice();
}

function printPackagesInputs() {
	for (i = 0; i < this.packages.length; i++) {
		if (this.packages[i][4]) {
			checked = ['checked'];
			this.setParamPackage(i);
		}
		else
			checked = [];
		
		html = '';
		html += createHtmlTag('input', [['type', 'checkbox'], ['name', this.instanceName + 'Package' + i], ['id', this.instanceName + 'Package' + i], ['onChange', this.instanceName + '.setParamPackage(' + i + ', this.checked)'], ['onClick', 'this.blur()'], checked], null);
		html += createHtmlTag('label', [['class', 'PackageName'], ['for', this.instanceName + 'Package' + i], ['onMouseOver', this.instanceName + '.displayPaperInfo('+ i +');return false;']], String(this.packages[i][1]));
		
		this.targets.packages.innerHTML += createHtmlTag('div', [['class', 'row']], html);
		
	}

	// reset error message
	this.targets.price_error.innerHTML = 'Du måste fylla i minst ' + this.minimumNumOfPackages + ' paket för pris.';
}

function setError(errMsg) {
	this.err = errMsg;
	this.errlog += errMsg + '\n';
}

function alertError() {
	alert(this.err);
}

// </PRICE CLASS>



function setDisplay(obj, disp) {
	if (obj)
		obj.style.display = disp;
}

function setInnerHTML(obj, content) {
	if (obj)
		obj.innerHTML = content;
}

function setOpacity(opacObj, value) {
	if (opacObj) {
		opacObj.style.opacity = value / 10;
		opacObj.style.filter = 'alpha(opacity=' + value * 10 + ')';
	}
}

function fadeObj(fdeObj, speed, display) {
	speed = (speed !== undefined) ? speed : 30;
	display = (display !== undefined) ? display : 'inline';

	setOpacity(fdeObj, 0);
	fdeObj.style.display = display;
	i = 0;
	while (i < 10)
		setTimeout(setOpacity, speed * i++, fdeObj, i);
}

function createHtmlTag(elType, attributes, html) {
	r = '<' + elType;
	for (attribute in attributes)
		if (attributes[attribute].length == 2)
			r += ' ' + attributes[attribute][0] + '="' + attributes[attribute][1] + '"';
		else if (attributes[attribute].length == 1)
			r += ' ' + attributes[attribute][0];
	if (html)
		r += '>' + html + '</' + elType + '>';
	else
		r += ' />';

	return r;
}

function numericSort(a, b) {
	a = parseFloat(a);
	b = parseFloat(b);
	if(a > b)
		return 1;
	if(a < b)
		return -1;
	return 0
}

function formatNum(number) {
    number = String(number);
    if (number.length > 3) {
        var mod = number.length%3;
        var output = (mod > 0 ? (number.substring(0,mod)) : '');
        for (i=0 ; i < Math.floor(number.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= number.substring(mod+3*i,mod+3*i+3);
            else
                output+= ' ' + number.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
    else return number;
}


