// make console.log "fix" for browsers not supporting the Firebug console object
try {
	console.log('init console... done');
	console.clear();
}
catch (e) {
	// below is a list of all Firebug console functions for version 1.9.1.
	// add more functions if Firebug is updated and they are needed.
	console = {
		log: function () { },
		debug: function () { },
		info: function () { },
		warn: function () { },
		error: function () { },
		assert: function () { },
		clear: function () { },
		dir: function () { },
		dirxml: function () { },
		trace: function () { },
		group: function () { },
		groupEnd: function () { },
		time: function () { },
		timeEnd: function () { },
		profile: function () { },
		profileEnd: function () { },
		count: function () { },
		exception: function () { },
		table: function () { }
	}
}


/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
js('/files/javascript/jquery.mousewheel.min.js');
js('/files/javascript/jScrollPane-1.2.3.min.js');
js('/files/javascript/jQuery.autocomplete.min.js');


/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function(){
	validateForms();
	toggleMainMenu();
	toggleAreaMenu();
	activateAjaxShopping();
	/*autocompletePostalCode();*/
	productlistImage();
	postPolls();
	quizWizzard();
	tracktrace();
	feedReader();
	changeProductImage();
	flashLoad();
	openPopups();
	showInlineHelp();
	//variantSelection();
	scrollMainMenu();
	createReportScreen();
	toggleImageList();
	
	activateReportLineAutocomplete();
	
	$('#jsSearch').focus(function(){ $(this).select(); });
	
});


/*
 * set autocomplete on reportLines
 *******************************************/
function activateReportLineAutocomplete(){
	if ($('#report').size() > 0) {
		$('#report').find('.crop select:visible').hide().after('<input class="autocomplete" type="text" value="' + $('#report').find('.crop select:eq(0)').find('option:first').text() + '"/>').next('.autocomplete').one('focus', function () {
			$(this).val('').click();
		}).focus(function () {
			$(this).click();
		}).autocomplete(groups, {
			minChars: 0,
			matchContains: true,
			max: 1000
		}).result(function (e, data, formatted) {
			varietyAutocomplete($(this), true, data, formatted);
		}).blur(function () {
			if ($.inArray($(this).val(), groups) == -1) {
				if ($(this).closest('#reportNonsap').length > 0) {
					//her må man godt skrive noget der ikke er på listen
					var extraOption = '<option value="jsAdded">' + $(this).val() + '</option>';
					$(this).parent().find('select').append(extraOption).find('option:last').select();
					$(this).parent().find('select').change();
				} else {
					$(this).val('').prev('select').val('');
					//fjern muligheder
				}
			}
		});


		$('#report').find('.variety select:visible').hide().after('<input class="autocomplete" type="text" value="' + $('#report').find('.variety select:eq(0)').find('option:first').text() + '"/>').next('.autocomplete');

		//Fyld indhold i rapportperioderne
		if ($('#jsReportperiod option').length == 0) {
			var options = '<option value=""></option>';
			var today = new Date();
			var thisYear = today.getFullYear() - 1;
			var thisQuarter = Math.floor((today.getMonth() + 1) / 4) + 1;
			var lastQuarterSet = false;
			//fix 4/1-2012: Vis hele året
			thisQuarter = 4;
			
			for (var i=0; i<=1; i++) {
				var period = 'Poinsettias ' + (thisYear - i);
				options += '<option value="' + period + '">' + period + '</option>'
			}
			
			thisQuarter = thisQuarter > 4 ? 4 : thisQuarter;
			for (var i=thisQuarter; i>=1; i--) {
				var period = 'Spring crops ';
				
				if (i >= 3 && !lastQuarterSet) {
					 period += '3rd and 4th';
				} else if (i == 2) {
					 period += '2nd';
				} else if (i == 1) {
					 period += '1st';
				}
				
				if (i <= 2 || !lastQuarterSet) {
					period +=  ' quarter ' + thisYear;
					options += '<option value="' + period + '">' + period + '</option>';
				}
				
				lastQuarterSet = i >= 3;
			}
			
			$('#jsReportperiod').append(options);
		}
	}
	
	$('#reportDeduction .supplier input')
		.focus(function(){ $(this).select(); })
		.focus(function(){ $(this).select(); })
		.change(function(){
			//klargør varieties
			$(this).closest('.reportLine').find('.varietyDeduction input:visible')
				.autocomplete(arrayFromSelect('#reportDeduction .varietyDeduction:first option'), {
					minChars: 0,
					matchContains: true,
					max: 1000
				}).focus(function(){
					$(this).click();
				}).focus()
				.result(function(e, data, formatted){
					var arrayIndex = $.inArray(formatted, arrayFromSelect('#reportDeduction .varietyDeduction:first option'));
					$(this).closest('.reportLine').find('.varietyDeduction option').eq(arrayIndex+1).attr('selected', 'selected').closest('select').change();
				});
		});
	/*
	$('#report').find('.supplier select:visible').hide().after('<input class="autocomplete" type="text" value="' + $('#report').find('.supplier select:eq(0)').find('option:first').text() + '"/>').next('.autocomplete').one('focus', function(){
		$(this).val('').click();
	}).focus(function(){
		$(this).click();
	}).autocomplete(arrayFromSelect('#reportDeduction .supplier:first option'), {
		minChars: 0,
		matchContains: true,
		max: 1000
	}).result(function(e, data, formatted){
		var arrayIndex = $.inArray(formatted, arrayFromSelect('#reportDeduction .supplier:first option'));
		$(this).closest('.reportLine').find('.supplier option').eq(arrayIndex+1).attr('selected', 'selected').closest('select').change();
		
		$(this).closest('.reportLine').find('.varietyDeduction input:visible').autocomplete(arrayFromSelect('#reportDeduction .varietyDeduction:first option'), {
			minChars: 0,
			matchContains: true,
			max: 1000
		}).focus(function(){
			$(this).click();
		}).focus()
		.result(function(e, data, formatted){
			var arrayIndex = $.inArray(formatted, arrayFromSelect('#reportDeduction .varietyDeduction:first option'));
			$(this).closest('.reportLine').find('.varietyDeduction option').eq(arrayIndex+1).attr('selected', 'selected').closest('select').change();
		});
	});
	*/
	
	$('#report').find('.varietyDeduction select:visible').hide().after('<input class="autocomplete" type="text" value="' + $('#report').find('.varietyDeduction select:eq(0)').find('option:first').text() + '"/>').next('.autocomplete');
}



