// -------------------------------------------------
// flybooking calendar
//
// needs fly_cal.css
// params for creating calendar objekt
// 1. reference pickup form element
// 2. reference return form element
// 3. id - will be td reference with a "td_" prefix
//    and the radio name with a "rad_" prefix
// 4. language
// 5. object name
//
// params for create_main()
// 1. element to read out (1 or 2)
// 2. read out date or not (1 or 0)
//
// created:     06.7.2004, based on erlier versions
// author:      jw
//
// modified:    10.02.2005
// item:        addLeading0 added to create the
//              leading 0 (needed for new travel_hc)
// author:      jw
//
// modified:    08.03.2005
// item:        add duration_pu and duration_re
//              to make it overridable
// author:      jw
//
// -------------------------------------------------


// set default rental duration 
// 
var duration_pu     =  1; // set duration if pickup is selected
var duration_re     =  1; // set duration if return is before pickup

// all displayed names in different languages
//
var cal_day_names   =  new Array();
var cal_mon_names   =  new Array();
var cal_status_pu   =  new Array(); 
var cal_status_re   =  new Array();

// -------------------------------------------------
// ATTENTION!
// For use in hc some default texts are set in
// override_calendar_vars.jsp
// -------------------------------------------------
//
cal_status_pu["de"] =  "Abflugdatum";
cal_status_re["de"] =  "Rückflugdatum";
cal_day_names["de"] =  new Array("Mo","Di","Mi","Do","Fr","Sa","So");
cal_mon_names["de"] =  new Array("JANUAR","FEBRUAR","MÄRZ","APRIL","MAI","JUNI","JULI","AUGUST","SEPTEMBER","OKTOBER","NOVEMBER","DEZEMBER");

cal_status_pu["en"] =  "departure";
cal_status_re["en"] =  "return";
cal_day_names["en"] =  new Array("Mo","Tu","We","Th","Fr","Sa","Su");
cal_mon_names["en"] =  new Array("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER");

cal_status_pu["fr"] =  "départ";
cal_status_re["fr"] =  "retour";
cal_day_names["fr"] =  new Array("Lu","Ma","Me","Je","Ve","Sa","Di");
cal_mon_names["fr"] =  new Array("JANVIER","FÉVRIER","MARS","AVRIL","MAI","JUIN","JUILLET","AOÛT","SEPTEMBRE","OCTOBRE","NOVEMBRE","DÉCEMBRE");

cal_status_pu["nl"] =  "startdatum";
cal_status_re["nl"] =  "einddatum";
cal_day_names["nl"] =  new Array("Ma","Di","Wo","Do","Vr","Za","Zo");
cal_mon_names["nl"] =  new Array("JANUARI","FEBRUARI","MAART","APRIL","MEI","JUNI","JULI","AUGUSTUS","SEPTEMBER","OKTOBER","NOVEMBER","DECEMBER");

cal_status_pu["da"] =  "departure";
cal_status_re["da"] =  "return";
cal_day_names["da"] =  new Array("man","tirs","ons","tors","fre","lør","søn");
cal_mon_names["da"] =  new Array("januar","februar","marts","april","maj","juni","juli","august","september","oktober","november","december");

cal_status_pu["pt"] =  "retirada";
cal_status_re["pt"] =  "retorno";
cal_day_names["pt"] =  new Array("Seg","Ter","Qua","Qui","Sex","Sab","Dom");
cal_mon_names["pt"] =  new Array("JANEIRO","FEVEREIRO","MARÇO","ABRIL","MAIO","JUNHO","JULHO","AGOSTO","SETEMBRO","OUTUBRO","NOVEMBRO","DEZEMBRO");

cal_status_pu["es"] =  "Fecha de salida";
cal_status_re["es"] =  "Fecha de regreso";
cal_day_names["es"] =  new Array("Lu","Ma","Mi","Ju","Vi","Sa","Do");
cal_mon_names["es"] =  new Array("ENERO","FEBRERO","MARZO","ABRIL","MAYO","JUNIO","JULIO","AGOSTO","SEPTIEMBRE","OCTUBRE","NOVIEMBRE","DICIEMBRE");

cal_status_pu["tr"] =  "Alis tarihi";
cal_status_re["tr"] =  "Dönüs tarihi";
cal_day_names["tr"] =  new Array("Pt","Sa","Ça","Pe","Cu","Ct","Pz");
cal_mon_names["tr"] =  new Array("OCAK","SUBAT","MART","NISAN","MAYIS","HAZIRAN","TEMMUZ","AGUSTOS","EYLÜL","EKIM","KASIM","ARALIK");

