/**
* Checks if destination is selected and checks departure and return dates and 
* returns false if destination is not selected or the return date is before the departure date
* or if the date is invalid (i.e. Feb 30). 
* Also checks if total number of passenges per booking exceeds 6
* @param form object
* @return true if search parameters ok
**/
function validateSearch(form)
{
	var roundtrip; //set to true if roundtrip
	//max number of pax is 6
	var pax=(form.adt.value-0)+(form.chd.value-0)+(form.inf.value-0); //-0 forces the variable to become numeric
//	if(pax>6) {
//		alert('Maks. antall passasjerer pr. booking er 6!'); NB20090604 rettet etter forespørsel fra B-H
	if(pax>9) {
		if (form.site.value=='bh') {
			alert("Maks. antall passasjerer pr. booking er 9! Ta kontakt med Gruppeopplevelser: www.berg-hansen.no/gruppeopplevelser"); 
		} 
		else {
			alert('Maks. antall passasjerer pr. booking er 9!'); 
		}
		form.adt.focus();
		return false;
	} 

	//Checking if destination is selected
	if(form.depcd.value == form.destcd.value) {alert('Velg en destinasjon!'); form.destcd.focus();return false}; 
	var monthArray=new Array ("Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember");

	var dy=form.dm.value.substr(0,4)-0;	//force the variable to become numeric by subtracting 0
	var dm=form.dm.value.substr(5,2)-1; //from 1 index to 0 index
	var dd=form.dd.value-0;

	//check if departure date is a valid date
	var dim=getMonthDays(dy, dm); //get the number of days in the month
	if (dim<dd) {
		//form.dd.value=dim; //set the day-part of the date to the max number of dates of selected month
		alert("Ugyldig Avreise dato!\nDet er kun "+dim+" dager i "+monthArray[dm]+"!")
		return false;
	}

	//check if departure date is at least 7 days or 3 days ahead of current date
	var depDate=new Date(dy, dm, dd);
	var depDays=Math.round(depDate.getTime()/(1000*3600*24)); 	//number of days since Jan 1, 1970
																//returns decimals after division, but should not
	//checking if units is a defined in the form
	var daystogo;
	if ( typeof ( form.units ) == "undefined" ) {
		daystogo=3; //3 days to earliest departure for flights
	}
	else {
		roundtrip=true; //cityweekend
		daystogo=7;	//7 days to earliest departure for cityweekend
	}
	
	var nowDate=new Date();
	var firstDays=nowDate.getTime()/(1000*3600*24)+daystogo;

	firstDays = Math.floor(firstDays); //truncates
	
	if (depDays<firstDays) {
		alert("Avreise dato kan ikke v"+String.fromCharCode(230)+"re tidligere enn "+daystogo+" dager frem i tid!"); 
		return false;
	}

	if (!roundtrip) {
		if	(form.owrt[0].checked) roundtrip = true;
	}
	
	if (roundtrip) {
		//return date is only checked if city weekend (always roundtrip) or flight roundtrip
		var ry=form.rm.value.substr(0,4)-0; 
		var rm=form.rm.value.substr(5,2)-1; 
		var rd=form.rd.value-0; 

		//check if return date is av valid date
		dim=getMonthDays(ry, rm); //get the number of days in the month
		if (dim<rd) {
			//form.rd.value=dim; //set the day-part of the date to the max number of dates of selected month
			alert("Ugyldig Retur dato!\nDet er kun "+dim+" dager i "+monthArray[dm]+"!")
			return false;
		}

		//check that return date is no earlier than departure date
		//increase the return month with one and keep the day-part of the return date intact
		var retDate=new Date(ry, rm, rd);
		var retDays=Math.round(retDate.getTime()/(1000*3600*24)); //number of days since Jan 1, 1970

		var daysFromDepToRet;
		daysFromDepToRet=retDays-depDays;

		if (daysFromDepToRet<0)  { //NB 20070812 kun sjekk dersom tur/retur reise
			alert("Avreise dato kan ikke komme etter Retur dato");
			return false;
		}
	}

	return true;
}

	
/**
* Finds the month one month in the future
* @param dt Date object containing todays date
* @param ret 1 if month for return is requested which is 4 days after the date for departure
* @return the same Date object as parameter moved approx one month in the future
**/
function nextMonthDate(dt, ret) {
	dt.setDate(dt.getDate() + 32 + ret * 4 - dt.getDay());
	return dt;
}

/** 
* Returns the number of days in the current month 
* @param y full year as YYYY
* @param m month as 0, ..., 11
* @returns number of days in month matching the parameters
**/
function getMonthDays(y, m) {
	var mdays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if (((0 == (y%4)) && ( (0 != (y%100)) || (0 == (y%400)))) && m == 1) {
		return 29;
	} else {
		return mdays[m];
	}
}
	
