// Skifter standardværdi i et input-felt til/fra
function toggleDefValue(myVal) {
	var myObj = getEventTarget();
	(myObj.value==myVal) ? myObj.value='' : myObj.value = myVal;
}

function getEventTarget() {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

/** JS Functions **/

//checker, om en e-mail adresse er gyldig (user@domain.land)
function checkEmail(str) {
	if ((str.indexOf('@') < 0) || (str.indexOf('.') < 0))
	{
		alert('Der er fejl i den indtastede e-mail adresse.\n'+
		'En korrekt e-mail angives som bruger@domæne.land; f.eks. jens@hansen.dk.');
		return false;
	}	
	else {
		return true;
	}
}

// skifter tilmeld til frameld i en nyhedsbrevformular
function frameldNyhedsbrev(myForm) {
	if (checkEmail(document.forms(myForm).email.value)) {
		document.forms(myForm).action.value = 'nyhedsbrev.delete';
		document.forms(myForm).submit();
		return true;
	}
	else {
		return false;
	}
}

function checkEmpty(str,fieldName) {
	var re = /\s/g; //Match any white space including space, tab, form-feed, etc. 
	RegExp.multiline = true; // IE support
	var myStr = str.replace(re, "");
	if (myStr.length == 0) {
		alert('Feltet "'+fieldName+'" manger at blive udfyldt.\n'+
		'Udfyld venligst feltet og prøv igen.');
		return false;
		} 
	else {return true;}
}

function checkVal(myVal,errMsg) {
	if (!myVal) {
		alert(errMsg);
	}
	return myVal;
}


// checker form under oprettelse/redigering af ejer
function checkEjerForm() {
	var myForm = document.getElementById("brugerForm");
	return checkEmail(myForm.email.value) &&
		checkEmpty(myForm.password.value,"Kodeord") &&
		checkEmpty(myForm.password2.value,"Bekræft kodeord") &&
		checkVal(myForm.password.value==myForm.password2.value,'De to kodeord skal være ens.\nCheck venligst kodeordet.') &&
		checkVal(myForm.password.value.length >= 5,'Kodeordet skal være 5 tegn eller længere.\nRet venligst kodeordet.') &&
		checkEmpty(myForm.navn.value,"For- og efternavn") &&
		checkEmpty(myForm.adresse.value,"Egen adresse") &&
		checkEmpty(myForm.postnr.value,"Postnr") &&
		checkEmpty(myForm.bynavn.value,"By");
}

// sætter default værdi i input-felt og fjerner on-click
function checkDefVal(myObj,myDefVal) {
	if (event.type=='focus') {
		if (myObj.value == myDefVal) {
			myObj.value = '';
		}
	} else if (event.type=='blur') {
		if (myObj.value == '') {
			myObj.value = myDefVal;
		}
	}
}


function ShowImage(filename,winTitle,imgText)
{
      // Hent billedet
      var myImage = new Image();
         myImage.src = filename+'?'+Math.random()*100000;

      // Starterstørrelse for loadervindue
      var loadWidth = 200;
      var loadHeight = 100;
      var loadText = '<div align="center">'+
        'Henter billedet - '+
        'vent venligst...</div>';

      posX = Math.round(((screen.width/2)-(loadWidth/2)));
      posY = Math.round(((screen.height/2)-(loadHeight/2)));
      imgWindow = window.open('','','width='+loadWidth+
      ',height='+loadHeight+
      ',left='+posX+',top='+posY);

      // Indsæt default titel, hvis mangler
      if (!winTitle) { winTitle = 'Billede'; }

      html = '<html><head><title>'+winTitle+'</title>'+
        '<style type="text/css">body {margin: 0;}</style>'+
        '<link type="text/css" rel="stylesheet" href="stylesheet.css">'+
        '</head>';
      html += '<body></body></html>';

      imgWindow.document.write(html);

      var winBody = imgWindow.document.body;
      winBody.innerHTML = loadText;

      // onerror: billedet ikke fundet
      myImage.onerror = function() {
        winBody.innerHTML = '<div class="popupBilledeTekst">'+
        '<b>The picture was not found!</b>'+
        '</div>';
      }

      // onload: billedet er hentet ind
      myImage.onload = function() {
        // Find nyt skærmposition og størrelse
        posX = Math.round(((screen.width/2)-(myImage.width/2)));
        var myHeight = ((imgText==undefined||imgText=='')?myImage.height:myImage.height+50);
        posY = Math.round(((screen.height/2)-(myHeight/2)));
        imgWindow.moveTo(posX,posY);
        imgWindow.resizeBy(myImage.width-loadWidth,myHeight-loadHeight);

        // Indsæt HTML for siden
        html = '<img src="'+myImage.src+
          '" width="'+myImage.width+
          '" height="'+myImage.height+
          '" alt="Klik på billedet for at lukke vinduet."'+
          ' name="Billede" id="PopupBillede" onclick="self.close();">';
        html += ((imgText==undefined||imgText=='')?'':'<div class="popupBilledeTekst">'+imgText+'</div>');
        winBody.innerHTML = html;
      }

      return false;
}

// functions til huskeliste

// Gemmer eller fjerner fra huskelisten
//Saves or removes from Shortlist
function huskeliste(myID) {
	if (isNumeric(myID)) {
		if (getCookie('huskeliste')) { myListe = getCookie('huskeliste'); } else { myListe = ''; }
		if (myListe.indexOf('#'+myID+',') == -1) {
			// indsæt i listen
			//indsæt i listen
			myListe = myListe+'#'+myID+',';
		} else {
			// fjern fra listen
			// Remove from list
			matchStr = new RegExp('\#'+myID+'\,', 'g');
			myListe = myListe.replace(matchStr,'');
		}
		setCookie('huskeliste',myListe,'Thu, 01-Jan-2015 00:00:01 GMT');
		
		myCookie = getCookie('huskeliste');
		checkHuskeliste(myID); 
		
	}
}

// checker krydser og tekster i de rette felter
//cross-check and text in the correct fields
function checkHuskeliste(myID,addText,delText) {
	myObj = document.getElementById('huskeliste'+myID);
	myTxt = document.getElementById('huskelisteInfo'+myID);
	myCnt = document.getElementById('huskelisteCounter');
	if (getCookie('huskeliste')) { myListe = getCookie('huskeliste'); } else { myListe = ''; }
	
	if (myListe.indexOf('#'+myID+',') == -1) {
		// findes ikke i huskelisten
		if (myObj) { myObj.checked = false; }
		if (myTxt) { 
			//myTxt.innerHTML = addText; 	
			if(addText){
				$("#huskeliste"+myID).attr('border','0');
				$("#huskeliste"+myID).attr('style','');
			}	
		}


	} else {
		// findes i huskelisten
		if (myObj) { myObj.checked = true; }
		if (myTxt) { 
			//myTxt.innerHTML = delText; 
			if(delText){
				$("#huskeliste"+myID).attr('border','1');
				$("#huskeliste"+myID).attr('style','border: 1px solid red');
			}	
		}

	}	
	if (myCnt) { myCnt.innerHTML = myListe.split("#").length-1; }
}


// returnerer antal huse i huskelisten
function huskelisteAntal() {
	if (getCookie('huskeliste')) { myListe = getCookie('huskeliste'); } else { myListe = ''; }
	document.write(myListe.split("#").length-1);
}

// returnerer hele huskelisten som en string (uden #)
function visHuskeliste() {	
	if (getCookie('huskeliste')) { myListe = getCookie('huskeliste'); } else { myListe = ''; }
	reg = new RegExp('#','g');
	document.write(myListe.replace(reg,''));
}

// sletter hele huskelisten
function sletHuskeliste() {
	if (confirm('Achtung: Möchten Sie wirklich die ganzen Favoritenliste löschen?')) {
		if (getCookie('huskeliste')) {
			setCookie('huskeliste','','Thu, 01-Jan-2000 00:00:01 GMT');
		}
		// reload til forsiden
		window.location='/';
	}
}

function huskelisteLink(myUrl) {
	myListe = getCookie('huskeliste');
	if (myListe) {
		reg = new RegExp('#','g');
		myListe = myListe.replace(reg,'');
		document.location.href = myUrl+'?action=find&id='+myListe+'&newsearch=1';
	} else {
		alert('Sie haben keiner Ferienhäuser auf Ihrer Favoritenliste!');
	}
}

function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function setCookie(name, value, expires, path, domain, secure)
{
	path="/";
    return document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


function deleteCookie(name, path, domain) {
	path="/";
	if ( getCookie(name)) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function isNumeric(strString)
//  check for valid numeric strings	
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

//  test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
  {
  strChar = strString.charAt(i);
  if (strValidChars.indexOf(strChar) == -1)
     {
     blnResult = false;
     }
  }
return blnResult;
}

// indhenter kontaktinformationer for huset i Iframe
function kontaktInfo(myId,myFrameId) {
	myFrame = document.getElementById('kontaktFrame'+myFrameId);
	document.getElementById('kontaktLinkDiv'+myFrameId).innerHTML = '<b>Udlejerinfo:</b>';
	myFrame.className = 'kontaktFrameSynlig';
	myFrame.src = 'kontaktinfo.php?id='+myId;
}

// åbner kalenderen
function openCalendar(myId) {
	//var $(this).attr();
/*	document.getElementById('kalenderVisning').style.visibility='visible';
	document.getElementById('kalenderContent').innerHTML = ''+
	'<iframe width="460" height="400" scrolling="auto" id="kalenderIframe" src="/de/kalender.php?id='+myId+'"></iframe>';
*/	
	
}

// lukker kalenderen
function closeCalendar() {
	document.getElementById('kalenderVisning').style.visibility='hidden';
}

// sender en tip
function tipper() {
	var myForm = document.getElementById('tipperForm');
	if (myForm) {
		myWin = window.open('tipAfsendt.php?modtager='+myForm.modtager.value+'&afsender='+myForm.afsender.value+'&url='+document.location.href,'winTipper','width=250,height=100,toolbar=no,location=no,directories=no,statusbar=0,status=no,menubar=no,scrollbars=no,resizable=no');
	}

}

// åbner eller lukker (display) en tag med bestemt ID
function toggleArea(myId) {
	var myObj = document.getElementById(myId);
	if (myObj) {
	    if (myObj.style.display == 'none') {
			myObj.style.display = 'block';
		} else {
			myObj.style.display = 'none';
		}
	}
}

/** End JS functions **/

/**
 * Description: search section 
 */
/** Jquery Functions **/

$(document).ready(function() {
	var thisPage = $("#facilities").attr("name");
	if(thisPage=="index"){
		$("#facilities").hide();
		$("#antalRum").hide();
	}

	//$("#brugerinfo").show();
	
/*
 * 	Shows up the advance search section
 */	
	$("#search-more a").click(function() {
		var maxafstand=$("#search-form").attr('maxafstand');
		var maxprice=$("#search-form").attr('maxprice');
		var maxpriceday=$("#search-form").attr('maxpriceday');
		var meter=$("#search-form").attr('meter');
		var pricedesc=$("#search-form").attr('pricedesc');
		var pricedaydesc=$("#search-form").attr('pricedaydesc');
		var afstanddesc=$("#search-form").attr('afstanddesc');

		$("#facilities").slideToggle('show');
		$("#antalRum").show();
		$("#search-more").css({"float":"left"}).html('<div class="search-title-h3" >'+maxafstand+'</div><input style="width:100px;" class="textbox" type="text" size="5" maxlength="5" name="strand" /><span id="small" > '+meter+'<br />'+afstanddesc+'</span>');
		$("#search-button").css({"float":"right","width":"150px"}).html('<div class="search-title-h3" >'+maxprice+'</div><input class="textbox" style="width:100px;" type="text" name="maxprice" /><span id="small"> &euro;<br />'+pricedesc+'</span><br/><br/><div class="search-title-h3">'+ maxpriceday +'</div><input class="textbox" style="width:103px;" type="text" name="maxpriceday" /><span id="small"> &euro;<br/>'+pricedaydesc+'</span>');
		return false;
	});

/*
 * Hide
 */	
	
	$("#hide-adv").click(function() {
		var thisButton = $("#search-form").attr('button');
		var thisMore = $("#search-form").attr('more');
		$("#facilities").slideToggle('slow');		
		$("#antalRum").hide();
		$("#search-more").css({"float":"right"}).html('<a href="#" onclick="javascript:" >'+thisMore+'</a>');
		$("#search-button").css({"width":"160px"}).html('<input type="hidden" name="max" value="10"><input type="hidden" name="dk" value="1"><input type="submit" class="button" value="'+thisButton+'">');
		$("#search-more a").click(function() {
			var thisButton = $("#search-form").attr('button');
			var thisMore = $("#search-form").attr('more');
			var maxafstand=$("#search-form").attr('maxafstand');
			var maxprice=$("#search-form").attr('maxprice');
			var maxpriceday=$("#search-form").attr('maxpriceday');
			var meter=$("#search-form").attr('meter');
			var pricedesc=$("#search-form").attr('pricedesc');
			var afstanddesc=$("#search-form").attr('afstanddesc');
			
			$("#facilities").slideToggle('show');
			$("#antalRum").show();
			$("#search-more").css({"float":"left"}).html('<div class="search-title-h3" >'+maxafstand+'</div><input style="width:100px;" class="textbox" type="text" size="5" maxlength="5" name="strand" /><span id="small" > '+meter+'<br />'+afstanddesc+'</span>');
			$("#search-button").css({"float":"right","width":"150px"}).html('<div class="search-title-h3" >'+maxprice+'</div><input class="textbox" style="width:100px;" type="text" name="maxprice" /><span id="small"> &euro;<br />'+pricedesc+'</span><br/><br/><div class="search-title-h3">'+ maxpriceday +'</div><input class="textbox" style="width:103px;" type="text" name="maxpriceday" /><span id="small"> &euro;<br/>'+pricedaydesc+'</span>');
			return false;
		});
		
		return false;		
	});
	
/*
 *when change it loads the area  
 */	
	$("#country").change(function() {
			loadCountry()
	});
	
	var thisUser = $("#userAdmin").attr('class');
	if(!thisUser){
		loadCountry();
	}
	
	function loadCountry(){
		var thisVal = $("#country").val();
		var language = $("#country").attr('language');
		
		
		if(!language){
			language='dansk'
		}	

			loadAjax("/system/loadajax.php?searchoption=area&geocountry="+thisVal+"&language="+language,"#area");
			$("#country").attr('name','geo');
			$("#geoarea").attr("name","");
			$("#cities").attr("name","");			
		
	}
	
	/*
	 * Send contact information
	 */
	
	$("#receive-contact").click(function() {
		var toMail = $("#receive-contact-email").val(); 
		var subcription = $("input:checkbox[name=receive-subcription]:checked").val(); 
		var husID = $("#husID").attr("name");
		var thisCode = $("#security_code").val();
		
		//alert(toMail+'-'+subcription+husID);
		
		if(subcription){
			var subValue=1;
		}else{
			var subValue=0;
		}		
		
		if(isValidEmailAddress(toMail)){
			loadAjax("/system/loadajax.php?sendmail=receiveContactInfo&language=tysk&toList="+toMail+"&subcription="+subValue+"&husID="+husID+"&sCode="+thisCode,"#receive-contact-result");
			//location.reload();
		}else{
			alert("Bitte geben Sie eine gültige E-Mail-Adresse");
		}
		return false;
	});
	
	/*
	 * Tipper
	 */

	 $("#house-tipper").click(function() {
		 var myForm = document.getElementById('tipperForm');
		 var thisEmail = $("#tb_modtager").val();
		 var thisName = $("#tb_afsender").val().split(' ').join('-');
		 if (myForm) {
			 if(isValidEmailAddress(thisEmail)){
			 	var	myWin = '/de/tipAfsendt.php?language=tysk&modtager='+thisEmail+'&afsender='+thisName+'&url='+document.location.href;
			 	loadAjaxContact(myWin,".tipperAjax");
			 }else{
				 alert("Bitte geben Sie eine gültige E-Mail-Adresse");
			 }	 
		 }	
		 return false;
		  	
	 });
	
	/*
	 * hover  result Price
	 */
	 /*
	$("#search-table #td-price").hover(function() {
		$("#search-table #td-price").css('border','#C1C1C1 1px solid');
		$(this).css('border','#aaF1FC 1px solid');
		//alert('dd');
		//return false;
	});
	*/
	
		$('.td-price').hover(over, out);
	    //Tell the browser to change the background when hovered over
	    function over(event) {
	       // $(this).css("border","2px #dbe4fb solid");	        
	        var thisID = $(this).attr('name');	      
			var thisLink = $(this).attr('thelink');
	        var lastPrice = $(this).attr('lp');
	        var lastPriceEuro = $(this).attr('lpe');
	        var week = $(this).attr('week');
	        var foerPris = $(this).attr('fp');
	      	
	       // alert(lastPrice);
	        	
	       //var thisTitle = 'Last-Minute Angebote <br /> für #'+thisID;
			var thisTitle = 'Last-Minute Angebote für #'+thisID+' '+ thisLink;
	       // $(this).append('<div class="mark-border" style="margin-top:-'+thisHeight+'px" >&nbsp;</div>');
	        //display the week price
	       
	        if(lastPrice){
	    	   $(this).append('<div style="" class="last-minute">'+thisTitle +'<br /><br />'+lastPrice+' <br /></div>');
 			$(".last-minute").fadeIn('slow');
	        }   	
	       
	    }
	    //tell the browser to change the background to nothing when 
	    //going outside the object area
	    function out(event) {
		    //$(this).css({"border":"none","border-right":"1px #CCCCCC solid","border-bottom":"1px #CCCCCC solid"});
		    $(".last-minute").remove();
		    //$(".mark-border").remove();
		}
	
	
	/*
	 * shortlist
	 */
	
	 $(".gem-save").click(function() {
		 var thisBorder=$(this).attr('border');
		// $(this).attr('bordercolor','#FEF1B5');
		// $(this).attr('border','1');
		 if(thisBorder=='1'){
			 $(this).attr('border','0');
			 $(this).css('border','none');
		 }else{
			 $(this).attr('border','1');
			 $(this).css('border','red 1px solid');
		 }		 
	 });
	 
	 $(".gem-save-link").click(function() {
		 $(".gem-save").click();		 
	 });
	 
	 $(".printPage").click(function() {
	 		mywindow = window.open ("http://www.ferienhausmietedaenemark.de/de/printhus.php?id=" + $("#hdnHusID").val(), "Sommerhuse","location=0,status=1,scrollbars=1, width=740,height=600");
	     mywindow.moveTo(0,0);
		 return false;
	 });
	 
	 $("#house-inquiry").click(function() {
			var inqEmail = $("#inquiry-to").val(); 
			var inqName = $("#inquiry-name").val();
			var inqBody = $("#inquiry-body").val();
			var receiveContact = $("input:checkbox[name=recieve-contact-info]:checked").val(); 
			var subcription = $("input:checkbox[name=receive-subcription-inquiry]:checked").val(); 
			var husID = $("#husID").attr("name");
			var thisCode = $("#security_code2").val();
			
			//alert('dd');
			
			if(subcription){
				var subValue=1;
			}else{
				var subValue=0;
			}		
			
			if(isValidEmailAddress(inqEmail)){
			   	if(inqName=='Ihre Name'){
  					alert('Ihre Name');
  				}else if(inqBody==''){
  					alert('Your booking request or other inquiries for the homeowner');
  				}else{	
  						//sendInquiry("/system/loadajax.php?sendmail=sendInquiry&language=tysk&toList="+inqEmail+"&subcription="+subValue+"&husID="+husID+"&sCode="+thisCode,"#receive-inquiry-result",inqEmail,inqName,inqBody);
  						sendInquiry("/system/loadajax.php?sendmail=sendInquiry&toList="+inqEmail+"&subcription="+subValue+"&husID="+husID+"&sCode="+thisCode,"#receive-inquiry-result",inqEmail,inqName,inqBody,receiveContact,subcription);
  						//location.reload();
  				}		
				      //sendInquiry("/system/loadajax.php?sendmail=sendInquiry&language=tysk&toList="+inqEmail+"&subcription="+subValue+"&husID="+husID,"#receive-inquiry-result",inqEmail,inqName,inqBody);
			}else{
				//alert("Please Enter a valid email");
				alert("Bitte geben Sie eine gültige E-Mail-Adresse");
			}
			return false;		 
		 
	 });
	 
	 /*
	  * 
	  */
	 
	 $(".husLinkData a").click(function() {
		 var confirmDel = confirm('Are you sure you want to delete this Link');
		 //alert('dd');
		// return false;

		 if(confirmDel){
			 return true;	
		 }else{
			 return false;
		 }		 
		
	 });
	 
	 /*
	  * Admin
	  */
	 
	 //abonnoment
	 $("#mnuAction").change(function() {
		 var thisVal = $(this).val();
		 
		 //alert(thisVal);
		 switch(thisVal){
		 	case'slet':
		 		confirmDel = confirm('Vil du slette ordren permanent fra databasen?\n\nOrdren bliver IKKE behandlet!');
		 		if(confirmDel){
		 			$("#mnuActionForm").submit();
		 		}
			break; 
		 	case'opretOgHenvis':
		 		confirmAction = confirm('Vil du tildele abonnementet til brugeren?\n\Evt. bonuspenge for henvisning tildeles samtidigt til evt. henvisende bruger.');
		 		if(confirmAction){
		 			$("#mnuActionForm").submit();
		 		} 		
			break; 
		 	case'opretUdenHenvis':
		 		confirmAction = confirm('Vil du tildele abonnementet til brugeren uden henvisning?\n\INGEN bonuspenge vil blive tildelt til henvisende bruger!!');
		 		if(confirmAction){
		 			$("#mnuActionForm").submit();
		 		}		 		
			break; 				
		 }
		 return false;	
	 });

	 //log in
	 $('#brugerlogin input:text[name=email]').click(function() {
		 	$(this).attr('value','');
		 	 return false;
	 });  
	 
	 $('#brugerlogin input:password[name=password]').click(function() {
		 	$(this).attr('value','');
		 	return false;
	 }); 	
	 
	 $('#receive-contact-email').click(function() {
		 $(this).attr('value','');		 
	 });

	 $('#inquiry-to').click(function() {
		 $(this).attr('value','');		 
	 });

	 $('#inquiry-name').click(function() {
		 $(this).attr('value','');		 
	 });

	 //save shortlist-letter
	 $(".gem-save-link").click(function() {
		 $(".gem-save").click();		 
	 });	
	 
	 //last-munite house ads
	 $(".icon-lastminute a").click(function() {
		 var husID=$("#husID").attr('name');
		 openCalendar(husID);
		
	 });

	 //security code
	 $("#security_code").addClass("textbox text-email");
	 $("#security_code2").addClass("textbox text-email");
	 //
	 $("#security_code").click(function() {
        $(this).val("");
        
   });
	 
	 $("#security_code2").click(function() {
        $(this).val("");
       
   });	
	
});

// Loading Ajax 
function loadAjax(href,divname){
	//$(divname).html("Loading...");
	$(divname).html("<div class='green'>Loading...</div>");
	$(divname).load(href,null,function(){
		var geoArea = divname + " #geoarea";
		var geoEgn = divname + " #geoegn";
		var geoCities = divname + " #cities";

		$(geoArea).change(function() {
			var thisVal = $(this).val();
			var countryVal = $("#country").val();	
			var language = $(this).attr('language');
		
			if(!language){
				language='dansk'
			}	
			
			loadAjax("/system/loadajax.php?searchoption=egn&geocountry="+countryVal+"&geoarea="+thisVal+"&language="+language,"#egn");
			$(this).attr('name','geo');
			$("#country").attr("name","");
			$(geoEgn).attr("name","");
			$(geoCities).attr("name","");

		});
		
		
		$(geoEgn).change(function() {	
			var thisVal = $(this).val();
			var areaVal = $(geoArea).val();
			var countryVal = $("#country").val();		
			var language = $(this).attr('language');
		
			if(!language){
				language='dansk'
			}	

			loadAjax("/system/loadajax.php?searchoption=cities&geocountry="+countryVal+"&geoarea="+areaVal+"&geoegn="+thisVal+"&language="+language,"#geocities");
			$(this).attr('name','geo');
			$("#country").attr("name","");
			$(geoArea).attr("name","");
			$(geoCities).attr("name","");

		});
			
			
		$(geoCities).change(function() {
			
			var language = $(this).attr('language');
			
			if(!language){
				language='dansk'
			}	
			
			$(this).attr('name','geo');
			$(geoArea).attr("name","");
			$(geoEgn).attr("name","");
			$("#country").attr("name","");
			
		});
		
		
	});
	
	
	
}

// Sending inquiry
function sendInquiry(href,divName,inqEmail,inqFrom,inqBody,receiveContact,subcription){
var admin_email = 'info@sommerhusdanmark.dk';

 $(divName).show();
 //$(divName).html("Loading...");
    $(divName).html("<div class='green'>Loading...</div>");
 //$(divName).load(href,({'ingEmail':inqEmail,'inqFrom':inqFrom,'inqBody':inqBody,'receiveContact':receiveContact,'subcription':subcription}),function() {
 //});
 $(divName).load(href + '&copy1=' + inqEmail + '&copy2=' + admin_email + '&userlanguage=tysk',({'ingEmail':inqEmail,'inqFrom':inqFrom,'inqBody':inqBody,'receiveContact':receiveContact,'subcription':subcription}),function() {});
 //$(divName).fadeOut('slow');
}

//contact
function loadAjaxContact(href,divName){
	$(divName).show();
	
	$(divName).html("<div class='green'>Loading...</div>");
	$(divName).load(href,null,function() {
		
		//$(divName).fadeOut('slow');
	});
}

/*
 * Javascript validating email add
 */
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}
/** **/


	

/*
	Print function
	created:12/11/2009
*/

(function($){
    $.fn.printElement = function(options){
        var mainOptions = $.extend({}, $.fn.printElement.defaults, options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
        if (mainOptions.printMode == 'iframe') {
            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) 
                mainOptions.printMode = 'popup';
        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();
        
        return this.each(function(){
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $this.data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn.printElement.defaults = {
        printMode: 'iframe', //Usage : iframe / popup
        pageTitle: '', //Print Page Title
        overrideElementCSS: null,
        /* Can be one of the following 3 options:
         * 1 : boolean (pass true for stripping all css linked)
         * 2 : array of $.fn.printElement.cssElement (s)
         * 3 : array of strings with paths to alternate css files (optimized for print)
         */
        printBodyOptions: {
            styleToAdd: 'padding:10px;margin:10px;', //style attributes to add to the body of print document
            classNameToAdd: '' //css class to add to the body of print document
        },
        leaveOpen: false, // in case of popup, leave the print page open or not
        iframeElementOptions: {
            styleToAdd: 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            classNameToAdd: '' //css class to add to the iframe element
        }
    };
    $.fn.printElement.cssElement = {
        href: '',
        media: ''
    };
    function _printElement(element, opts){
        //Create markup to be printed
        var html = _getMarkup(element, opts);
        
        var popupOrIframe = null;
        var documentToWriteTo = null;
        if (opts.printMode.toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=745,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
            var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            $(iframe).attr({
                style: opts.iframeElementOptions.styleToAdd,
                id: printElementID,
                className: opts.iframeElementOptions.classNameToAdd,
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document) 
                documentToWriteTo = documentToWriteTo.document;
            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
            popupOrIframe = iframe.contentWindow || iframe;
        }
        focus();
        documentToWriteTo.open();
        documentToWriteTo.write(html);
        documentToWriteTo.close();
        _callPrint(popupOrIframe);
    };
    
    function _callPrint(element){
        if (element && element.printPage) 
            element.printPage();
        else 
            setTimeout(function(){
                _callPrint(element);
            }, 50);
    }
    
    function _getElementHTMLIncludingFormElements(element){
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function(){
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function(){
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function(){
            var $select = $(this);
            $("option", $select).each(function(){
                if ($select.val() == $(this).val()) 
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function(){
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            if ($.browser.mozilla) 
                this.firstChild.textContent = value;
            else 
                this.innerHTML = value;
        });
        var elementHtml = $element.html();
        return elementHtml;
    }
    
    function _getBaseHref(){
        return window.location.protocol + window.location.hostname + window.location.pathname;
    }
    
    function _getMarkup(element, opts){
        var $element = $(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);
        
        var html = new Array();
        html.push('<html><head><title>' + opts.pageTitle + '</title>');
        if (opts.overrideElementCSS) {
            if (opts.overrideElementCSS.length > 0) {
                for (var x = 0; x < opts.overrideElementCSS.length; x++) {
                    var current = opts.overrideElementCSS[x];
                    if (typeof(current) == 'string') 
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
                    else 
                        html.push('<link type="text/css" rel="stylesheet" href="' + current.href + '" media="' + current.media + '" >');
                }
            }
        }
        else {
            $(document).find("link").filter(function(){
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function(){
                html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
            });
        }
        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');
        html.push('</head><body style="' + opts.printBodyOptions.styleToAdd + '" class="' + opts.printBodyOptions.classNameToAdd + '">');
       
		 html.push('<img class="hovedindholdKant" width="695" height="9" src="/grafik/v2/venstrespalte-top.png"/><div class="' + $element.attr('class') + '" style="background:#fff;">' + elementHtml + '</div><img class="hovedindholdKant clear" width="695" height="13" src="/grafik/v2/venstrespalte-bottom.png"/>');
        html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts.leaveOpen && opts.printMode.toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');
        
        return html.join('');
    };
})(jQuery);
    
function scrollIt(name, name2)
{
  var targetOffset = $("input[name='" + name + "']").offset().top - 70;
  $('html,body').animate({scrollTop: targetOffset}, 3000);    
  return false;
} 





function monthYearChanged(str){
            var thevalues = str.split("-");
			var daysinMonth = daysInMonth(thevalues[0],thevalues[1]);
			var options = '';
			var master=document.findForm.arrivalday;
			var master2=document.findForm.monthyear;
			var d = new Date();
			var curr_date = d.getDate();
			
			var curr_month = d.getMonth();
			var curr_year = d.getFullYear();
			var thedays=$("#search-form").attr('thedays');
			$tempdays = thedays.split(",");
			
			//if (curr_month <=0) curr_month = curr_month + 1;
			
			//alert (curr_month + ' '+ curr_year+' '+curr_date  );
	        //alert(d.getMonth());
			
		
    if (str <= null){
		 var therealmonth = curr_month + 1;
		 var str = therealmonth + '-' + curr_year; 
		 var thevalues = str.split('-');
		 var daysinMonth = daysInMonth(thevalues[0],thevalues[1]);
		
		x = curr_date + 1; noddays = 0;  master.options.length=0;
		for (var i = 0; i <= daysinMonth; i++) {
			if (i == curr_date) break;	
			if (noddays >=6) noddays =1; else noddays = noddays + 1;	
		}
		
		noddays = noddays + 2;
	    for (var i = 0; i <= daysinMonth; i++) {
				if (x <=9) tmpx = '0'.x; else tmpx = x;
				master.options[i]=new Option(x +'. '+ getDayName(thevalues[0]+"/"+ x +"/"+thevalues[1], "/"), x, false, false);
					if (noddays >=6) noddays =1; else noddays = noddays + 1;
					if (x == daysinMonth) break;
					x = x + 1;
					
			}
		
		
	}//if
	
	if 	 ((thevalues[0] <= 12) &&  (thevalues[1] == curr_year) && (thevalues[0] == curr_month + 1) ) { 
		//master2.options[0] = null;
		x = curr_date + 1; noddays = 0;  master.options.length=0;
		
		for (var i = 0; i <= daysinMonth; i++) {
			if (i == curr_date) break;	
			if (noddays >=6) noddays =1; else noddays = noddays + 1;	
		}
		
		//alert(noddays);	
		//alert(thevalues[0]+"-"+ x +"-"+thevalues[1]);
		noddays = noddays + 2;
	    for (var i = 0; i <= daysinMonth; i++) {
				master.options[i]=new Option(x +'. ' + getDayName(thevalues[0]+"/"+ x +"/"+thevalues[1], "/"), x, false, false);
					if (noddays >=6) noddays =1; else noddays = noddays + 1;
					if (x == daysinMonth) break;
					x = x + 1;
					
			}
	
			//master.options[0] = null; 
	
	}  else {
			//master2.options[0] = null;
			master.options.length=0;			
			noddays =0;			
			x =1;
			for (var i = 0; i < daysinMonth; i++) {
					//master.options[i]=new Option(x +'. ' + $tempdays[noddays], i, false, false);
					x = eval(x);
					if (x <= 9) tempx = "0" + x; else  tempx =  x; 
					if (thevalues[0] <=9) tempmonth = "0" + thevalues[0]; else tempmonth = thevalues[0]; 
					master.options[i]=new Option(x +'. '+ getDayName(tempmonth+"/"+ tempx +"/"+thevalues[1], "/"), x, false, false);
					x = x + 1;
			}
		}	
			
					master.focus();
			
}//function

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
      var d = dec_point == undefined ? "," : dec_point;
  
      var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
  
      var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  
       
        return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
  
      }

function getDayName(appDate, seperator){
               // Name of the days as Array
			   var currentTime = new Date();  

			   var thedays=$("#search-form").attr('thedays');
               var dayNameArr = thedays.split(",");
			  // var dayNameArr = new Array ("Saturday","Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday");
			   
               var dateArr = appDate.split(seperator); // split the date into array using the date seperator
               var month = dateArr[0]; 
               var day = dateArr[1];
               var year = dateArr[2];
			   var dt = new Date(year,month,day);
              // Calculate the total number of days, with taking care of leapyear 
        
			  var totalDays = day + (2*month) + parseInt(3*(month+1)/5) + year + parseInt(year/4) - parseInt(year/100) +  parseInt(year/400) + 2;			
              // Mod of the total number of days with 7 gives us the day number		  
			 // var dayNo = (totalDays % 7);			 
              // if the resultant mod of 7 is 0 then its Saturday so assign the dayNo to 7			  
			  var dayNo = (dt.getDay());
			  
			if (month != 4){
			  switch(dayNo){
				case 0:
						dayNo = 5;
						break;
				case 1:
						dayNo = 6;
						break;		
				case 2:
						dayNo = 0;
						break;		
				case 3:
						dayNo = 1;
						break;
				case 4:
						dayNo = 2;
						break;						
				case 5:
						dayNo = 3;
						break;
				case 6:
						dayNo =  4;
						break;		
			
			  }//switch
			}
			  
			 if (month == 2) dayNo = dt.getDay() + 1; 
			 if (month == 4){
					switch(dayNo){	
						case 0:
								dayNo = 6;
								break;
						case 1:
								dayNo = 0;
								break;		
						case 2:
								dayNo = 1;
								break;		
						case 3:
								dayNo = 2;
								break;
						case 4:
								dayNo = 3;
								break;						
						case 5:
								dayNo = 4;
								break;
						case 6:
								dayNo =  5;
								break; 
					}
						//dayNo = dt.getDay() + 1;
			}		
			 
			 switch(year){
				
			 case currentTime.getFullYear():
							 
							//if (month == 2) dayNo = dayNo + 3;
							//if (month == 4) dayNo = dayNo + 7;
							if (dayNo <= 0) dayNo = 0;
							if(dayNo >= 7) dayNo = 0;
							//alert(dayNameArr[dayNo] +" "+dayNo);
							
							if (dayNo == 0){
									addtltxt = getWeekMarker(year,month,day);
							} else addtltxt = '';
							
							return dayNameArr[dayNo]+ addtltxt;//  + " " + dayNo;
							break;
				default:
							 myDate = new Date(eval('"'+appDate+'"'))	
							 dayNo = myDate.getDay() + 1;							
							 
							if(dayNo >= 7) dayNo = 0;	
							//return dayNameArr[dayNo] +" "+dayNo;
							
							if (dayNo == 0){
									addtltxt = getWeekMarker(year,month,day);
							} else addtltxt = '';
							
							return dayNameArr[dayNo]+ addtltxt;
							break;					
			  }
			
			//return dayNameArr[dayNo]+" "+appDate+" "+dayNo+" "+totalDays; // return the repective Day Name from the array
}


function arrivaldaychanged(){
	var daystay=document.findForm.dage;	
	
	daystay.options.length=0;	
	x =1;
	for (var i = 0; i < 48; i++) {
		daystay.options[i]=new Option(x +' dag', x, false, false);			
		x = x + 1;
	}//for
}//function

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function getWeekMarker(year,month,day) {
	var theweek=$("#search-form").attr('theweek');
    year = y2k(year);
	//alert(year+' '+month+' '+day);
	
    var when = new Date(year,month,day);
	//alert(when);
    var newYear = new Date(year,0,1);
    var offset = 7 + 1 - newYear.getDay();
    if (offset == 8) offset = 1;
	if (when.getMonth() > 0) tmp_month = when.getMonth() -1; else tmp_month = when.getMonth();
    var daynum = ((Date.UTC(y2k(year),tmp_month,when.getDate(),0,0,0) - Date.UTC(y2k(year),0,1,0,0,0)) /1000/60/60/24) + 1;
    var weeknum = Math.floor((daynum-offset+7)/7);
    if (weeknum == 0) {
        year--;
        var prevNewYear = new Date(year,0,1);
        var prevOffset = 7 + 1 - prevNewYear.getDay();
        if (prevOffset == 2 || prevOffset == 8) weeknum = 53; else weeknum = 52;
    }
	
	//alert(weeknum);
    return ', '+theweek+' '+weeknum;
	
	
	//return ', '+theweek+' '+weeknotemp;
}


function arrivalDayHasChanged(){
	var arrivalday=document.findForm.arrivalday;
	var theweek=$("#search-form").attr('theweek');
	var dage=document.findForm.dage;
    var detectSaturdayTemp = arrivalday.options[arrivalday.selectedIndex].text;
	var A= dage.options;
	var L= A.length; 
	
	//alert('Test');
	
	detectSaturday = detectSaturdayTemp.split(theweek);
	
	//alert(theweek)
	//alert(detectSaturday[0]+" "+detectSaturday[1]);
	
	if(detectSaturday[1] > 0){
	
     while(L){
         if (A[--L].value== 7){
             A.selectedIndex= L;
             L= 0;
         } //if
     } //while
	}//if 
	
		
}//function

function iFrameAutoResize() {
  var iFrame = parent.document.getElementById ? parent.document.getElementById("iframe1") : parent.document.all["iframe1"];
  var iFrameContent = iFrame.contentDocument ? iFrame.contentDocument : document.frames("iframe1").document;
  
  
  if (navigator.appName != 'Microsoft Internet Explorer')
		iFrame.height = iFrameContent.body.offsetHeight ;
   else 
		iFrame.height = iFrameContent.body.scrollHeight; 
} //function     
    
