// jQuery functions and definitions
$(document).ready(function() {
	
	// SHOW / HIDE SMALL BASKET
	$('#basketButton').hover(function() {
		$('#shopBasket')
			.stop(true,true)
			.fadeIn(50);
	}, function() {
		$('#shopBasket')
			.stop(true,true)
			.fadeOut(50);
	});
	
	// SHOW / HIDE BUY BUTTONS VARIANTS
	$('#buyButton').hover(function() {
		$('#variant')
			.stop(true,true)
			.fadeIn();
	}, function() {
		$('#variant')
			.stop(true,true)
			.fadeOut(400);
	});
	
	// SHOW / HIDE COLORS
	$('.color').hover(function() {
		$('.color ul').show();
	}, function() {
		$('.color ul').hide();
	});
	
	// SHOW / HIDE SIZES
	$('.sizeChoice').hover(function() {
		$('.sizeChoice ul').show();
	}, function() {
		$('.sizeChoice ul').hide();
	});
	// Update size for filter
	$('.sizeChoice ul a').click(function() {
		var value = $(this).attr('title');
		$.ajax({
			type: 'POST',
			url: '/updateFilter.php',
			data: { value: value, updateType: 'size' },
			success: function(data) {
				window.location=data;
			}
		});
	});
	// Remove filter when user chooses All
	$('#removeFilter').click(function() {
		var gotoUrl = $(this).attr('value');
		$.ajax({
			type: 'POST',
			url: '/updateFilter.php',
			data: { value: '', updateType: 'size' },
			success: function(data) {
				window.location=gotoUrl;
			}
		});
	});
	
	
	// DISABLED ITEMS
	$('.buyButtonDisabled').css({'opacity': '0.5', 'cursor': 'default'});
	
	
	// POPULAR PRODUCTS: Functions and parameters
	$(".carouselPopular").jCarouselLite({
    	btnNext: ".popularNext",
 		btnPrev: ".popularPrev",
 		scroll: 2,
 		circular: false
	});

	// LAST VISITED PRODUCTS: Functions and parameters
	$(".carouselLastVisited").jCarouselLite({
    	btnNext: ".lastVisitedNext",
 		btnPrev: ".lastVisitedPrev",
 		scroll: 2,
 		circular: false
	});

	// CUSTOMER ADDRESS: Funtions for customer data input
	$('#Name').click(function(){
		$('#Name').focus();
	});
	$('#showDeliveryInfo').click(function(){
	 	$('#showDeliveryInfo').fadeOut();
	 	$('#deliveryInfo').fadeIn();
	 	$('#deliveryHeader').html('Din bestilling betales af:');
	});
	$('#hideDeliveryInfo').click(function(){
	 	document.getElementById('Name2').value='';
	 	document.getElementById('Address2').value='';
	 	document.getElementById('City2').value='';
	 	$('#deliveryInfo').fadeOut();
	 	$('#showDeliveryInfo').fadeIn();
	 	$('#deliveryHeader').html('Betales af og leveres til:');
		updatePurchase( 0 , 'updateDelivery' );
	});

	// SEARCH: Fade out suggestions box on blur
	$('#inputString').blur(function(){
	 	this.value='Skriv søgeord';
	 	$('#inputString').css('color', '#a99f92');
	 	$('#suggestions').fadeOut();
	 });
	 
	 // Product image and zoom
	 var imageWidth = 300;
	 var numImages = $('#productImage img').length;
	 $('.imageExtras a').css({'opacity': '.5'});
	 $('.imageExtras a:first').addClass('imageSelected').css({'opacity': '1'});
	 $('.imageExtras a').hover(function() {
	 	$(this).animate({ 'opacity': '1' }, 150) }, function() { if (!$(this).hasClass('imageSelected')) $(this).animate({ 'opacity': '.5' }, 250)
	 });
	 $('.imageExtras a').click(function() {
	 	$('#productImage').animate({ 'left': '-'+($(this).attr('name')*imageWidth)+'px' }, 500);
	 	$('.imageExtras a').removeClass('imageSelected').css({ 'opacity': '.5' });
	 	$(this).addClass('imageSelected').css({'opacity': '1'});
	 });
	 $(".jqzoom").jqzoom();
	 
	// Size guide and chart
	$('.openSizeChart').click(function(){
	 	$('.sizechart').show();
	});
	$('.closeSizeChart').click(function(){
	 	$('.sizechart').hide();
	});
	
	// Overlay for productlist
	$('.productItem').hover(function(){
		$(this).attr('title','')
	 	current = $(this).find('.listItemOverlay');
	 	prod_id = $(this).attr('name');
	 	timer = setTimeout(function() {
	 		$.get("/includes/avaliableSizes.php", {prod_id: ""+prod_id+""}, function(data) {
				current.show();
				current.html(data);
			});
		}, 750);
	}, function() {
		clearTimeout(timer);
		$('.listItemOverlay').hide();
	});
	
	
 });