cal_status_pu["it"] =  "Data di ritiro";
cal_status_re["it"] =  "Data di riconsegna"; 
cal_day_names["it"] =  new Array("Lun","Mar","Mer","Gio","Ven","Sab","Dom");
cal_mon_names["it"] =  new Array("GENNAIO","FEBBRAIO","MARZO","APRILE","MAGGIO","GIUGNO","LUGLIO","AGOSTO","SETTEMBRE","OTTOBRE","NOVEMBRE","DICEMBRE");

cal_status_pu["pt-br"] =  "retirada";
cal_status_re["pt-br"] =  "retorno";
cal_day_names["pt-br"] =  new Array("Seg","Ter","Qua","Qui","Sex","Sab","Dom");
cal_mon_names["pt-br"] =  new Array("JANEIRO","FEVEREIRO","MARÇO","ABRIL","MAIO","JUNHO","JULHO","AGOSTO","SETEMBRO","OUTUBRO","NOVEMBRO","DEZEMBRO");


function create_calendar (pu_form_el, re_form_el, id, lang) {

    this.obj_name               =  id;    
    this.id                     =  id; 
    this.td_ref                 =  document.getElementById("td_" + id); 
      
    this.form_el                =  new Array();
    this.form_el[1]             =  pu_form_el; 
    this.form_el[2]             =  re_form_el; 
    this.lang                   =  lang;
    
    this.aktDate                =  new Array();
	this.aktMonth               =  new Array();
	this.aktYear                =  new Array();
	this.aktTime                =  new Array();
    
    this.runMonth               =  false;
    this.runYear                =  false;
    
    this.create_main            =  create_main;
    this.get_month_table        =  get_month_table;
    this.get_day_table          =  get_day_table;
    this.get_state_table        =  get_state_table;
    this.get_date               =  get_date;
    this.create_cell            =  create_cell;
    this.nextMonth              =  nextMonth;
    this.pastMonth              =  pastMonth;
    this.outCal                 =  outCal;
    this.addLeading0            =  addLeading0;
}



// create the inner table that contents the status-radio buttons
// IE is not able to create radios the dom way
// so watch out for $MS prop-code
//
function get_state_table () {

    // create some content
    //
    var radio_pu      =  document.createElement("input");
    var radio_re      =  document.createElement("input");     
    var pu_txt        =  document.createTextNode(cal_status_pu[this.lang]);
    var re_txt        =  document.createTextNode(cal_status_re[this.lang]);   
    
    // create table
    //
    var state_table   =  document.createElement("table");
    var state_tbody   =  document.createElement("tbody");
    var state_tr      =  document.createElement("tr");
    var rad_pu_td     =  document.createElement("td");    
    var txt_pu_td     =  document.createElement("td");
    var rad_re_td     =  document.createElement("td");
    var txt_re_td     =  document.createElement("td");
    
    
    // add to dom
    //
    if (document.body.insertAdjacentHTML) {
    
        // first do a little $MS-coding
        //
        rad_pu_td.insertAdjacentHTML('beforeEnd','<input name="rad_"' + this.id + ' type="radio" onclick="self[\'' + this.obj_name + '\'].create_main (1,1)" value="1"' + ((parseInt(this.state) == 1)? " checked='checked'" : "") + '>');
        rad_re_td.insertAdjacentHTML('beforeEnd','<input name="rad_"' + this.id + ' type="radio" onclick="self[\'' + this.obj_name + '\'].create_main (2,1)" value="2"' + ((parseInt(this.state) == 2)? " checked='checked'" : "") + '>');
        
    } else {
    
        // do it the dom way
        // add radio attributes here
        //
        rad_pu_td.appendChild(radio_pu);        
        rad_re_td.appendChild(radio_re);
               
        radio_pu.setAttribute("type","radio");
        radio_pu.setAttribute("value","1");
        radio_pu.setAttribute("name", "rad_" + this.id);        
        radio_pu.onclick =  new Function(this.obj_name + ".create_main (1,1)");        
        if (parseInt(this.state) == 1) radio_pu.setAttribute("checked","checked");
        
        radio_re.setAttribute("type","radio");
        radio_re.setAttribute("value","2");
        radio_re.setAttribute("name", "rad_" + this.id);
        radio_re.onclick =  new Function(this.obj_name + ".create_main (2,1)");
        if (parseInt(this.state) == 2) radio_re.setAttribute("checked","checked");            
    }
    
    txt_pu_td.appendChild(pu_txt); 
    txt_re_td.appendChild(re_txt);
    
    state_tr.appendChild(rad_pu_td);
    state_tr.appendChild(txt_pu_td);
    state_tr.appendChild(rad_re_td);
    state_tr.appendChild(txt_re_td);
    
    state_tbody.appendChild(state_tr);
    state_table.appendChild(state_tbody);
    
    // add some styles and attributes
    //
    state_table.className =  "tableState";
    txt_pu_td.className   =  "calStatePu";
    txt_re_td.className   =  "calState";
    
    return state_table;
}


