// insert a style-tag, which hides the menu lists before they are shown
$('<style type="text/css">#siteMainMenu ul ul { display: none; }</style>').appendTo('head');

// options for the zoom effect on product pages
var jqZoomOptions = {
	zoomWidth: 219,
	zoomHeight: 219
}

// jquery initialization script
$(function(){
	
	// menu interaction
	$('#siteMainMenu>ul ul').hide();
	$('#siteMainMenu>ul>li').bind('mouseenter',function(){
		$(this).siblings().find('ul').hide();
		$('ul',this).fadeIn(400);
	}).bind('mouseleave',function(){
		$('ul',this).hide();
	});
	
	// replace content if there is a flashmovie available 
	$('div.frontpageLargePicture[class*="jsFlash"],ul.frontpageArticleList li[class*="jsFlash"]').flash(null,{version: 8},function(htmlOptions){
		var $this = $(this);
		var flashRegExp = new RegExp('jsFlash.+]','i');
		htmlOptions.src = $this.attr('class').match(flashRegExp)[0].replace('jsFlash[','').replace(']','');
		htmlOptions.width = 175;
		htmlOptions.height = 219;
		htmlOptions.wmode = 'transparent';
		if ($this.hasClass('frontpageLargePicture')){
		htmlOptions.width = 300;
		htmlOptions.height = 448;
		}
		this.innerHTML = '<div class="flashAlt">'+this.innerHTML+'</div>';
		$this.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
	});

	// when a key have been pressed inside a textfield in the productorderlist, update the relevant calculated values
	function UpdateProductOrderListValues(that)
	{
		var tr = that.closest('tr');
		var newVal = 0;
		
		// set the new total amount
		tr.find(':text').each(function(){
			var amount = parseInt($(this).val(), 10);
			if (!isNaN(amount)){ newVal += amount; }
		});
		tr.find('td.amountTotal').text(newVal);
		
		// convert the number into one that javascript understands
		var unitPrice = parseFloat(tr.find('td.unitPrice').eq(0).text().replace(',','.')); 
		
		// set the new total price for the product and set the format back to what it was
		tr.find('input.priceTotalInp').val(newVal*unitPrice);
		var totalPrice = FormatNumber(newVal*unitPrice,2,true,false,true);
		tr.find('span.priceTotal').text(totalPrice + ' DKK');
		
		// sum up the total cost and total amount of items.
		var allTotals = 0;
		var allTotalItems = 0;
		$('#productorderlist input.priceTotalInp').each(function(){
			allTotals += parseInt($(this).val());
			allTotalItems += parseInt($(this).closest('tr').find('td.amountTotal').text());
		});
		allTotals = FormatNumber(allTotals,2,true,false,true);
		$('#productorderlist td.allTotalItems').text(allTotalItems);
		$('#productorderlist td.allTotal').text(allTotals + ' DKK');
	}
	
	// set zoom on the large product image
	$('.largeProductImage').jqzoom(jqZoomOptions);
	
	// on error handling on product info pages
	$('.smallProductImage img').each(function(){
		$(this).error(function(){
			$(this).closest('td').html('<div class="replaceBox"/>');
		}).attr('src',this.src);
	});
	$('.mixnmatch img').each(function(){
		$(this).error(function(){
			$(this).closest('td').remove();
		}).attr('src',this.src);
	});
	
	
	$('#colorproducts').change(getProductAvailabillity);
	
	getProductAvailabillity();
	
	$('#jsgetdatabutton').click(function(){
  	getaddressdata('#jsgetdatainput');
  });
	$('#jsgetdatainput').keyup(function(evt){
  	if (evt.keyCode == 13) {
  		getaddressdata('#jsgetdatainput');
  		return false;
  	}
  });
  
  // "Koeb mere"-haandtering
  knap_mere();
  
  // Productorderlist
  readyCheckboxes();
	
	
	// when pressing searchbutton, find the next result
	$("#orderlistSearchForm").submit(function(){
		return false;
	}).find(':button').click(function(evt){
		searchOrderlist(evt,1);
	});
	
	// search when typing in the searchbox 
	$("#orderlistSearchBox").keyup(searchOrderlist).focus();

	// when the page loades, get the results from the database, depending on the postalcode
	if($('#postalcodeResults').size() > 0){
		$('#postalcodeField').keyup(function(){
			var $this = $(this);
			if (isNaN(parseInt($this.val()),10) == false){
				$this.val(parseInt($this.val(),10));
			} else {
				$this.val('');
			}
		});
		
		var strUrl = escape('http://www.geoplugin.net/extras/postalcode.gp?lat=' + geoplugin_latitude() + '&long=' + geoplugin_longitude() + '&format=json');
		$.ajax({
			url: '/proxy.aspx?url=' + strUrl,
			success: function(data){
				var objData = $.json.decode(data.replace('geoPlugin(','').replace(')',''));
				
				$('#postalcodeField').val(objData.geoplugin_postCode);
				$('#postalcodeForm').ajaxSubmit({
					success: function(data){
						$('#postalcodeResults').html(data);
					}
				});
				
			}
		});
	};

	// activate Ajax on the 'aabenthus' page to get retailers depending on postalcode
	$('#postalcodeForm').ajaxForm({
		success: function(data){
			$('#postalcodeResults').html(data);
		}
	});

}); // jQuery ready end