// SEARCH: Handle Search query
function lookup(inputString) {
	if(inputString.length == 0) {
		// Hide the suggestions box if no query
		$('#suggestions').fadeOut();
	} else {
		$('#inputString').css('color', '#675339');
		// Make string æ,ø,å safe
		inputString = inputString.replace(/Æ/g, "_ae_");
		inputString = inputString.replace(/æ/g, "_ae_");
		inputString = inputString.replace(/Ø/g, "_oe_");
		inputString = inputString.replace(/ø/g, "_oe_");
		inputString = inputString.replace(/Å/g, "_aa_");
		inputString = inputString.replace(/å/g, "_aa_");
		
		// AJAX call if query
		$.get("/includes/search.php", {queryString: ""+inputString+""}, function(data) {
			$('#suggestions').fadeIn();		// Show suggestions box
			$('#suggestions').html(data);	// Fill suggestions box with html
		});
	}
}

// UPDATE BASKET
function addProduct(prodId , variant , number) {
	var realTop = (($(window).height() - $('#realImage').height()) / 2)+$(document).scrollTop();
	var imgTop = $(document).scrollTop();
	$('#basketPop')
		.html('<div id="realImage"><div class="update">Opdaterer kurv</div><img src="/templates/images/wait-state.gif" /></div><div id="imgShow" style="display:none"></div>')
		.find('#realImage')
		.css('top', realTop);
	$('#basketPop').load('/updateBasket.php', 'prodId=' + prodId + '&variant=' + variant + '&number=' + number,  function(data) {
			$('#realImage').css('top', realTop);
			$('#imgShow')
				.css({'top': imgTop, 'opacity': '0'})
				.animate({'opacity': '0.5'}, 'slow');
		}).fadeIn();
}

function updatePurchase(prodId , updateType) {
	var realTop = (($(window).height() - $('#realImage').height()) / 2)+$(document).scrollTop();
	var imgTop = $(document).scrollTop();
	if(updateType=='delete') {
		$('#basketPop')
			.html('<div id="realImage"><div class="update">Opdaterer kurv</div><img src="/templates/images/wait-state.gif" /></div><div id="imgShow" style="display:none"></div>')
			.find('#realImage')
			.css('top', realTop);
		$('#basketPop').load('/updateBasket.php', 'prodId=' + prodId + '&updateType=' + updateType,  function(data) {
			$('#realImage').css('top', realTop);
			$('#imgShow')
				.css({'top': imgTop, 'opacity': '0'})
				.animate({'opacity': '0.5'}, 'slow');
		}).fadeIn();	
	}
	else {
		$('#basketPop').load('/updateBasket.php', 'prodId=' + prodId + '&updateType=' + updateType,  function(data) {window.location = "/kurv/Din_bestilling";});
	}
}

	
		
		
		