// create inner table to display the month and the back and next buttons
// use create_cell to return the complete back/next cells with links
//
function get_month_table () {

    var navistyle     =  (this.state == 1)? "calNaviC"  : "calNaviB";
    var cellstyle     =  (this.state == 1)? "calMonthC" : "calMonthB";
    
    var month_table   =  document.createElement("table");     // month table
    var month_tbody   =  document.createElement("tbody");
    var month_tr      =  document.createElement("tr");
    var back_td       =  this.create_cell ("<<", navistyle, "#", this.obj_name + ".pastMonth(" + this.state + ");return false");
    var next_td       =  this.create_cell (">>", navistyle, "#", this.obj_name + ".nextMonth(" + this.state + ");return false");   
    var month_td      =  document.createElement("td");
    
    // create some content for next and back
    //
    var month_name    =  document.createTextNode(cal_mon_names[this.lang][this.aktMonth[this.state]]);  

    // add to dom
    //
    month_td.appendChild(month_name);
        
    month_tr.appendChild(back_td);
    month_tr.appendChild(month_td);
    month_tr.appendChild(next_td);
    
    month_tbody.appendChild(month_tr);    
    month_table.appendChild(month_tbody);  
    
    // add some attributes and styles
    //    
    month_table.setAttribute("width","100%");
    month_table.className =  "tableMonth";
    month_td.setAttribute("align","center");
    next_td.setAttribute("align","right");
    month_td.className    =  cellstyle;
    
    return month_table;
}


