function year(y) { // some browsers return year - 1900, others don't 
    return (y<1000) ? y + 1900 : y;
}


kMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
function month(m) { // returns human readable month based on int input, 0==january, etc.
    return(kMonths[m]);
}


function daysInMonth(m,y) {
    if(m==2) {
        // February has 29 days in any year evenly divisible by four,
        // EXCEPT for centurial years which are not also divisible by 400.
        return (((y % 4 == 0) && ( (!(y % 100 == 0)) || (y % 400 == 0))) ? 29 : 28);       
    }
    else if(m==4 || m==6 || m==9 || m==11) return 30;
    else return 31;
}


// populate year and month and date selection
function populateDateSelection(formMe) {           
    today = new Date();            

    // year and date
    d = new Date(year(today.getYear()), today.getMonth(), 1);    
    for(i=0; i<12; i++) {               
        // human readable options
        sm = month(d.getMonth());
        sy = year(d.getYear());
                        
        // values for the option
        vm = d.getMonth()+1;
        vy = year(d.getYear());
                
        // set option -- option syntax will be mm,yy
        document.forms[formMe].arrivalMonthYear.options[i] = new Option(sm + " " + sy,vm+","+vy);
        
        d.setMonth(d.getMonth()+1);            
    }
    
    // days
    tm = today.getMonth()+1;
    ty = today.getYear();
    ty = year(ty);
    maxDays = daysInMonth(tm,ty);
     
    for(i=1; i<=maxDays; i++) {
        document.forms[formMe].arrivalDate.options[i-1] = new Option(i,i);
    }
    theDate = today.getDate();
    document.forms[formMe].arrivalDate.selectedIndex = theDate-1;
}


// redo Date
function checkDate(formMe) {

    // in dates
    my = document.forms[formMe].arrivalMonthYear.value.split(","); // month, year            
    im = my[0]; // in month
    iy = my[1]; // in year
    id = document.forms[formMe].arrivalDate.value; // in date

    // current dates
    today = new Date();
    tm = today.getMonth()+1;
    ty = today.getYear();
    ty = year(ty);
    td = today.getDate()-1;
    
    // same month, year - is date less?
    if (iy==ty && im==tm && id<=td) {
        document.forms[formMe].arrivalDate.selectedIndex = td;
    }
}

// redo Month & Year
function checkMonthYear(formMe) {
    
    // in dates
    my = document.forms[formMe].arrivalMonthYear.value.split(","); // month, year            
    im = my[0]; // in month
    iy = my[1]; // in year
    id = document.forms[formMe].arrivalDate.value; // in date
    
    // redo dates
    maxDays = daysInMonth(im,iy);
    document.forms[formMe].arrivalDate.length=0;
    for(i=1; i<=maxDays; i++) {
        document.forms[formMe].arrivalDate.options[i-1] = new Option(i,i);
    }
    
    // is date no longer available?
    if (id > maxDays) {
        document.forms[formMe].arrivalDate.selectedIndex = maxDays-1;
    }
    else document.forms[formMe].arrivalDate.selectedIndex = id-1;
    
    checkDate(formMe);
}


// send form One Bal Harbour
function sendOne() {

    // in dates
    my = document.onebh.arrivalMonthYear.value.split(","); // month, year            
    im = my[0]; // in month
    iy = my[1]; // in year
    id = document.onebh.arrivalDate.value; // in date
    
    ni = parseInt(document.onebh.nights.value);
    ad = parseInt(document.onebh.adults.value);
    ch = parseInt(document.onebh.children.value);
    
    // check rooms
    ro = Math.round(ad/2);

    hotelid = 73042;
    myURL = "https://booking.ihotelier.com/istay/istay.jsp?hotelid=" + hotelid + "&languageid=1";
    myURL += "&DateIn=" + im + "/" + id + "/" + iy;
    myURL += "&Length=" + ni + "&Rooms=" + ro + "&Adults=" + ad + "&Children=" + ch;
    extern=window.open(myURL,'_blank','dependent=no,locationbar=no,menubar=no,resizable=yes,width=1000,height=700,scrollbars=yes,status=no');
    extern.focus();
}


// send form Sea View
function sendSea() {
    
    // in dates
    my = document.sea.arrivalMonthYear.value.split(","); // month, year            
    im = my[0]; // in month
    iy = my[1]; // in year
    id = document.sea.arrivalDate.value; // in date
    
    ni = parseInt(document.sea.nights.value);
    ad = parseInt(document.sea.adults.value);
    ch = parseInt(document.sea.children.value);
    
    // check rooms
    ro = Math.round(ad/2);
    
    document.sea.month.value = im;
    document.sea.day.value = id;
    document.sea.year.value = iy;
    document.sea.rooms.value = ro;
    
    document.sea.submit();
}