/*
 * PLA menu modified
 *******************************************/
function toggleMainMenu(){

	$('#mainMenu > ul > li').hoverIntent(function(){ 
		$('ul:first',this).slideDown('fast');
	},function(){ // on mouseout
		$('ul:first',this).slideUp('slow');
	});
	$('#mainMenu li li').hoverIntent({
		timeout: 300,
		over: function(){ 
			var count = $('ul:first li',this).size();
			var originalcount = count;
			if (count > 10) {
				count = 10;
			}
			var menuheight = count * 30;
			var containerheight = menuheight + 1 + 22;
			var scrolloffset = menuheight + 1 + 11;
			
			if (originalcount < 11) {
				$('.scrollfix', this).css('height',menuheight+'px').css('width','222px').parent().css('top','-37px').find('.jsScrolldown, .jsScrollup').css('display','none');
				$('div:first, ul:first',this).animate({width: 'show'}, 200).find('ul:first').css('height',menuheight + 'px').css('width','222px');
			} else {
				$('div:first, ul:first',this).animate({width: 'show'}, 200).find('ul:first').css('height',menuheight + 'px').css('width','222px').jScrollPane({scrollbarWidth:0, scrollbarMargin:0, animateTo:true});
			}
			
			
		},
		out: function(){ // on mouseout
			$('div:first, ul:first',this).animate({width: 'hide'}, 200,function(){
				$(this).find('ul:first').jScrollPaneRemove();
			});
		}
	});

}

function scrollMainMenu() {
	$('.jsScrolldown').click(function(){
		var $scroller = $(this).parent().find('ul');
		$scroller[0].scrollBy(93);
	});
	$('.jsScrollup').click(function(){
		var $scroller = $(this).parent().find('ul');
		$scroller[0].scrollBy(-93);
	});
}