/**
* Fills the month select box with months i.e. Jan 2007 and marks a monthr as selected.
* The month marked as selected is a month approximately one month in the past, and 
* one month and 4 days if it is the months for the return date
* ret - 1 if months of return date, 0 if months of departure date
* NOTE: This function is not used since is it identical to month(lang, selected)
*/
function months_NEW(lang, ret)
{
	var monthString="Jan,Feb,Mar,Apr,Maj,Jun,Jul,Aug,Sep,Okt,Nov,Des";
	if(lang == 'no') {monthString="Jan,Feb,Mar,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Des"};
	if(lang == 'en') {monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"};
	var time = new Date();
	var year = time.getYear();
	var month = time.getMonth();
	var dmonth=1+(nextMonthDate(time, ret)).getMonth(); //finds the month approx. 1 month in the future
	var months = 12;
	if (year < 1900) { year = year + 1900; }
	do {months--; month++; 
		if(month>12){year++;month=1}
		var lz = '';
	
		if(month < 10){lz = '0'}
		var seltext = '';
		document.writeln("<OPTION" + seltext + " value=\"" + year + "-" + lz + month + "\">" + monthString.split(",")[month-1]+" x"+year); //NB20060926 year appended

	} while (months > 0);
}

function months(lang,selected)
{
	/* selected: 0=torsdag, 1=mandag */
	var monthString="Jan,Feb,Mar,Apr,Maj,Jun,Jul,Aug,Sep,Okt,Nov,Des";
	if(lang == 'no') {monthString="Jan,Feb,Mar,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Des"};
	if(lang == 'en') {monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"};
	var time = new Date();
	var year = time.getYear();
	var month = time.getMonth();
	time.setDate(time.getDate() + 32 + selected * 4 - time.getDay());
	var dmonth = 1 + time.getMonth();
	if(selected == 'x') dmonth = null;
	var months = 12;
	if (year < 1900) { year = year + 1900; }
	do {months--; month++; 
		if(month>12){year++;month=1}
		var year2digits=year%100;
		if (year2digits<10) year2digits='0'+year2digits;
		var lz = '';
		if(month < 10){lz = '0'}
		var seltext = '';
		if(month==dmonth){seltext = ' selected';}
		document.writeln ("<OPTION" + seltext + " value=\"" + year + "-" + lz + month + "\">" + monthString.split(",")[month-1]+" "+year2digits); //NB20060926 year appended
	} while (months > 0);
}

/**
* Fills the day select box with days 01, ..., 31 and marks a day as selected.
* The day marked as selected is a day approximately one month in the past, and 
* one month and 4 days if it is the days for the return date
* ret - 1 if days of return date, 0 if days of departure date
* NOTE: Since this function is only called once the number of months must be 31 for each month.<b> 
*		This function is therefore not in use, but is kept as reference if needed later.
*/
function days_NEW(ret)
{	
	var time = new Date();
	time=nextMonthDate(time, ret); //finds the date approx. 1 month in the future
	var dyear = time.getFullYear();
	var dmonth=time.getMonth();
	var dday = time.getDate();

	var day = 0; 
	var selected=''; 
	var md=getMonthDays(dyear, dmonth);
	while(++day <= md)
	{
		selected = '';
		if(day==dday){selected = ' selected';}
		if(day<10){day = '0' + day}
		document.writeln("<OPTION" + selected + " VALUE=" + day + ">" + day);
	}
}

function days(selected)
{	
	/* selected: 0=torsdag, 1=mandag */
	var time = new Date();
	time.setDate(time.getDate() + 32 + selected * 4 - time.getDay());
	var dday = time.getDate();
	var day = 0;
	while(++day < 32)
	{
		selected = '';
		if(day==dday){selected = ' selected';}
		if(day<10){day = '0' + day}
		document.writeln("<OPTION" + selected + " VALUE=" + day + ">" + day);
	}
}


/**
* The function checks that certain rules for the out and return dates are asserted.
* The out and return dates are changed to abey the rules. This is not a good solution,
* so the functionality of this function has been moved to validateSearch(form) which is called
* when the search form is submitted.
**/
function checkDates(form) {
	function lz(d) {
		var lz="";
		if (rm<10)
		lz="0"
		return lz+d;
	}
	//var monthArray=new Array ("Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember");
	var dy=form.dm.value.substr(0,4)-0;	//force the variable to become numeric by subtracting 0
	var dm=form.dm.value.substr(5,2)-1; //from 1 index to 0 index
	var dd=form.dd.value-0;
	var ry=form.rm.value.substr(0,4)-0; 
	var rm=form.rm.value.substr(5,2)-1; 
	var rd=form.rd.value-0; 
	//check if departure date is a valid date
	var dim=getMonthDays(dy, dm); //get the number of days in the month
	if (dim<dd) {
		form.dd.value=dim; //set the day-part of the date to the max number of dates of selected month
		//alert("Ugyldig utreisedato!\nDet er kun "+dim+" dager i "+monthArray[dm]+"!")
		//return false;
	}
	//check if departure date is at least 7 days ahead of current date
	var depDate=new Date();
	depDate.setFullYear(dy);
	depDate.setMonth(dm);
	depDate.setDate(dd);

	var depDays=depDate.getTime()/(1000*3600*24); //number of days since Jan 1, 1970
	var nowDate=new Date();
	var firstDays=nowDate.getTime()/(1000*3600*24)+7;
	if (depDays<firstDays) {
		alert("Avreisedato kan ikke v"+String.fromCharCode(230)+"re tidligere enn 1 uke frem i tid!"); 
		depDate.setTime(firstDays*1000*3600*24); //converting from days to msecs since Jan 1, 1970
		form.dm.value=depDate.getFullYear()+"-"+lz(depDate.getMonth()+1); //year and date
		form.dd.value=depDate.getDate();	//the day of the month
	}

	//check that return date is no earlier than departure date
	//increase the return month with one and keep the day-part of the return date intact
	var retDate=new Date();
	var daysFromDepToRet;
	do {
		retDate.setFullYear(ry);
		retDate.setMonth(rm);
		retDate.setDate(rd);
		daysFromDepToRet=(retDate.getTime()-depDate.getTime())/(1000*3600*24);
		//alert("diff: "+daysFromDepToRet);
		if (daysFromDepToRet<0) {
			//alert("Before adjustment ry: "+ry+" rm: "+rm+" rd: "+rd);
			ry=dy;
			rm+=1;
			if (rm>11) {
				ry+=1;
				rm=0;
			} 
			//alert("After adjustment ry: "+ry+" rm: "+rm+" rd: "+rd);
			form.rm.value=ry+"-"+lz(rm+1);
		}
	} while (daysFromDepToRet<0)
	return true;
}

// function f?r att hemresan skall st?lla in sig tre dagar efter utresan
function checkdate()
{
	// h?r st?ller du in hur m?nga dagar hemresan skall skjutas fram?t!

	//Programmet fungerer ikke bra nok n?r man velger dato i januar
	return;
	var reslangd=2;
	var utar=document.form1.dm.value.substr(0,4);
	var utmanad=document.form1.dm.value.substr(5,2);
	utmanad--;
	var utdag=document.form1.dd.value;
	var hemar=document.form1.rm.value.substr(0,4);
	var hemmanad=document.form1.rm.value.substr(5,2);
	hemmanad--;
	var hemdag=document.form1.rd.value;
	
	var utdatum = new Date(utar,utmanad,utdag);
	var hemdatum = new Date(hemar,hemmanad,hemdag);
	// h?r kollar jag s? att datumet f?r utresan verkligen finns!
			dagen1=utdatum.getDate()
			utdatum.setDate(dagen1);
		
			var testl=utdatum.getYear();
			if(testl<1900)
				{
					testl=testl+1900;
				}
			var tjo1=testl;
			tjo1=tjo1 + '-';
			hej1=utdatum.getMonth();
			hej1++;
			tjo1=tjo1+hej1;
			document.form1.dm.value=tjo1;
			document.form1.dd.value=utdatum.getDate();
	
	// h?r s?tter jag r?tt hemdatumet
		
	if (hemdatum < utdatum)
		{
			hemdatum=utdatum;
			dagen=hemdatum.getDate()
			dagen+=reslangd;
			hemdatum.setDate(dagen);
		}
		var test=hemdatum.getYear();
		if (test<1900)
			{
			test=test+1900;
			}
			//document.write(test);
		var tjo=test; //hemdatum.getYear() + '-';
		tjo=tjo + '-';
		hej=hemdatum.getMonth();
		hej++;
		tjo=tjo+hej;		
		document.form1.rm.value=tjo;
		document.form1.rd.value=hemdatum.getDate();		
}	

function CheckEmail(eadress){
        if(eadress==""){
         alert("Vennligst angi en gyldig e-post adresse!");
		 return false;
        }
        if(!/^.+@.+\..+$/.test(eadress)){
        alert("Vennligst angi en gyldig e-post adresse!");
        return false;
        }
      return true;
}

function bValidate(form)
{
	if(form.addressat.value.length < 3) {alert("Vennligst legg inn navn!"); form.addressat.focus();return false}; 
	if(form.zip.value.length < 4) {alert("Vennligst legg inn postnummer!"); form.zip.focus();return false}; 
	if(form.city.value.length < 3) {alert("Vennligst legg inn poststed!"); form.city.focus();return false}; 
	if(form.tlf.value.length < 8) {alert("Vennligst legg inn telefonnummer!"); form.tlf.focus();return false}; 
	if(!CheckEmail(form.email.value)){form.email.focus();return false};
	if(!form.agency.value) {alert("Vennligst velg et reisebyra!"); form.agency.focus();return false}; 
	if(!form.conditions.checked) {alert("Vennligst les og aksepter betingelsene!"); form.conditions.focus();return false}; 
	if(form.cardnr.value.length < 14) {alert("Vennligst legg inn et kortnummer 14-16 siffer!"); form.cardnr.focus();return false}; 
	return true;
}

function sValidate(form)
{
	if(form.depcd.value == form.destcd.value) {alert('Velg en destinasjon!'); form.destcd.focus();return false}; 
	if(form.dm.value > form.rm.value || (form.dm.value == form.rm.value && form.dd.value > form.rd.value)) {alert('Returdato etter avreisedato!'); form.rm.focus();return false}; 
	return true;
}
	