// inline search in the orderlist
function searchOrderlist(event,intSearchDirection) {
	var $this = $("#orderlistSearchBox");
	var strSearchValue = $this.val().toLowerCase();
	var intIndexOldResult = -1;
	
	var intKey = event.keyCode;
	var boolShift = event.shiftKey;
	
	// check if the user clicked on enter
	/*
	// backward search - is not possible as such
	if (intKey == 13 && boolShift){
		intSearchDirection = -1;
	}
	else
	*/
	
	if (intKey == 13){
		intSearchDirection = 1;
	}

	// remember which was marked earlier
	var oldResult = $('#productorderlist').find("tr.marked");
	
	// remove the marking of the old result
	oldResult.removeClass("marked");
	
	// test if there is actually a searchstring
	if (strSearchValue != "") {
		var objSearchResultFound;
		var strStringToCheck;
		
		if (oldResult.size() > 0) {
			intIndexOldResult = $('#productorderlist').find("tr").index(oldResult);
		}
		
		// run through all the available searchterms
		$('#productorderlist').find(".tdProduct a").each(function() {
			var $this = $(this);
			strStringToCheck = $.trim($this.text().toLowerCase());

			// if the searchstring matches
			if (strStringToCheck.substring(0, strSearchValue.length) == strSearchValue) {
				
				objSearchResultFound = $this.closest('tr');
				var intIndexThisResult = $('#productorderlist').find("tr").index(objSearchResultFound);
				
				// if we have found the correct (and new) result, return false and stop the search 
				if ((intSearchDirection == 1 && intIndexThisResult > intIndexOldResult) || typeof intSearchDirection == 'undefined') {
					return false;
				}
				
			}
		});
		
		// test if we actually found something, scroll to the result and make it visible for the user
		if (objSearchResultFound != undefined) {
			objSearchResultFound.addClass('marked').closest("#content").scrollTo(objSearchResultFound, { axis: 'y', offset: {top: -70}});
		}
		
		
	}
}




function knap_mere()
{
	$('#knap_mere').click(function() {
		if (document.referrer.toLowerCase().indexOf('basket') > 0 || document.referrer.toLowerCase().indexOf('delivery') > 0)
		{
			location.replace('default.aspx?data=ProductListPaging&key=PKJOLE&load=main&paging=1&curpage=1');
		}
		else
		{
			history.go(-3);
		}
	});
}

function getProductAvailabillity() 
	{
		if ($('#colorproducts').size() > 0){
			$.ajax
			({
				url:'dynamic.aspx',
				data:{data:"getAvailabillity",productid:$('#colorproducts').val()},
				success:function(data)
				{
					//plain text
					//$('#productinfoDelivery').text(data);
			
					//HTML
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					// replace the old basketpreview with the body-content of 'data'
					$('.productinfoDelivery').replaceWith($(data.substring(startCut,endCut)));				
				}
			});
		}
	}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		
		tmpNumStr = tmpNumStr.replace('.',',');
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

// get address information via an Ajax call
function getaddressdata(strInputfieldselector){
	$.get(
		'/dynamic.aspx?ajaxmode=1&data=findaddress',
		{
			key: $(strInputfieldselector).val()
		},
		function(data){
			data = eval("(" + data + ")");
			$('#contact').val(data.contact);
			$('#street').val(data.street);
			$('#postalcode').val(data.postalcode);
			$('#city').val(data.city);
			$('#phone').val(data.phone);
			$('#usr_mobile').val(data.mobile);
			$('#email').val(data.email);
			
			$('#contact2').val(data.contact2);
			$('#street2').val(data.street2);
			$('#postalcode2').val(data.postalcode2);
			$('#city2').val(data.city2);
			
			formValidationCheck($(strInputfieldselector).closest('form').get(0),true);
	},'text');
}