/*
 * PLA Reporting
 **************************************************/
 
 function createReportScreen(){
//log_debug('createReportScreen');
	//Focusing on quantity-fields select text.
	$('.quantity input').focus(function(){$(this).select()});
	
	//Suppress enter-key
	$(".tReport form").live("keypress", function(e) {
		if (e.keyCode == 13) {
			return false;
		}
	});
	
// Report Varieties only
	//selectbox change events
	$('#reportVarieties .crop select').change(function(){
		var $this = $(this);
		var thisValue = $this.val();
		var varieties = '<option value="">Choose variety</option>';
		
		resetVariety($this, varieties);
		fillVarieties($this);
		
		//create new line if lowest
		if ($('#report #reportVarieties .crop select').index($this) >= ($('#report #reportVarieties .crop select').size() -2)) {
			newReportLine('#reportVarieties');
			activateReportLineAutocomplete();
		}
		
	});
	
	//selectbox2 change
	$('#reportVarieties .variety select').change(function () {
		var $this = $(this);

		
		resetQuantity($this);

		if ($this.val() != '') {
			$this.closest('.reportLine').find('.quantity input').removeAttr('readonly').addClass('open').focus().select();

			var nextLineSelect = $($this.closest('.reportLine').find('.crop select'));
			changeNextLine(nextLineSelect);
		}


		//show poinsettia deductions
		if ($this.closest('.reportLine').find('.crop select').val() == poin & $('#reportDeduction .reportLine').size() < 2) {

			$('#reportDeduction').fadeIn('slow');

			//add all poinsettia varieties
			$.each(report[poin], function (i, v) {
				var ii = i + 1;
				if (ii < report[poin].length) {
					$('#reportDeduction .reportLine .varietyDeduction select').append('<option value="' + report[poin][ii][0] + '">' + report[poin][ii][1] + '</option>');
				}
			});

			newReportLine('#reportDeduction');
			activateReportLineAutocomplete();
		}

		//add poinsettia variety if one is selected
		/*
		if ($this.closest('.reportLine').find('.crop select').val() == '7') {
		var productid = $this.val();
		var productname = $this.find('option[value="' + productid + '"]').html();
		var found = false;

		$('#reportDeduction .varietyDeduction select:first option').each(function(){
		if ($(this).val() == productid) { found=true; }
		});
			
		if(found) {
		//crop already here, don't insert
		} else {
		$('#reportDeduction .varietyDeduction select').append('<option value="' + productid + '">' + productname + '</option>');
		}
		}
		*/
	});
	
//Non SAP only
	//select box
	$('#reportNonsap .crop select').change(function(){
		var $this = $(this);
		
		if ($this.val() != '') {
			$this.closest('.reportLine').find('.name input').removeAttr('readonly').focus().select();
		}
		
		//create new line if lowest
		if ($('#report #reportNonsap .crop select').index($this) >= ($('#report #reportNonsap .crop select').size() -2)) {
			newReportLine('#reportNonsap');
			activateReportLineAutocomplete();
		}
	});
	
	//write name
	$('#reportNonsap .name input').live('change',function(){
		var $this = $(this);
		//create new line if lowest
		if ($this.val() != '') {
			$this.closest('.reportLine').find('.quantity input').removeAttr('readonly').removeAttr('disabled').addClass('open');
			$this.closest('.reportLine').find('.quantity input').focus().select();
		}
	});
	$('#reportNonsap .quantity input').live('focus',function(){
		$(this).removeAttr('readonly').removeAttr('disabled').addClass('open').select();
		
	});
	
//Deductions only
	//selectbox 1 change events
	$('#reportDeduction .supplier input').change(function(){
		
		//create new line if lowest
		if ($('#report #reportDeduction .supplier input').index($(this)) >= ($('#report #reportDeduction .supplier input').size() -2)) {
			newReportLine('#reportDeduction');
			activateReportLineAutocomplete();
		}
	});
	
	$('#reportDeduction .varietyDeduction select').change(function(){
		var $this = $(this);
		if ($this.val() != '') {
			$this.closest('.reportLine').find('.quantity input').removeAttr('readonly').addClass('open').focus().select();
		}
	});

	
//General function
	//insert new lines
	for(var i=1;i<10;i++) {
		newReportLine('#reportVarieties');
	}
	newReportLine('#reportNonsap');
	
	//quantity number control
	$('.quantity input, .writetotal input').keydown(function(e){
		var $this = $(this);
		var key = e.charCode || e.keyCode || 0;
		//allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
		var isNumber = (
			key == 8 || 
			key == 9 ||
			key == 46 ||
			(key >= 37 && key <= 40) ||
			(key >= 48 && key <= 57) ||
			(key >= 96 && key <= 105));
		
		return isNumber;
	});
	$('.quantity input, .writetotal input').keyup(function(){
		var $this =  $(this);
		priceRecalc();	
		$(this).val(addThousands(0,removeThousands($this.val())));
	});
	
	//delete line
	$('#report .reportDelete').live('click', function(){
		$(this).closest('.reportLine').fadeOut('slow', function(){ 
			$(this).remove();
			priceRecalc();
			updateTotalQuantities();
		});
	});
	
	//report no production
	$('#reportNothing input').change(function(){
		if($(this).attr('checked') == true) {
			$('#reportVarieties, #reportNonsap, .reportTotal').fadeOut('slow', function(){ $(this).remove();});
		} else {
			window.location.reload();
		}
	});
	
	//Login-screen
	if ($('#customerlogin').size() > 0) {
		$('#customerlogin').modal({containerId: 'login-container'});
	
		$('#customerlogin #customerid, #customerlogin #password')
			.focus(function(){
				var $this = $(this);
				$this.css('background-image', 'none').select();
			})
			.keyup(function(){
				var $this = $(this);
				$this.css('background-image', 'none');
			})
			.focusout(function(){
				inputBG(this);
			})
			.load(function(){
				inputBG(this);
			});
		
		inputBG($('#customerlogin #customerid').get(0));
		inputBG($('#customerlogin #password').get(0));
	}
	
	//Create order
	$('#jsSubmit').click(function(){		
		//valider
		var errors = new Array();
		if ($('#jsReportperiod').val() == '') {
			errors.push('No report period is selected.');
		}
		if (!($('#reportNothing input:first').attr('checked') == true) && $('.quantity input[value!=Quantity]').filter('.quantity input[value!=0]').length == 0) {
			errors.push('You must either check the "No produkction" box or report at least one crop.');
		}
		//check deductions
		if ($('#reportDeduction:visible').length > 0) {
			var deductionErrors = new Array();
			var deductionsChecked = new Array();
			
			$('#reportDeduction .quantity:visible').each(function(){
				var t = $(this);
				var thisVariety = t.closest('.reportLine').find('.varietyDeduction select').val();
				var thisVarietyName = t.closest('.reportLine').find('.varietyDeduction select option:selected').html();
				var alreadyChecked = '#' + deductionsChecked.join('#') + '#';
				
				if (deductionsChecked.length = 0 || alreadyChecked.indexOf('#' + thisVariety + '#') < 0 ) {
					deductionsChecked.push(thisVariety);
					
					var totalThisVarietyDeduction = 0;
					$('.varietyDeduction select').each(function(){
						var t2 = $(this);
						if (t2.val() == thisVariety) {
							var thisVal = removeThousands(t2.closest('.reportLine').find('.quantity input').val());
							thisVal = isNaN(thisVal) ? 0 : thisVal;
							totalThisVarietyDeduction += parseInt(thisVal);
						}
					});
					
					var totalThisVarietyReported = 0;
					$('#reportVarieties .variety select').each(function(){
						var t2 = $(this);
						if (t2.val() == thisVariety) {
							var thisVal = removeThousands(t2.closest('.reportLine').find('.quantity input').val());
							thisVal = isNaN(thisVal) ? 0 : thisVal;
							totalThisVarietyReported += parseInt(thisVal);
						}
					});
					if (totalThisVarietyDeduction > totalThisVarietyReported) {
						deductionErrors.push(thisVarietyName);
					}
				}
			});
			
			if (deductionErrors.length > 0) {
				errors.push('You\'ve deducted more cuttings than you have reported for the following varieties: ' + deductionErrors.join(', '));
			}
		}
		
		if (errors.length > 0) {
			var errorList = 'Please correct the following issues before submitting your report.\n\n'
			errorList += errors.join('\n')
			alert(errorList);
			return false;
		} else {
			
			//spørg om de vil fortsætte
			var bContinue = confirm('Please check your report before submitting. After you submit, the report can only be changed by contacting PLA International.\nAre you sure you want to continue?');
			
			if (!bContinue) {
				return false;
			}
			
			var strData;
			var i = 1;
			strData = '_function=BatchUpdateBasket&_returnto=default.aspx&Remarks1=' + $('#jsReportperiod').val() + '&Remarks2=' + $('#jsComments').val();
			
			$('#jsReportwait div').appendTo('body').show();
			$('#jsReportwait img').appendTo('body').show();
			
			if($('#reportNothing input:first').attr('checked') == true) {
				strData += '&productid=nonsap0__1&quantitynonsap0__1=1&pricenonsap0__1=0&descriptionnonsap0__1=No production this period'; //skift ikke uden at ændre sys_UpdateBasket
			} else {
				$('#report #reportVarieties .quantity input[value!="Quantity"]').each(function(){
					var $inp = $(this);
					var quantity = removeThousands($inp.val());
					if (!(isNaN(quantity)) && quantity > 0) {
						var productid = $inp.parent().parent().find('.variety select').val() + '__' + i;
						i = i+1;
						strData += '&productid=' + productid;
						strData += '&quantity' + productid + '=' + quantity;
					}
				});
				
				$('#report #reportNonsap .quantity input[value!="Quantity"]:visible').each(function(index){
					var $this = $(this).closest(".reportLine");
					var price = '0';
					var quantity = removeThousands($this.find('.quantity input:first').val());
					var description = $this.find('.crop input.autocomplete').val()  + ': ' + $this.find('.name input:first').val();
					var productid = 'nonsap' + index + '__' + i;
						i = i+1;
					if (!(isNaN(quantity)) && quantity > 0) {
						strData += '&productid=' + productid;
						strData += '&quantity' + productid + '=' + quantity;
						strData += '&description' + productid + '=' + description;
						strData += '&price' + productid + '=' + price;
					}
				});
				
				$('#report #reportDeduction .quantity input[value!="Quantity"]').each(function(){
					var $this = $(this).closest(".reportLine");
					var price = '0';
					var quantity = removeThousands($this.find('.quantity input:first').val());
					var description = $this.find('.supplier input.autocomplete').val() + ': ' + $this.find('.varietyDeduction input.autocomplete').val();
					var productid = $this.find('.varietyDeduction select').val() + '__' + i;
						i = i+1;
					if (!(isNaN(quantity)) && quantity > 0) {
						strData += '&productid=' + productid;
						strData += '&description' + productid + '=' +  description;
						strData += '&quantity' + productid + '=-' + quantity;
					}
				});
			}
			
//log_debug(strData);

			$.ajax({
				url:'/post.aspx',
				type:'post',
				data: '_function=DELETEBASKETALL&_returnto=default.aspx',
				success: function(){
					$.ajax({
						url:'/post.aspx',
						type:'post',
						data: strData,
						success: function() {
							$('#jsEndreport').submit();
						},
						error:function(data){
						}
					});
				},
				error:function(data){
				}
			});
			return false;
		}
		
	});
	
	//Clear all
	$('#jsClear').click(function(){ window.location.reload();});
	
	//slet teksten når man klikker på feltet
	$('.ac_input').live('focus.test',function(){
		$(this).val('');
	});
	
	//klik på skift adgangskode
	$('.jsChangePassword').click(function(){
		$('#changePassword').modal();
	});
	$('#changePassword form').submit(function(){
		if ($('input[name=password]').val() != $('input[name=repeatpassword]').val() || $('input[name=password]').val() == '') {
			alert('The passwords aren\'t identical.');
			return false;
		}
	});
	
	//glemt adgangskode
	$('#jsForgottenpassword').click(function(e){
		e.preventDefault();
		$.modal.close();
		$('#forgottenPassword').modal();
	});
	
	//opdater samlede antal
	$('#report .reportArea .quantity input').live('change',function(){
		updateTotalQuantities();
	});
	$('#report .reportArea .quantity input').live('blur',function(){
		updateTotalQuantities();
	});
	
}
function updateTotalQuantities(t){
	
	$('.reportArea').each(function(){
		var t = $(this);
		var total = 0;
		var strTotal;
		var type = '';
		var negative = false;
		
		switch (t.attr('id')) {
			case 'reportVarieties':
				type = 'quantityCommercial';
				break;
			case 'reportNonsap':
				type = 'quantityNonSap';
				break;
			case 'reportDeduction':
				type = 'quantityDeductions';
				negative = true;
				break;
			default:
				type = ''
				break;
		}
		
		if (type != '') {
			t.find('.quantity:visible input').each(function(){
				var t2 = $(this);
				if (!isNaN(removeThousands(t2.val()))) {
					total = parseInt(total) + parseInt(removeThousands(t2.val()));
				}
			});
			if (negative) {
				total = total * (-1);
			}
			strTotal = addThousands(0,total);
			//fix bug
			strTotal = strTotal.indexOf(0) == 0 ? strTotal.substring(1) : strTotal;
			
			$('.' + type + ' input').val(strTotal);
		}
	
	});
	
	var totalReported = 0;
	$('.reportTotalQuantity div').each(function () {
		if ($(this).hasClass('quantityReported') == false) {
			var input = $(this).find('input');
			if (input.val() != '') {
				var thisval = removeThousands(input.val());
				totalReported = parseInt(totalReported) + parseInt(thisval);
			}
		}
	});
	$('.quantityReported input').val(addThousands(0,totalReported));
}

