/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
//js('/files/javascript/SCRIPTNAME.js');
js('/files/javascript/jquery.autocomplete.min.js');
js('/files/javascript/jquery.colorbox-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();
	toggleShoppinglist();
	alterBasketQuantity();
	basketBatchDelete();
	basketUpdateQuantity();
	selectDeliveryLocation();
	testUserId();
	changeCountrySelectBox();
	ProductImageHover();
});

// open/close the different levels in the area menu on clicks
$('<style type="text/css">#tLeftmenu ul ul { display: none; }</style>').appendTo('head');
function toggleAreaMenu(){
	$('#areaMenu li ul, #tLeftmenu li ul').prev().click(function(){
		$this = $(this);
		if ($this.hasClass('closed')){
			// when the item is closed, open it and close all the open lists
			$this.removeClass('closed').addClass('open').next().slideDown('fast').parent().siblings().find('ul').slideUp().prev().removeClass('open').addClass('closed');
		} else {
			// when the item is open, close it
			$this.removeClass('open').addClass('closed').next().slideUp('fast');
		}
		$this.blur();
		return false;
	})
	$('#areaMenu li ul.closed').prev().addClass('closed');
	$('#areaMenu li ul.open').prev().addClass('open');
}

function toggleShoppinglist () {
	$('.jsShowlist').click(function() {
		$this = $(this);
		$this.parent().find('.jsShoppinglist').slideUp('fast');
		$this.next().slideDown('fast');
	});
}


/* SIKA Basket functiona
******************************************************/
function alterBasketQuantity() {
	$('.jsAddquantity').click(function(){
		$this = $(this);
		var qtycolli = parseFloat($this.parent().find('input[name=qtycolli]').val());
		$this.parent().find('input.quantity').val(round_float((parseFloat($this.parent().find('input.quantity').val()) + qtycolli),2));
	});
	$('.jsRemovequantity').click(function(){
		$this = $(this);
		var qtycolli = parseFloat($this.parent().find('input[name=qtycolli]').val());
		$this.parent().find('input.quantity').val(round_float((parseFloat($this.parent().find('input.quantity').val()) - qtycolli),2));
	});
}

function basketBatchDelete() {
	$('.jsSelectall').click(function(){
		$('input.jsDelete').attr('checked', true);
	});
	$('.jsDeletemarked').click(function(){
	
		$('.jsDeletemarked').after('<div style="width:1px; position:relative; float:right;"><div style="position:absolute; border:1px solid black; background-color:silver; padding:10px; text-align:middle">Sletter<br/><img src="/images/preloader.gif"/></div></div>');
	
		$('input:checked.jsDelete').each(function(i){
			
			var $this = $(this);
			$this.data('ajaxing','1');			
			
			$('#delete' + $(this).val()).ajaxSubmit({
				success:function(){
					$this.data('ajaxing','0');
					var bitReload = true;
					
					$('input:checked.jsDelete').each(function(i){
						if ($(this).data('ajaxing') == '1'){
							bitReload = false;
							return false;
						}
					});
					
					if (bitReload){
						window.location.reload();
					}
					
				}
			});
			
		});
	});
}

function basketUpdateQuantity() {
	$('.jsUpdateQuantity').click(function(){
		$('#BasketReturnto').val("default.aspx?load=main&data=basket");
		$('#jsBasket').submit();
	});
}

function selectDeliveryLocation() {
	$('#jsLocationselect').change(function(){
		var loc = locations[$('#jsLocationselect').val()];
		log_debug($('#jsLocationselect').val());
		log_debug(loc);
		log_debug(locations);
		$('#company2').val(loc[0]);
		//$('#contact2').val(loc[5]);
		$('#contact2').val('');
		$('#street2').val(loc[4]);
		$('#postalcode2').val(loc[3]);
		$('#city2').val(loc[1]);
		$('#country2').val(loc[2]);
	});
	$('.jsClearData').change(function(){
		$('#jsLocationselect option[value=1]').attr('selected', 'selected');
	});
}


/* Sika user administration
***********************************************************/

function userRemoveDisable(userid, customerid) {
	log_debug(userid);
	$.get	(
		'dynamic.aspx?data=UpdateUser',
		{
			DisableUser: '0',
			userId: userid
		}
	);
	$('.jsRemovedisabled.user_' + userid).hide();
	$('.jsDisable.user_' + userid).show();
}

function userDisable(userid, customerid) {
	log_debug(userid);
	$.get	(
		'dynamic.aspx?data=UpdateUser',
		{
			DisableUser: '1',
			userId: userid
		}
	);
	$('.jsDisable.user_' + userid).hide();
	$('.jsRemovedisabled.user_' + userid).show();
}