// CUSTOMER ADDRESS: Validating input and adding help text
function isNumeric( numberId ) {
    return document.getElementById( numberId ).value.match(/^[0-9]+$/);
}

function isLatinName( numberId ) {
    return document.getElementById( numberId ).value.match(/^[a-zA-Z-.,æøåÆØÅ ]+$/);
}

function isAddress( numberId ) {
    return document.getElementById( numberId ).value.match(/^[a-zA-Z-.,æøåÆØÅ0-9 ]+$/);
}

function isEmail( numberId ) {
    return document.getElementById( numberId ).value.match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/);
}

function validateName( helpId, thisId ) {
	var content = document.getElementById( thisId ).value;
	var helpTxt = 'Skriv dit fulde navn eller et firmanavn.<br />Du kan anvende tal, bogstaver, punktum, bindestreg og mellemrum';
	var checkChr = content.substring( content.length-1 , content.length );
	var valid = true;
	var toLong = false;
	
	if ( content.length != 0 ) {
		if ( isAddress( thisId ) == null ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			valid = false;
		}
		if ( content.length < 2 && content.length !=0 ) {
			helpTxt = '<em>' + helpId +'et skal indeholde mindst 2 tegn</em>';
		} else if ( content.length >= 2 && content.length <= 80 ) {
			helpTxt = '<span>' + helpId +'e-feltet er gyldigt</span>';
		}
		else if ( content.length > 80 ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			helpTxt = '<span>' + helpId +'e-feltet er gyldigt</span>';
			valid = false;
			toLong = true;
		}
	}
	
	if (!valid) {
		if (toLong) {
			helpTxtShow( '' + helpId + '', '<em>' + helpId +'et kan højst indeholde 80 tegn</em>' );
			toLong = false;
		} else {
			helpTxtShow( '' + helpId + '', '<em>' + checkChr + ' er ikke et gyldigt tegn</em>' );
		}
		valid = true;
		setTimeout( "helpTxtShow('" + helpId + "', '" + helpTxt + "' )", 2000 );
	} else {
		helpTxtShow( '' + helpId + '', helpTxt );
	}
}

function validateAddress( helpId, thisId ) {
	var content = document.getElementById( thisId ).value;
	var Address = helpId.replace(/_/gi, " ");
	var helpTxt = 'Du kan anvende tal og bogstaver samt punktum, bindestreg og mellemrum';
	var checkChr = content.substring( content.length-1 , content.length );
	var valid = true;
	var toLong = false;
	
	if ( content.length != 0 ) {
		if ( isAddress( thisId ) == null ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			valid = false;
		}
		if ( content.length < 6 && content.length !=0 ) {
			helpTxt = '<em>'+ Address +' skal indeholde mindst 6 tegn</em>';
		} else if ( content.length >= 6 && content.length <= 80 ) {
			helpTxt = '<span>'+ Address +'-feltet er gyldigt</span>';
		}
		else if ( content.length > 80 ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			helpTxt = '<span>'+ Address +'-feltet er gyldigt</span>';
			valid = false;
			toLong = true;
		}
	}
	
	if (!valid) {
		if (toLong) {
			helpTxtShow( '' + helpId + '', '<em>'+ Address +'-feltet kan højst indeholde 80 tegn</em>' );
			toLong = false;
		} else {
			helpTxtShow( '' + helpId + '', '<em>' + checkChr + ' er ikke et gyldigt tegn</em>' );
		}
		valid = true;
		setTimeout( "helpTxtShow('" + helpId + "', '" + helpTxt + "' )", 2000 );
	} else {
		helpTxtShow( '' + helpId + '', helpTxt );
	}
}