function varietyAutocomplete(t, trueSelect, data, formatted) {
	t = $(t);
	var arrayIndex = $.inArray(formatted, groups) + 1;
	t.prev('select').val(arrayIndex).change();
	
	var $varietyInput = t.closest('.reportLine').find('.variety select');
	
	var arrVarieties = '';
	var arrVarietyValues = '';
	var jqThis = $();
	

	$varietyInput.addClass('appliedAutocomplete').find('option:not(:first)').each(function (i) {
		jqThis = $(this);

		if (i != 0) {
			arrVarieties += '##';
			arrVarietyValues += '##';
		}
		arrVarieties += jqThis.text();
		arrVarietyValues += jqThis.val();
	});
	

	arrVarieties = arrVarieties.split('##');
	arrVarietyValues = arrVarietyValues.split('##');
	
	$varietyInput.filter('.appliedAutocomplete').next('input').remove();
	
	$varietyInput.hide().after('<input class="autocomplete" type="text"/>').next('.autocomplete').autocomplete(arrVarieties, {
		minChars: 0,
		matchContains: true,
		max: 1000
	}).result(function (e, data, formatted) {
		var varietyArrayIndex = $.inArray(formatted, arrVarieties);

		$(this).prev('select').val(arrVarietyValues[varietyArrayIndex]).change();
	}).blur(function () {
		if ($.inArray($(this).val(), arrVarieties) == -1) {
			$(this).val('').prev('select').val('');
		}
	}).focus(function () {
		$(this).click();
	}).each(function () {
		if (trueSelect) {
			$(this).focus();
		}
	});
	
}
function changeNextLine(t){
	//change next line to the same value
	var body = $('body');
	var thisValue = t.val();
	var next = t.closest('.reportLine').next('.reportLine').find('.crop');
	var nextTarget = next.find('select');
	if (nextTarget.val() == '') {
		next.find('select').val(thisValue).change();
		next.find('input').val(t.siblings('input').val()).change();
		
		resetVariety(nextTarget, '<option value="">Choose variety</option>');
		fillVarieties(nextTarget);
		varietyAutocomplete(nextTarget, false, [thisValue], thisValue);
	}
}
function fillVarieties(t) {
//log_debug('fillVarieties:');
//log_debug(t);
	var thisValue = t.val();
	var varieties = '<option value="">Choose variety</option>';
	
	if (thisValue != '') {
		for(var i = 1; i < report[thisValue].length; i++) {
			varieties = varieties + '<option value="' + report[thisValue][i][0] + '">' + report[thisValue][i][1]  + '</option>';
		}
		t.parent().parent().find('.variety select').removeAttr('readonly').html(varieties).focus();
	}
}