// create inner table to display the days
// use create_cell to return the complete day cells with links
//
function get_day_table () {

	// get length of the month
	// get first day
    //
	var firstDay      =  new Date(this.aktYear[this.state], this.aktMonth[this.state], 1);
	this.firstDayId   =  firstDay.getDay();
	this.firstDayId   =  (this.firstDayId > 0)? this.firstDayId - 1 : 6; // Sunday will be the seventh day
    
	// get last day
    //
	var nextMonth     =  new Date(this.aktYear[this.state], this.aktMonth[this.state] + 1 ,1);   // first day next month
	var monthDur      =  nextMonth - (1000*60*60*23);                    // minus one day (23 hours because of summertime)
	var lastDay       =  new Date(monthDur);                             // last day's date
	this.lastDayDate  =  lastDay.getDate();	
    
    // create table now
    //
    var day_table     =  document.createElement("table");     // month table
    var day_tbody     =  document.createElement("tbody");
    var day_name_tr   =  document.createElement("tr"); 
    
    var day_td;
    var day_name_tr;
    var day_tr;
    
    // create 7 daynames
    //
    for (var i = 0; i < 7; i++) { 
    
         day_td =  this.create_cell (cal_day_names[this.lang][i], "calDayName", 0, 0);
         day_td.setAttribute("align","right");
         day_name_tr.appendChild(day_td);         
    } 
    
    // add daynames row to dom
    //
    day_tbody.appendChild(day_name_tr);    
    
    // ---------------------------------------------
    // create every day cell
    // ---------------------------------------------

    var day_cnt   =  1; // daycounter
    var td_cnt    =  0; // cellcounter
    var sty;
    var click_str;

    // create 6 rows
    //
    for (var j = 0; j < 6; j++) {
    
        day_tr =  document.createElement("tr");     
        
        // create 7 days
        //
        for (var k = 0; k < 7; k++) {
            
            // if cell number fits with the days range	
            //	
            if(this.firstDayId <= td_cnt && day_cnt <= this.lastDayDate) {
            
                // past or future
                // get akt dates microtime to caompare
                //
                run_date     =  new Date(this.aktYear[this.state], this.aktMonth[this.state], day_cnt);
                run_microsec =  run_date.getTime();	
                run_date_str =  this.addLeading0(day_cnt) + "." + this.addLeading0(this.aktMonth[this.state] +1) + "." + this.aktYear[this.state];
                click_str    =  this.obj_name + ".outCal('" + run_date_str + "'," + this.state + ");return false;";
                

                if (run_microsec < this.todayTime) {
                
                    // past
                    //
                    day_td =  this.create_cell (day_cnt, "calDaysPast", 0, 0);                    
 
                } else if (run_microsec == this.todayTime && run_microsec == this.aktTime[this.state]) {
                
                    // today equals readout pickup date
                    // readout selected pickup/return date
                    //
                    sty    =  (this.state == 1)? "calPuDate" : "calReDate";            
                    day_td =  this.create_cell (day_cnt, sty, "#", click_str);				
                
                } else if (run_microsec == this.todayTime) {
                
                    // today 
                    //
                    day_td =  this.create_cell (day_cnt, "calToday", "#", click_str);	
                    			
                } else if (run_microsec == this.aktTime[this.state]) {
                    
                    // readout selected pickup/return date
                    //
                    sty    =  (this.state == 1)? "calPuDate" : "calReDate";                    
				    day_td =  this.create_cell (day_cnt, sty, "#", click_str);				

				} else if (td_cnt && (td_cnt +1) % 7 ==  0) {
                
                    // future sunday
                    //
                    day_td =  this.create_cell (day_cnt, "calSunday", "#", click_str);	
                
                } else {
                
                    // future
                    //
                    day_td =  this.create_cell (day_cnt, "calNorm", "#", click_str);	
                }
                day_cnt++;	
            
            } else {
            
                // day_cnt does not fit with days tange
                //
                day_td =  this.create_cell ("00", "calEmpty", 0, 0);
            }
            
            // set attributes to new cell an add to row
            //
            day_td.setAttribute("align","right");
            day_tr.appendChild(day_td);
            
            // count cells
            //
            td_cnt++;
        }
        day_tbody.appendChild(day_tr);
    }
    // ----------------------------------------------
    // end create every day cell
    // ----------------------------------------------      
    day_table.appendChild(day_tbody);   
     
    // some styles and attributes
    //
    day_table.setAttribute("width","100%");
    day_table.className =  "tableDay";
    
    return day_table;
}

// create cell-content
//
function create_cell (txt, style, href, click_str) {
	
	var temp_txt          =  document.createTextNode(txt);
	var temp_td           =  document.createElement("td");
		temp_td.className =  style;
	
	// cell-content is a link?
    //
	if (href) {
		var temp_a            =  document.createElement("a");
		    temp_a.className  =  style;
		    temp_a.onclick    =  new Function(click_str);
		    temp_a.setAttribute("href","#");	
		    temp_a.appendChild(temp_txt);
		    temp_td.appendChild(temp_a);
        
	} else {
		temp_td.appendChild(temp_txt);		
	}
	return temp_td;
}

// delete old content first
// use get_date if use_get_date is set
// create new main calendar table
// add new table to dom 
//
function create_main (state, use_get_date) {

    // first delete old content
    //
    if (this.td_ref.firstChild) this.td_ref.removeChild(this.td_ref.firstChild);	
    
    // what form element was selected
    //
    this.state         =  state;    

    // create todays date or use form date
    // use pickup or return depending on state 
    //
    if (use_get_date) this.get_date();

    // create new content
    //    
    this.main_table    =  document.createElement("table");     // calendar table
    this.main_tbody    =  document.createElement("tbody");
    
    this.main_tr_state =  document.createElement("tr");        // pickup/return-display-row
    this.main_tr_month =  document.createElement("tr");        // month-display-row
    this.main_tr_day   =  document.createElement("tr");           // daytable display row 
       
    this.main_td_state =  document.createElement("td");        // pickup/return display-td
    this.main_td_month =  document.createElement("td");        // month-display-td
    this.main_td_day   =  document.createElement("td");        // month-display-td
    
    // add to dom
    // 
    this.main_td_state.appendChild(this.get_state_table());
    this.main_td_month.appendChild(this.get_month_table());
    this.main_td_day.appendChild(this.get_day_table());
    
    this.main_tr_state.appendChild(this.main_td_state);
    this.main_tr_month.appendChild(this.main_td_month);
    this.main_tr_day.appendChild(this.main_td_day);
    
    // state is only needed if departure and return is available
    //
    if (this.form_el[2]) this.main_tbody.appendChild(this.main_tr_state);    
    this.main_tbody.appendChild(this.main_tr_month);
    this.main_tbody.appendChild(this.main_tr_day);
    
    this.main_table.appendChild(this.main_tbody);

    // add attributes to main table
    //
    this.main_table.className    =  "tableMain";
    
    this.main_td_state.className =  "mainCalState";
    this.main_td_month.className =  "mainCalMonth";
    this.main_td_day.className   =  "mainCalDay";   
    
    // output main table
    //    
    this.td_ref.appendChild(this.main_table);
    
}