function validateComment( helpId, thisId ) {
	var content = document.getElementById( thisId ).value;
	var Address = helpId.replace(/_/gi, " ");
	var helpTxt = 'Du kan anvende tal og bogstaver samt punktum, bindestreg og mellemrum';
	var checkChr = content.substring( content.length-1 , content.length );
	var valid = true;
	var toLong = false;
	
	if ( content.length != 0 ) {
		if ( isAddress( thisId ) == null ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			valid = false;
		}
		if ( content.length < 0 && content.length !=0 ) {
			helpTxt = '<span>'+ Address +'-feltet er gyldigt</span>';
		}
		else if ( content.length > 100 ) {
			content = content.substring( 0 , content.length-1 );
			document.getElementById( thisId ).value = content;
			helpTxt = '<span>'+ Address +'-feltet er gyldigt</span>';
			valid = false;
			toLong = true;
		}
	}
	
	if (!valid) {
		if (toLong) {
			helpTxtShow( '' + helpId + '', '<em>'+ Address +'-feltet kan højst indeholde 40 tegn</em>' );
			toLong = false;
		} else {
			helpTxtShow( '' + helpId + '', '<em>' + checkChr + ' er ikke et gyldigt tegn</em>' );
		}
		valid = true;
		setTimeout( "helpTxtShow('" + helpId + "', '" + helpTxt + "' )", 2000 );
	} else {
		helpTxtShow( '' + helpId + '', helpTxt );
	}
}

function validateEmail( helpId, thisId ) {
	var content = document.getElementById( thisId ).value;
	
	if ( content.length != 0 ) {
		if ( isEmail( thisId ) == null ) {
			helpTxtShow( '' + helpId + '', '<em>E-mail-adressen er endnu ikke gyldig</em>' );
		} else {
			helpTxtShow( '' + helpId + '', '<span>E-mail-adressen er gyldig</span>' );
		}
	} else {
		helpTxtShow( '' + helpId + '', 'Du modtager en e-mail med et track-and-trace nummer ved afsendelse af dine varer, så du kan følge din bestilling hos PostDanmark' );
	}
}

function validateNumber( helpId, thisId, minL, maxL ) {
	var content = document.getElementById( thisId ).value;
	var helpTxt = 'Skriv kun tal uden mellemrum eller andre tegn';
	var valid = true;
	var toLong = false;

	if ( content.length != 0 && isNumeric( thisId ) == null ) {
		content = content.substring( 0 , content.length-1 );
		document.getElementById( thisId ).value = content;
		valid = false;
	}
	if ( content.length < minL && content.length !=0 ) {
		helpTxt = '<em>Nummeret skal indeholde mindst ' + minL + ' tal</em>';
	}
	else if ( content.length >= minL && content.length <= maxL ) {
		helpTxt = '<span>Nummeret er gyldigt</span>';
	}
	else if ( content.length > maxL ) {
		content = content.substring( 0 , content.length-1 );
		document.getElementById( thisId ).value = content;
		helpTxt = '<span>Nummeret er gyldigt</span>';
		valid = false;
		toLong = true;
	}
	
	if (!valid) {
		if (toLong) {
			helpTxtShow( '' + helpId + '', '<em>Nummeret kan højst indeholde ' + maxL + ' tal</em>' );
			toLong = false;
		} else {
			helpTxtShow( '' + helpId + '', '<em>Du kan ikke indtaste andre tegn end tal</em>' );
		}
		valid = true;
		setTimeout( "helpTxtShow('" + helpId + "', '" + helpTxt + "' )", 1500 );
	} else {
		helpTxtShow( '' + helpId + '', helpTxt );
	}
}

function helpTxtShow( showId, text ){
	document.getElementById( showId ).style.display = 'block';
	document.getElementById( showId ).innerHTML = '<div id="topTxt">' + showId.replace(/_/gi, " ") + '</div><div id="botTxt">' + text + '</div>';
}
function helpTxtHide( hideId ){
	document.getElementById( hideId ).style.display = 'none';
}

function changeNumber( prodId , number ) {
	document.getElementById( "addProd"+prodId ).value = number;
}
		