// Reporting support functions
function newReportLine(area){
//log_debug('newReportLine');
	$('#report ' + area + ' > .reportLine:first').clone(true).css('display', 'none').appendTo('#report ' + area).fadeIn('slow').find('select').val('');
	
	if (area == '#reportVarieties') {
		resetVariety($('#report > .reportLine:last .quantity input'),'');
	}
	if (area == '#reportNonsap') {
		resetNonsap($('#report #reportNonsap > .reportLine:last'),'');
	}
	
}
function priceRecalc() {
	
	var priceUnit, priceLine, priceTotal;
	var isNegative = false;
	priceTotal = 0;

	$.each($('#report div.quantity.jsCalculate input'), function(){
		var $this = $(this);
		var $thisline = $this.closest('.reportLine');
		var quantity = parseInt(removeThousands($this.val()));
		priceUnit = 0;
		priceLine = 0;
		
		isNegative = ($thisline.find('.varietyDeduction').size() == 1);
		
		if (isNaN(quantity)) {
			//Ikke et tal, beregn ikke på det
		} else {
			var groupPosition, productPosition 
		
			if (isNegative) { 
				groupPosition = poin;
				productPosition = $thisline.find('.varietyDeduction select').attr('selectedIndex');
				quantity = quantity * -1;
			} else {
				groupPosition = $thisline.find('.crop select').val();
				productPosition = $thisline.find('.variety select').attr('selectedIndex');
			}
			
			priceUnit = report[groupPosition][productPosition][2];
			priceLine = (priceUnit * quantity);
				
			priceTotal += priceLine;
			$thisline.find('.total').html(nicePrice(priceLine)).addClass('open');
		}
	});

	/* no longer needed - no price calculation done
	$.each($('#report #reportNonsap .writetotal input'), function(){
		var $this = $(this);
		var priceCustom = parseFloat(removeThousands($this.val()));
		if (isNaN(priceCustom)) {
			//Ikke et tal, beregn ikke på det
		} else {
			$this.closest('.reportLine').find('.total').html(nicePrice(priceCustom));
			priceTotal += priceCustom;
		}
	});
	*/
	
	$('#report .reportTotal .total').html(nicePrice(priceTotal)).addClass('open');
	
}
function resetVariety(obj,html) {
	if (html == '') {
		html = '<option value="">Choose variety</option>';
	}
	obj.closest('.reportLine').find('.variety select').attr('readonly','readonly').html(html);
	
	resetQuantity(obj);
}
function resetQuantity(obj) {
	if (typeof(strTotal) != 'undefined') {
		obj.closest('div.reportLine').find('div.quantity input').attr('readonly','readonly').val('Quantity').removeClass('open');
		obj.closest('div.reportLine').find('div.total').html(strTotal).removeClass('open');
		priceRecalc();
	}
}
function resetNonsap(obj) {
//log_debug('resetNonsap');
	obj.find('.name input').val('');
	obj.find('.quantity input').attr('readonly','readonly').val('Quantity').removeClass('open');
}

