// Function to be able to place overlay in the view - even if scrolled down
function getMouseY(e) {
	var scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
	    // Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && document.body.scrollTop ) {
	    // DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
	    // IE6 standards compliant mode
	    scrOfY = document.documentElement.scrollTop;
	}
	if ( scrOfY < 0 ) scrOfY = 0;
	if ( document.getElementById('realImage') != null) document.getElementById('realImage').style.top = scrOfY + 350 + 'px';
	if ( document.getElementById('imgShow') != null) document.getElementById('imgShow').style.top = scrOfY + 350 + 'px';
	return true;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

function removeFyns()
{
	setCookie('fynsk', 'off', 1);
	
	if($('#fynsRow').is(':visible')) {
		var halfPrice = $('.basketContent .goods .basketTotal.totalBottom').html();
		var totalOld = parseFloat(halfPrice.replace('.','').replace(',','.'))*2;
		totalOld = addCommas(totalOld.toFixed(2).toString().replace(/\./g,','));
		$('.basketContent .goods .basketTotal.totalBottom').html(totalOld+' DKK');
		$('#fynsRow').hide();
	}
}

// jQuery functions and definitions
$(document).ready(function() {
	
	if(getCookie('campaign') != 'done') {
		// Fynsk forår
		$('#City, #City2').blur(function() {
			var postNr = parseInt($('#City').attr('value'));
			var postNrLev = parseInt($('#City2').attr('value'));
			
			if(getCookie('otherdelivery') == 'on') {
				if(postNrLev > 4999 && postNrLev < 5900) {
					setCookie('fynsk', 'lev2', 1);
				} else {
					removeFyns();
				}
			} else {
				if(postNr > 4999 && postNr < 5900) {
					setCookie('fynsk', 'lev', 1);
				} else {
					removeFyns();
				}
			}
			
			if(getCookie('fynsk') == 'lev' || getCookie('fynsk') == 'lev2') {
				$('#fynskForaar').fadeIn(250);
			}
			
			if(getCookie('fynsk') == 'lev' || getCookie('fynsk') == 'lev2') {
				if(!$('#fynsRow').is(':visible')) {
					var totalOld = $('.basketContent .goods .basketTotal.totalBottom').html();
					totalOld = parseFloat(totalOld.replace('.',''))/2;
					var halfPrice = addCommas(totalOld.toFixed(2).toString().replace(/\./g,','));
					$('.basketContent .goods .basketTotal.totalBottom').html(halfPrice+' DKK');
				}
				if($('#fynsRow').length == 0) {
					$('.basketContent .goods tr:last').before('<tr id="fynsRow"><td colspan="4"></td><td colspan="2" class="basketTotalTxt">Fynsk forårsrabat:</td><td class="basketTotal"> - '+halfPrice+' DKK</td></tr>');
				} else {
					$('#fynsRow').show();
				}
			}
		});
		$('#fynskForaar').click(function() {
			$('#fynskForaar').fadeOut(250);
		});
	}

	
	// POPULAR PRODUCTS: Functions and parameters
	$(".carouselPopular").jCarouselLite({
    	btnNext: ".popularNext",
 		btnPrev: ".popularPrev",
 		scroll: 3,
 		circular: false
	});

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

	// CUSTOMER ADDRESS: Funtions for customer data input
	$('#Name').click(function(){
		$('#Name').focus();
	});
	// CUSTOMER DELIVERY ADDRESS
	$('#showDeliveryInfo').click(function(){
	 	$('#showDeliveryInfo').fadeOut();
	 	$('#deliverySuggest').hide();
	 	$('#deliveryInfo').fadeIn();
	 	$('#deliveryHeader').html('Din bestilling betales af:');
	 	setCookie('otherdelivery', 'on', 1);
	});
	$('#hideDeliveryInfo').click(function(){
	 	document.getElementById('Company').value='';
	 	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' );
		setCookie('otherdelivery', 'off', 1);
		
		// For fynsk forår kampagne
		var postNr = parseInt($('#City').attr('value'));
		if(postNr > 4999 && postNr < 5900) {
			setCookie('fynsk', 'lev', 1);
		} else {
			removeFyns();
		}
	});
	if (getCookie('otherdelivery') == 'on') $('#deliverySuggest').hide();
	
	// SEARCH: Fade out suggestions box on blur
	$('#inputString').blur(function(){
	 	this.value='Skriv søgeord';
	 	$('#suggestions').fadeOut();
	 });
	 
	 // Product image zoom
	 $(".jqzoom").jqzoom();
	 
	// Size guide and chart
	$('.openSizeChart').click(function(){
	 	$('.sizechart').show();
	});
	$('.closeSizeChart').click(function(){
	 	$('.sizechart').hide();
	});
 });

 
 // COOKIE FUNCTIONS
function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	  {
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name)
	    {
	    return unescape(y);
	    }
	  }
}
function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

 
// SEARCH: Handle Search query
function lookup(inputString) {
	if(inputString.length == 0) {
		// Hide the suggestions box if no query
		$('#suggestions').fadeOut();
	} else {
		// 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
		$.post("/includes/search.php", {queryString: ""+inputString+""}, function(data) {
			$('#suggestions').fadeIn();		// Show suggestions box
			$('#suggestions').html(data);	// Fill suggestions box with html
		});
	}
}

// Show Video
function showVideo(youtubeUrl,videoHeight) {
	var realTop = (($(window).height() - parseInt(videoHeight)) / 2)+$(document).scrollTop();
	var imgTop = $(document).scrollTop();
	$('#basketPop')
		.html('<div id="showVideo"><a onclick="javascript:videoClose()" id="videoClose">Luk</a><object width="853" height="'+videoHeight+'"><param name="movie" value="'+youtubeUrl+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+youtubeUrl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="853" height="'+videoHeight+'"></embed></object></div><div id="videoBackground" ></div>')
		.find('#showVideo')
		.css('top', realTop);
	$('#showVideo').css('top', realTop);
	$('#videoBackground')
		.css({'top': imgTop, 'opacity': '0'})
		.animate({'opacity': '0.75'}, 'slow');
		
}
function videoClose() {
	$('#basketPop').css({'display': 'none'}).html('').css({'display': 'block'})
}



// 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 ){
	if(document.getElementById('deliverySuggest')!=null) document.getElementById( 'deliverySuggest' ).style.display = 'none';
	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;
}
		