function nextMonth(id) {

    // empty old content
    //
    if (this.aktMonth[id] < 12) this.aktMonth[id] += 1;
    if (this.aktMonth[id] == 12) {
        this.aktYear[id]  += 1;
        this.aktMonth[id] =  0;
    }
    this.create_main(id,0);
}

function pastMonth(id) {

    // empty old content
    //
    if (this.aktMonth[id] > -1) this.aktMonth[id] -= 1;
    if (this.aktMonth[id] == -1) {
        this.aktYear[id]  -= 1;
        this.aktMonth[id] =  11;
    }
    this.create_main(id,0);
}

function outCal (val, id) {

	// write selected date into input
    //
	this.form_el[id].value =  val;	
    this.form_el[id].focus();
    
	// setting aktDate back to the input date
    //
	this.get_date();
	
	// check if dates still are plausible
	// return before pickup?	
    //
	if (this.form_el[2] && this.aktDate[2] < this.aktDate[1]) {
		
		if (id == 1) {
        
            // pickup date? add some days
            //
			reD                   =  new Date(this.aktYear[1], this.aktMonth[1], this.aktDate[1].getDate() +duration_pu);
			this.form_el[2].value =  this.addLeading0(reD.getDate()) + "." + this.addLeading0(reD.getMonth() +1) + "." + ((reD.getYear() < 1000)? reD.getYear() +1900 : reD.getYear());
		
		} else {
        
            // return date sub some days unless new date is before today
            //
			puD                   =  new Date(this.aktYear[2], this.aktMonth[2], this.aktDate[2].getDate() -duration_re);
			puD_time              =  puD.getTime();
			if (puD_time >= this.todayTime) this.form_el[1].value =  this.addLeading0(puD.getDate()) + "." + this.addLeading0(puD.getMonth() +1) + "." + ((puD.getYear() < 1000)? puD.getYear() +1900 : puD.getYear());
			else                            this.form_el[1].value =  this.form_el[2].value;
		}	
	}
	this.create_main(id,0);
}


// get date from form-input or take actual date
//
function get_date () {

	// today month, year, day
    //
	var today       =  new Date();
	var todayMon    =  today.getMonth();
	var todayYear   =  (today.getYear() < 1000)? today.getYear() + 1900 : today.getYear();
	var todayDate   =  today.getDate();
    
	// today at 00:00:00
    //
	this.todayDate  =  new Date(todayYear, todayMon, todayDate);
	this.todayTime  =  this.todayDate.getTime();	
    
    var date, reg, datArr;
	
	// check form input2 or use todays date
	for (var i = 1; i < 3; i++) {
    
        date =  (this.form_el[i])? this.form_el[i].value : 0;
        reg  =	/^([0-9]{1,2})[\.\,]([0-9]{1,2})[\.\,]([0-9]{2,4})$/;
		
		if(reg.exec(date)) {
			datArr    =  reg.exec(date);
			datArr[3] =  (datArr[3].length == 2)? "20" + datArr[3] : datArr[3];
			datArr[2] =  (datArr[2] > 0 )? datArr[2] - 1 : 11;
			this.aktDate[i] =  new Date(datArr[3], datArr[2], datArr[1]);
		} else {
			this.aktDate[i] =  this.todayDate;
		}
        
        // actual date to display
        //        
		this.aktMonth[i] =  this.aktDate[i].getMonth();
		this.aktYear[i]  =  (this.aktDate[i].getYear() < 1000)? this.aktDate[i].getYear() + 1900 : this.aktDate[i].getYear();
		this.aktTime[i]  =  this.aktDate[i].getTime();
	}
}

// adds the leading 0 if day or month < 10
//
function addLeading0 (val) {
   return (val < 10)? "0" + val : val;
}