function nicePrice(price) {
////log_debug('nicePrice');
	var result, point;
	if (price != 0) {
		result = round_float(price,3);
	} else {
		result = price;
	}
	result = result.toString();
	point = result.lastIndexOf('.');
	
	if (point == -1) {
		result = result + '.000';
	} else if (point == (result.length - 2)) {
		result = result + '00';
	} else if (point == (result.length - 3)) {
		result = result + '0';
	}
	
	return addThousands(3, result);
}

function round_float(x,n){
////log_debug('round_float');
  if(!parseInt(n))
  	var n=0;
  if(!parseFloat(x))
  	return false;
  return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}


function inputBG(obj){
//log_debug('inputBG');
	var $this = $(obj);
	if ($this.val() == '') {
		//bg tilbage
		if ($this.attr('name') == 'customerid') {
			$this.css('background-image','url(/images/login_user_bg.gif)');
		} else {
			$this.css('background-image','url(/images/login_pass_bg.gif)');
		}
	}
}


function addThousands(decimalDigits,value) {
////log_debug('addThousands');
	// Separator Length. Here this is thousand separator
	var separatorLength = 3;
	var OriginalValue=value;
	var TempValue = '' + OriginalValue;
	var NewValue = '';
	var pStr;
	var dStr;
	
	
	if (isNaN(value)) {
		return 0;
	}else {
		if (TempValue.indexOf('.')==-1){
			TempValue+='.'
		}
		
		dStr=TempValue.substr(0,TempValue.indexOf('.'));
		pStr=TempValue.substr(TempValue.indexOf('.'))
		
		while (pStr.length-1< decimalDigits){
			pStr+='0';
		}
		if(pStr =='.') {
			pStr =''; 
		}
		
		if(dStr.length > separatorLength) {
			while( dStr.length > separatorLength) {
				NewValue = ',' + dStr.substr(dStr.length - separatorLength) + NewValue;
				dStr = dStr.substr(0,dStr.length - separatorLength);
			}
			NewValue = dStr + NewValue;
		} else {
			NewValue = dStr;
		}
		
		NewValue = NewValue + pStr;
		return(NewValue);
	}
} 
function removeThousands(value) {
////log_debug('removeThousands');
	return parseFloat(value.replace(/,/g,''));
}

