/*
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){
			var arrayIndex = $.inArray(formatted, groups) + 1;
			$(this).prev('select').val(arrayIndex).change();
			
			var $varietyInput = $(this).closest('.reportLine').find('.variety select');
			
			var arrVarieties = '';
			var arrVarietyValues = '';
			
			$varietyInput.addClass('appliedAutocomplete').find('option:not(:first)').each(function(i){
				if (i != 0) {
					arrVarieties += '##';
					arrVarietyValues += '##';
				}
				arrVarieties += $(this).text();
				arrVarietyValues += $(this).attr('value');
			});
			
			
			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();
			}).focus();
			
		}).blur(function(){
			if ($.inArray($(this).val(), groups) == -1) {
				$(this).val('').prev('select').val('');
			}
		});
		
		$('#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');
	}
	
	
	$('#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).prev('select').val(arrayIndex).change();
		$(this).closest('.reportLine').find('.supplier option').eq(arrayIndex+1).attr('selected', 'selected').closest('select').change();
		
		//if ($(this)closest('.reportLine').find('.varietyDeduction input.autocomplete').size() == 0) {
			$(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(){ // on mouseover
		// var count = $('ul:first > li',this).size();
		// var originalcount = count;
		// if (count > 10) {
			// count = 10;
		// }
		// log_debug(count);
		// log_debug(originalcount);
		// var menuheight = count * 30;
		// var containerheight = menuheight + 1 + 22;
		// var scrolloffset = menuheight + 1 + 11;
				
		// if (originalcount > 10) {
			// $('div:first, ul:first',this).slideDown('fast').find('ul:first').css('height',menuheight + 'px').css('width','222px').jScrollPane({scrollbarWidth:0, scrollbarMargin:0, animateTo:true});
		// } else {
			$('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(){
	
// Report Varieties only
	//selectbox change events
	$('#reportVarieties .crop select').change(function(){
		var $this = $(this);
		var varieties = '<option value="">Choose variety</option>';
		
		resetVariety($this, varieties);
		
		if ($this.val() != '') {
			for(var i = 1; i < report[$this.val()].length; i++) {
				varieties = varieties + '<option value="' + report[$this.val()][i][0] + '">' + report[$this.val()][i][1]  + '</option>';
			}
			$this.parent().parent().find('.variety select').removeAttr('readonly').html(varieties).focus();
		}
		
		//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();
		}
		
		
		//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').addClass('open').focus().select();
		}
	});
	
//Deductions only
	//selectbox 1 change events
	$('#reportDeduction .supplier select').change(function(){
		
		//create new line if lowest
		if ($('#report #reportDeduction .supplier select').index($(this)) >= ($('#report #reportDeduction .supplier select').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();
		});
	});
	
	//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();
	
		$('#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(){ 
		var strData;
		var i = 1;
		strData = '_function=BatchUpdateBasket&_returnto=default.aspx'
		
		$('#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';
		} else {
			$('#report #reportVarieties .quantity input[value!="Quantity"]').each(function(){
				var $inp = $(this);
				var quantity = removeThousands($inp.val());
				if (!(isNaN(quantity))) {
					var productid = $inp.parent().parent().find('.variety select').val() + '__' + i;
					i = i+1;
					strData += '&productid=' + productid;
					strData += '&quantity' + productid + '=' + quantity;
				}
			});
			
			$('#report #reportNonsap .name input[value!=""]: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))) {
					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))) {
					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('');
	});
}




// Reporting support functions
function newReportLine(area){
	$('#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 .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('.reportLine').find('.quantity input').attr('readonly','readonly').val('Quantity').removeClass('open');
		obj.closest('.reportLine').find('.total').html(strTotal).removeClass('open');
		priceRecalc();
	}
}
function resetNonsap(obj) {
	obj.find('.name input').val('');
	obj.find('.quantity input').attr('readonly','readonly').val('Quantity').removeClass('open');
}

function nicePrice(price) {
	var result, point;
	if (price != 0) {
		result = round_float(price,2);
	} else {
		result = price;
	}
	result = result.toString();
	point = result.lastIndexOf('.');
	
	if (point == -1) {
		result = result + '.00';
	} else if (point == (result.length - 2)) {
		result = result + '0';
	}
	
	return addThousands(2, result);
}

function round_float(x,n){
  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){
	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)
{
	// 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) {
	return parseFloat(value.replace(/,/g,''));
}

function arrayFromSelect(inp) {
	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');
			}
		}
	);
}