// populate year and month and date selection for the Quarzo Bal Harbour booking widget
function populateDateSelectionQuarzo() {           
    var today = new Date();
        //today.setDate(today.getDate()+3);  //The booking widget needs to preset the date to a few days forward for the dates to be received

    // year and date
    var d = today.getDate();
    var m = today.getMonth() 
    var y = today.getFullYear();    
    
    //populate 4 digits numbers for the year, starting with this year and ending 2 years later.
    for(var i=0; i<3; i++){
        var option = document.createElement('option');
        option.value = today.getFullYear() + i;
        option.text = today.getFullYear() + i;
        document.getElementById('CIY').options[i] = option;
    }

    document.getElementById('CID').selectedIndex = d-1; //pre set the day field 
    document.getElementById('CIM').selectedIndex = m; //preset the month field
    document.getElementById('CIY').selectedIndex = 0; //preset the year field
}

function sendQuarzo(){
    //The builtin JS date object is smart enough to advance the year, month, date properly if want to make a guest's stay last one night
    //first we get the date the user selected, then we make it a JS date() object for the check-in date, 
    //then we make a new date object for the check out one day later than the check-in, by default.
    
    //get the DOM objects where the user entered the data
    var inDate = document.getElementById('CID');
    var inMonth = document.getElementById('CIM'); 
    var inYear = document.getElementById('CIY');
    
    //port it to a js date() object
    var checkInDate = new Date();
    checkInDate.setFullYear( inYear.options[inYear.selectedIndex].value,
                        inMonth.options[inMonth.selectedIndex].value-1, //month is 0-zero relative in Javascript (January = 0, February =1, etc), but on the Quarzo server month is 1-relative (January =1, Feb =2), etc.
                        inDate.options[inDate.selectedIndex].value);
    var checkOutDate = new Date( checkInDate.getTime() );
    checkOutDate.setDate( checkOutDate.getDate() + 1 );  //set the checkout date for the next day

    //send the data to the form, and submit the form to Quarzo's server
    document.getElementById('COD').value = checkOutDate.getDate();
    document.getElementById('COM').value = checkOutDate.getMonth()+1;
    document.getElementById('COY').value = checkOutDate.getFullYear();

    document.forms['Res_Form'].submit();
}

//If no leading zero, adds one. Return the result.
//@number = string or number
function addLeadingZero( number ){
	number = number *1; //convert to a number
	if( number < 10 ){
		number = "0" + number;
	}
	return number;
}


//Submit Booking Data to StRegis Booking Engine
function sendStRegis() {	
	//Format Arrival Date Info
	monthNameYear = document.stregis.arrivalMonthYear.value.split(","); // string in format of "month, year"
	monthName = monthNameYear[0]; // this is the month as a string, ex: January
	dayInt = document.stregis.arrivalDate.value; // date as 1, 2, 3, 11, 25
	year = monthNameYear[1]; // year as 4 digit value. No formating required
	arrivalDateObj = new Date( monthName + " " + dayInt + ", " + year); //handles the conversion of month name to month number
	month = addLeadingZero( arrivalDateObj.getMonth()+1 ); //Add a leading zero, make sure January = 01 not 00.
	date = addLeadingZero( dayInt ); //add leading zeros.
	arrivalDate = year + "-" + month + '-' + date; //format our arrival date value
	alert( arrivalDate );
	
	
	//Format Departure Date
	var departDateObj = arrivalDateObj; //Get the arrival date object
	var lengthOfStay = parseInt(document.stregis.nights.value); //Get the number of days staying
	departDateObj.setDate( arrivalDateObj.getDate() + lengthOfStay ); //Add the length of stay to arrival date to get the departure date.
	var departureYear = departDateObj.getFullYear();
	var departureMonth = addLeadingZero( departDateObj.getMonth()+1 ); //zero-relative
	var departureDay = addLeadingZero( departDateObj.getDate() );
	var departureDate = departureYear + '-' + departureMonth + '-' + departureDay;
	
	
	//Set all values necessary for booking engine
	document.stregis.lengthOfStay.value = addLeadingZero( lengthOfStay );
	document.stregis.roomOccupancyTotal.value = addLeadingZero( 1 ); //We're not making this option available, since I'm not sure how the booking engine works on this part exactly
	document.stregis.departureDate.value = departureDate;
	document.stregis.arrivalDate.options.length = 0; //Reconfigure the arrivalDate field. It's used by the existing UI in one format and it's required by the booking widget in another format. This is my compromise to make it work.
	document.stregis.arrivalDate.options[0] = new Option( arrivalDate, arrivalDate, true, true );

	//Remove entries that screw up the booking engine
	jQuery('.stregis-remove-on-submit').remove();

	//Submit info to the booking widget
	document.stregis.submit();
}