function arrayFromSelect(inp) {
//log_debug('arrayFromSelect');
	var result = '';
	$(inp).each(function(i){
		if (i != 0) {
			if (i != 1) {
				result += '##';
			}
			result += $(this).html();
		}
	});
	return result.split('##');
}

/*
 * PLA imagelist
 **********************************/
function toggleImageList() {
	if (typeof imgServer != 'undefined') {
		$.ajax({
			url: 'proxy.aspx?datatype=text&url=' + imgAll,
			type: 'get',
			success: function(data,a,b){
				var images = data.substring(0,data.length-2).split('||');
				$.each(images,function(key, value){
					var li = '<li class="loading"></li>';
					var small = '<img src="' + imgServer + 'Img.ashx?size=small&crop=' + imgCrop + '&variety=' + imgVariety + '&file=' + value + '" alt=""/>';
					var large = '<img src="' + imgServer + 'Img.ashx?size=large&crop=' + imgCrop + '&variety=' + imgVariety + '&file=' + value + '" alt=""/>';
					var url = imgServer + 'Img.ashx?size=print&crop=' + imgCrop + '&variety=' + imgVariety + '&file=' + value;
					$('#jsImagelist').append(li);
					

					$(large).appendTo('#mainimage').load(function(){ 
						$('#jsImagelist li').eq(key).removeClass('loading')
						.append(small).find('img')
						.hoverIntent(
							function(){
								switchImage(this,url);
							},
							function(){}
						);
						
						if (key == 0) {
							switchImage($('#jsImagelist li img').get(key),url);
						}
						
					});

				});
			}
		});

	}
}

function switchImage(img, url) {
	var $thumb = $(img);
	var pos = $('#jsImagelist img').index($thumb);
	var $old = $('#mainimage img.visible');
	var $new = $('#mainimage img').eq(pos);
	var imgHeight;
	var imgEqual = eval($('#mainimage img').index($old) == $('#mainimage img').index($new));
	
	$new.css('opacity','0').css('display','block');
	imgHeight = $new.height();
	
	$('a.jsDownloadImage').attr('href', url);
	
	if (imgEqual == false) {
		$old.fadeOut(700);
	}
	$new.css('opacity','1').css('display','none').fadeIn(700);
	
	$('#mainimage').animate(
		{height: imgHeight}, 700,
		function(){
			if (imgEqual == false) {
				$old.removeClass('visible');
				$new.addClass('visible');
			}
		}
	);
}