function testUserId() {
	//$('#createUser_form').submit(function() {
	$('#gem').click(function() {
		var url = 'dynamic.aspx?data=ajaxTestUserId&userid=' + $('input[name=userid]').val() + '&customerid=' + $('input[name=customerid]').val();
		var response = '';
		var redirectURL = $('input[name=_returnto]').val();
		var shouldRedirect = false;
		
		// Test username
		$.ajax({
			url: url,
			type: 'GET',
			async: false,
			cache: false,
			timeout: 30000,
			error: function(){
			},
			success: function(data){ 
				response = data.substring(data.indexOf('<body id=\'pageDynamic\'>') + '<body id=\'pageDynamic\'>'.length, data.indexOf('</body>'));
				//alert(url + ': ' + response);
				
				if (response == 'USERID_VALID') // Valid username
				{
					var disabledUsr = '0';
					
					if ($('input[name=disableuser]').is(':checked'))
					{
						disabledUsr = '1';
					}
					
					var createUserURL = 'dynamic.aspx?data=CreateUser' +
										'&userid=' + $('input[name=userid]').val() +
										'&email=' + $('input[name=email]').val() +
										'&name=' + $('input[name=name]').val() +
										'&creditmax=' + $('input[name=creditmax]').val() +
										'&password=' + $('input[name=password]').val() + 
										'&disableuser=' + disabledUsr;
					// Create user
					$.ajax({
						url: createUserURL,
						type: 'GET',
						async: false,
						cache: false,
						timeout: 30000,
						error: function(){
						},
						success: function(data){ 
							alert('Brugeren er oprettet!');
							shouldRedirect = true; // Redirect
							return false;
						}
					});
					/*$.get(createUserURL, function() {
						alert('Brugeren er oprettet!');
						location.href = redirectURL; // Redirect
					});*/
				}
				else if (response == 'USERID_INVALID') // Invalid username
				{
					alert('Brugernavnet er ugyldigt. Prøv et andet brugernavn.');
				}
				else // User exists or unspecified error
				{
					alert('Brugeren findes allerede i systemet. Prøv et andet brugernavn.');
				}
			}
		});
		
		// Redirect
		if (shouldRedirect)
		{
			location.href = redirectURL;
		}
		
		/*$.get(url, function(data) {
			response = data.substring(data.indexOf('<body id=\'pageDynamic\'>') + '<body id=\'pageDynamic\'>'.length, data.indexOf('</body>'));
			alert(url + ': ' + response);
		});*/
	});
}


/* SIKA Quantity per Colli Control
   Bygget på kopi af standard-funktionalitet 08/03-2010 ei@e-supplies.dk
*******************************************************/

function activateAjaxShopping(objArg){
	
	
	$('#jsBatchUpdateBasket').submit(function(){
		$('input[name^=quantity][value!=""]',this).each(function(){
			checkQuantity(this);
		});
	});
	
	$('input.jsCheckQtycolli').blur(function(){
		checkQuantity(this);
	});
	
}

function checkQuantity(obj) {
		var qtycolli = parseFloat($(obj).parent().find('input.qtycolli').val());
		var quantity = parseFloat($(obj).val().toString().replace(',','.'));
		
		if (isNaN(quantity)) {
			$(obj).val('');
		} else { 
			$(obj).val(quantity);
		}
		
		if (qtycolli > 1 && quantity > 0 && round_float(quantity % qtycolli,2) > 0) {			
			$(obj).val(round_float(Math.ceil(quantity / qtycolli) * qtycolli,2));
			$(obj).after('<div class="jsMessage"><div>Antallet passer ikke med en hel pakning og er blevet justeret.</div></div>');
			$(obj).parent().find('.jsMessage').fadeIn('slow',function(){
				window.setTimeout("$('.jsMessage').fadeOut('slow')",5000);
			});
		}
}

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 changeCountrySelectBox() {

	$('.jsCountry2').change(function(){
		$('.jsPostalcode2, .jsCity2').val('');
	});

}

function ProductImageHover() {
	$('.jsShowphoto').hoverIntent(
		function(){
			var productid = $(this).attr('class').replace('jsShowphoto jsShowphoto_','');
			$('#productimage img').css('display','none');
			$('#productimage .prodimg_' + productid).css('display','inline');
		},
		function(){
			$('#productimage img').css('display','none');
			$('#productimage .groupimage').css('display','inline');
		}
	).click(function(){
			var productid = $(this).attr('class').replace('jsShowphoto jsShowphoto_','');
		$.colorbox({
			href: '/dynamic.aspx?data=productinfo&template=productimage&key=' + productid,
			iframe: true,
			width: '465',
			height: '370',
			onOpen: function(){
				$('#colorbox').addClass('pagePopup');
			},
			onClosed: function(){
				$('#colorbox').removeClass('pagePopup');
			}
		});
	});
}






