// Productorderlist quantity change
function readyCheckboxes() {
	$('#productorderlist :text').keyup(function(){
		var tr = $(this).closest('tr');
		var newVal = 0;
		
		// set the new total amount
		tr.find(':text').each(function(){
			var amount = parseInt($(this).val(), 10);
			if (!isNaN(amount)){ newVal += amount; }
		});
		tr.find('td.amountTotal').text(newVal);
		
		// convert the number into one that javascript understands
		var unitPrice = parseFloat(tr.find('td.unitPrice').eq(0).text().replace(',','.')); 
		
		// set the new total price for the product and set the format back to what it was
		tr.find('input.priceTotalInp').val(newVal*unitPrice);
		var totalPrice = FormatNumber(newVal*unitPrice,2,true,false,true);
		tr.find('span.priceTotal').text(totalPrice + ' DKK');
		
		// sum up the total cost and total amount of items.
		var allTotals = 0;
		var allTotalItems = 0;
		$('#productorderlist input.priceTotalInp').each(function(){
			allTotals += parseInt($(this).val());
			allTotalItems += parseInt($(this).closest('tr').find('td.amountTotal').text());
		});
		allTotals = FormatNumber(allTotals,2,true,false,true);
		$('#productorderlist td.allTotalItems').text(allTotalItems);
		$('#productorderlist td.allTotal').text(allTotals + ' DKK');
	});
	
	$('#productorderlistform').submit(
		function() {
			$('input[type=text]').each(
				function() { $(this).attr('disabled', false); }
			);
		}
	);
	$('input[type=checkbox]').click(
		function() {
			var that = $(this);
			
			// Change value of textbox to 1
			if ($(this).is(':checked'))
			{
				$('input[name=quantity' + that.attr('title') + ']').attr('value', '1');
				$('input[name=quantity' + that.attr('title') + ']').attr('readonly', true);
				var tr = $(this).closest('tr');
				var newVal = 0;
				
				// set the new total amount
				tr.find(':text').each(function(){
					var amount = parseInt($(this).val(), 10);
					if (!isNaN(amount)){ newVal += amount; }
				});
				tr.find('td.amountTotal').text(newVal);
				
				// convert the number into one that javascript understands
				var unitPrice = parseFloat(tr.find('td.unitPrice').eq(0).text().replace(',','.')); 
				
				// set the new total price for the product and set the format back to what it was
				tr.find('input.priceTotalInp').val(newVal*unitPrice);
				var totalPrice = FormatNumber(newVal*unitPrice,2,true,false,true);
				tr.find('span.priceTotal').text(totalPrice + ' DKK');
				
				// sum up the total cost and total amount of items.
				var allTotals = 0;
				var allTotalItems = 0;
				$('#productorderlist input.priceTotalInp').each(function(){
					allTotals += parseInt($(this).val());
					allTotalItems += parseInt($(this).closest('tr').find('td.amountTotal').text());
				});
				allTotals = FormatNumber(allTotals,2,true,false,true);
				$('#productorderlist td.allTotalItems').text(allTotalItems);
				$('#productorderlist td.allTotal').text(allTotals + ' DKK');
			}
			else
			{
				$('input[name=quantity' + that.attr('title') + ']').attr('value', '');
				$('input[name=quantity' + that.attr('title') + ']').attr('readonly', false);
				var tr = $(this).closest('tr');
				var newVal = 0;
				
				// set the new total amount
				tr.find(':text').each(function(){
					var amount = parseInt($(this).val(), 10);
					if (!isNaN(amount)){ newVal += amount; }
				});
				tr.find('td.amountTotal').text(newVal);
				
				// convert the number into one that javascript understands
				var unitPrice = parseFloat(tr.find('td.unitPrice').eq(0).text().replace(',','.')); 
				
				// set the new total price for the product and set the format back to what it was
				tr.find('input.priceTotalInp').val(newVal*unitPrice);
				var totalPrice = FormatNumber(newVal*unitPrice,2,true,false,true);
				tr.find('span.priceTotal').text(totalPrice + ' DKK');
				
				// sum up the total cost and total amount of items.
				var allTotals = 0;
				var allTotalItems = 0;
				$('#productorderlist input.priceTotalInp').each(function(){
					allTotals += parseInt($(this).val());
					allTotalItems += parseInt($(this).closest('tr').find('td.amountTotal').text());
				});
				allTotals = FormatNumber(allTotals,2,true,false,true);
				$('#productorderlist td.allTotalItems').text(allTotalItems);
				$('#productorderlist td.allTotal').text(allTotals + ' DKK');
			}
		}
	);
}

$.fn.equals = function(selector) {
	return $(this).get(0)==$(selector).get(0);
};
