
/*-------------------------------------------------------------------
 *	Generic class that enables you to manage a stack of objects
 *  Nurun @Copyright
 *------------------------------------------------------------------*/
StackObject = function(){
	this.objects = new Array();
}

StackObject.prototype.addObject = function(obj){
	if(this.getObject(obj.id)==null)
		this.objects[this.objects.length] = obj;
	else
		this.objects[this.getIndex(obj.id)] = obj;
}

StackObject.prototype.getObject = function(id){
	var returnValue = null;
	for(var count=0;count<this.objects.length;count++)
	{	
		if(this.objects[count].id==id)
		{
			returnValue = this.objects[count];
			break;
		}
	}
	return returnValue;
}

StackObject.prototype.getIndex = function(id){
	var returnValue = null;
	for(var count=0;count<this.objects.length;count++)
	{	
		if(this.objects[count].id==id)
		{
			returnValue = count;
			break;
		}
	}
	return returnValue;
}

var STACK_OBJECT = new StackObject();

 // Base object
 
 AbstractObject = function(id){
	this.id = id;
	this.parentListener = null;
	this.srcEvent = null;
	STACK_OBJECT.addObject(this);
 }
 
 AbstractObject.prototype.addParentListener = function(obj){
	this.parentListener = obj;
 }
 
 AbstractObject.prototype.getParentListener = function(){
	return(this.parentListener);
 }
 
 AbstractObject.prototype.getSrcEvent = function(){
	return(this.srcEvent);
 } 

 AbstractObject.prototype.notifyEvent = function(method){
	if(this.parentListener==null) return;
	this.parentListener.srcEvent = this;
	eval("this.parentListener"+"."+method);
 }
 /*
 Generic function enables you to fire customs events.
*/
function fireEventListener(targeted,method) {
	var myTargetElement = STACK_OBJECT.getObject(targeted);
	eval("myTargetElement"+"."+method);
}
 
/*-------------------------------------------------------------------
 *	Generic class that enables you to create a calendar for Europcar
 *  Nurun @Copyright
 *------------------------------------------------------------------*/
 // Calendar management //

var CONST_DAYS_en = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');


//var CONST_MONTHS = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Bug id==6895: is supposed to be a temprary solution: introduce the locale for internationalisation ==> see calendar.js
//	Need a refactorisation

var CONST_MONTHS_en = new Array('January','February','March','April','May','June','July','August','September','October','November','December');


function getMonths(curLocale,defLocale) {
	try {
		var months	=	eval("CONST_MONTHS_"+curLocale);
		return months;
	} catch(e1) {
		try {
			var defMonths	=	eval("CONST_MONTHS_"+defLocale);
			return defMonths;
		} catch(e2) {
			return eval("CONST_MONTHS_en");
		}		
	}
}


function getDays(curLocale,defLocale) {
	try {
		var months	=	eval("CONST_DAYS_"+curLocale);
		return months;
	} catch(e1) {
		try {
			var defMonths	=	eval("CONST_DAYS_"+defLocale);
			return defMonths;
		} catch(e2) {
			return eval("CONST_DAYS_en");
		}		
	}
}

 
//Constructor
Calendar = function(id, currentDate){
	
	this.base = AbstractObject;
	this.base(id);
	this.dateObject = currentDate;
	this.month		= currentDate.getMonth();
	this.date		= currentDate.getDate();
	this.day		= currentDate.getDay();
	this.year		= currentDate.getFullYear();
	this.dates		= new Array();
	this.maximumDate = null;
	
	currentDate.setDate(1);
	this.firstDay	= currentDate.getDay();
	currentDate.setDate(this.date);
}

Calendar.prototype = new AbstractObject;

Calendar.prototype.setMaximumDate = function(maximumDate) {
	this.maximumDate = maximumDate;
}


//Render the calendar

Calendar.prototype.writeCalendar = function(check, container){
	var calString = '<div id="' + this.id + '">';
	calString += '<table id="cal' + this.id + '" cellspacing="0" style="border:1px black solid;">';
	//calString += '<tr><th colspan="6" class="month">&nbsp;' + CONST_MONTHS[this.month] + ',&nbsp;' + this.year + '</th>';
	calString += '<tr><th colspan="6" class="month">&nbsp;' + getMonths(getCurrentLocale(),getDefaultLocale())[this.month] + ',&nbsp;' + this.year + '</th>';
	if (check.indexOf("first")!=-1)
	{
		//calString += '<td class="navCalendar" colspan="7" align="center" style="font-size: 16px;" onClick="changeMonth(-1)">&lt;</td>';
		calString += '<td class="navCalendar" colspan="7" align="center" style="font-size: 16px;" onClick="javascript:fireEventListener(\''+this.parentListener.id+'\',\'changeMonth(-1);\');"><img src="../images/picto_calendar_lastmonth.jpg"></td>';
	}else
	{
		//calString += '<td class="navCalendar" colspan="7" align="center" style="font-size: 16px;" onClick="changeMonth(1)">&gt;</td>';
		calString += '<td class="navCalendar" colspan="7" align="center" style="font-size: 16px;" onClick="javascript:fireEventListener(\''+this.parentListener.id+'\',\'changeMonth(1);\');"><img src="../images/picto_calendar_nextmonth.jpg"></td>';
	}

	//calString += '<td class="navCalendar" style="font-size: 16px;text-decoration:underline;" onClick="changeMonth(-12,\'' + this.id + '\')">&lt;</td>';
	//calString += '<td class="navCalendar" style="font-size: 16px;" onClick="changeMonth(-1)">&lt;</td>';
	//calString += '<td class="month" colspan="3">&nbsp;</td>';
	//calString += '<td class="navCalendar" style="font-size: 16px;" onClick="changeMonth(1)">&gt;</td>';
	//calString += '<td class="navCalendar" style="font-size: 16px;text-decoration:underline;text-align:right;" onClick="changeMonth(12,\'' + this.id + '\')">&gt;</td>';
	calString += '</tr>';	calString += '<tr>';
	
	var DAYS = getDays(getCurrentLocale(),getDefaultLocale());
	for(i=0;i<DAYS.length;i++){
		calString += '<th class="dayHeader">' + DAYS[i].substring(0,1) + '</th>';
	}
	
	calString += '<tr class="week">';
	for(var j=0;j<42;j++){
		var displayNum = (j-this.firstDay+1);
		var dateToKnow = buildTempDate(this.year,this.month,displayNum);
		this.dates[j] = dateToKnow;
		if(j<this.firstDay){
			calString += '<td class="empty">&nbsp;</td>';
		}else if(displayNum > getLength((this.month), this.year)){
			calString += '<td>&nbsp;</td>';
		}else if(this.maximumDate!=null && dateToKnow>buildCompareDate(this.maximumDate)) {
			calString += '<td id="'+dateToKnow+'" class="unselectableDays" align="center">' + displayNum + '</td>';					
		}else if(displayNum<(new Date()).getDate() && this.month==(new Date()).getMonth() && this.year==(new Date()).getFullYear()){
			calString += '<td id="'+dateToKnow+'" class="unselectableDays" align="center">' + displayNum + '</td>';
		}else if(j%7==6 || j%7==0){
			calString += '<td id="'+dateToKnow+'" class="weekend"  align="center" onClick="javascript:fireEventListener(\''+this.id+'\',\'setIndex('+j+',true)\');">' + displayNum + '</td>';
		}else{
			calString += '<td id="'+dateToKnow+'" class="days"  align="center" onClick="javascript:fireEventListener(\''+this.id+'\',\'setIndex('+j+',true)\');">' + displayNum + '</td>';
		}
		if(j%7==6){
			calString += '</tr><tr  class="week">';
		}
	}
	calString += '</tr>';
	
	
	calString += '</table>';
	calString += '</div>';	
	getObj(container).innerHTML = calString;
}


//set current date
Calendar.prototype.setIndex = function(index,notify){	
	var date = this.dates[index];
	this.currentDate = buildDate(date);
	this.refreshSelection();
	//alert(date);
	for(var i=2;i<8;i++)
	{
		//get line with values
		var p = getObj(this.id).childNodes[0].childNodes[0].childNodes[i].childNodes;
		if(p==null) continue;
		for(var pi=0;pi<p.length;pi++)
		{
			var dayCurrent = parseInt(p[pi].firstChild.nodeValue, 10);
			var compare = buildTempDate(this.year, this.month, dayCurrent);
			if(compare==date)
			{				
				p[pi].className = (p[pi].className!="weekend")?"date":"weekendselected";
				if(notify)
					this.notifyEvent("setDate('"+date+"');");
			}
		}		
	}	
}

//retrieve date
Calendar.prototype.setCurrentDate = function(date){	
	var returnValue = -1;
	for(var count=0;count<this.dates.length;count++)
	{
		if(this.dates[count]==date)
		{
			returnValue = count;
			break;
		}
	}
	if(returnValue!=-1)
		this.setIndex(returnValue,false); 
}


//refresh selection in the calendar
Calendar.prototype.refreshSelection = function(){
	for(i=2;i<8;i++)
	{
		var p = getObj(this.id).childNodes[0].childNodes[0].childNodes[i].childNodes;
		if(p==null) continue;
		for(pi=0;pi<p.length;pi++)
		{
				if(!eval("p[pi].className")) break;
				if(p[pi].className=="date")
					p[pi].className = "days";
					
				if(p[pi].className=="weekendselected")
					p[pi].className = "weekend";
		}
	}
}
//return an object
function getObj(id){
	return document.getElementById(id);
}


/* Statics functions enables you to manage date */
//just to know how many days are in a month...
function getLength(month, year){
	switch(month){
		case 1:
			if((year%4==0&&year%100!=0)||year%400==0)
				return 29; 
			else
				return 28;
		case 3:
		case 5:
		case 8:
		case 10:
			return 30;
		default:
			return 31;
	}
}


function buildTempDateWithMonth(yearmonth, day)
{
	var temp = (yearmonth.substring(0,4)*10000) + ((yearmonth.substring(4,6)-1)*100) + day;
	return temp;
}

function buildTempDate(year, month, day)
{
	var temp = (year*10000) + (month*100) + day;
	return temp;
}


function buildCompareDate(date)
{
	var temp;
	var year = date.getFullYear();
	var month = date.getMonth();
	var day = date.getDate();
	var temp = (year*10000) + (month*100) + day;
	return temp;
}

function buildDate(date)
{
	var myDate = new Date();
	myDate.setDate(findDay(date));
	myDate.setMonth(findMonth(date));
	myDate.setFullYear(findYear(date));
	return myDate;
}

function findDay(obj)
{
	var day = parseInt(obj.toString().substring(6,8),10);
	return day;
}

function findMonth(obj)
{
	var month = parseInt(obj.toString().substring(4,6),10);
	return month;
}

function findYear(obj)
{
	var year = parseInt(obj.toString().substring(0,4),10);
	return year;
}

function findMonthYear(obj)
{
	var monthyear = parseInt(obj.toString().substring(0,8),10);
	return monthyear;
}

function findHour(obj)
{
	var hour = parseInt(obj.toString().substring(8,10),10);
	return hour;
}

function findMinute(obj)
{
	var minute = parseInt(obj.toString().substring(10,12),10);
	return minute;
}



//europcar calendar
EuropcarCalendar = function(id, date, container){
	this.base = AbstractObject;
	this.base(id);
	this.date = buildDate(date);
	this.currentPeriod = buildDate(date);
	this.createCalendars(this.date);
	this.container = container;
	this.maxDate = new Date();
}

EuropcarCalendar.prototype = new AbstractObject;

EuropcarCalendar.prototype.setMaxDate = function(date) {
	this.maxDate = date;
	this.createCalendars(this.date);
}

EuropcarCalendar.prototype.setDate = function(date){
	var myObj = (this.srcEvent.id.indexOf("firstCalendar")!=-1)?this.secondCalendar:this.firstCalendar;
	myObj.refreshSelection();
	this.date = buildDate(date);
	this.notifyEvent("setDateFromCalendar('"+date+"');");
	this.hide();
}

EuropcarCalendar.prototype.createCalendars = function(date){
	this.firstCalendar = new Calendar("firstCalendar"+this.id, date);
	if(this.maxDate!=undefined) 
		this.firstCalendar.setMaximumDate(this.maxDate);
	this.firstCalendar.addParentListener(this);
	date.setMonth(date.getMonth()+1);
	this.secondCalendar = new Calendar("secondCalendar"+this.id, date);
	if(this.maxDate!=undefined)
		this.secondCalendar.setMaximumDate(this.maxDate);
	this.secondCalendar.addParentListener(this);
	date.setMonth(date.getMonth()-1);	
	this.firstCalendar.writeCalendar("first"+this.id, "container1"+this.id);
	this.secondCalendar.writeCalendar("second"+this.id, "container2"+this.id);

	this.firstCalendar.setCurrentDate(buildCompareDate(this.date));
	this.secondCalendar.setCurrentDate(buildCompareDate(this.date));
}

EuropcarCalendar.prototype.changeMonth = function(compare){

	this.currentPeriod.setMonth(this.currentPeriod.getMonth()+compare);
	if(
		((this.currentPeriod.getMonth()>=(new Date()).getMonth() && this.currentPeriod.getFullYear()==(new Date()).getFullYear() ) 
		||
		( this.currentPeriod.getFullYear()>(new Date()).getFullYear() ))
		 && 
		this.currentPeriod < this.maxDate) {
		this.createCalendars(this.currentPeriod);
	}
	else {
		this.currentPeriod.setMonth(this.currentPeriod.getMonth()-compare);
	}
}

EuropcarCalendar.prototype.show = function(){
	getObj(this.container).style.display = "block";
}

EuropcarCalendar.prototype.hide = function(){
	getObj(this.container).style.display = "none";
}


//europcar form

var CONST_PREFIX				= "reservation";
var CONST_DIFF					= 2; //difference between two dates
var CONST_CHECKOUT				= "checkout";
var CONST_CHECKIN				= "checkin";
var CONST_SELECT_DAYS			= "day";
var CONST_SELECT_MONTHYEAR		= "monthyear";
var CONST_SELECT_HOUR			= "hour";
var CONST_SELECT_MINUTE			= "minute";


EuropcarForm = function(){
	this.base = AbstractObject;
	this.base("EuropcarForm");
	
	//specific creation of months
	this.init(CONST_CHECKOUT);
	this.init(CONST_CHECKIN);

	//get the limit of date
	this.maxDateCheckout = (maximumDate!=null)?buildDate(maximumDate):buildDate(this.getMaximumDate(CONST_CHECKOUT));
	//this.maxDateCheckin = (maximumDate!=null)?buildDate(maximumDate):buildDate(this.getMaximumDate(CONST_CHECKIN));
	this.maxDateCheckin = buildDate(this.getMaximumDate(CONST_CHECKIN));
	this.maxDateCheckout.setMonth(this.maxDateCheckout.getMonth());
	this.maxDateCheckin.setMonth(this.maxDateCheckin.getMonth());
	
	//intiliaze calendars
	var myDate = buildDate(this.getDate(CONST_CHECKOUT));
	//this.setSelect(CONST_CHECKOUT,buildCompareDate(myDate));
	myDate.setDate(myDate.getDate()+CONST_DIFF);
	//this.setSelect(CONST_CHECKIN,buildCompareDate(myDate));	
}

EuropcarForm.prototype = new AbstractObject;

EuropcarForm.prototype.createEuropcarCalendar = function(where,date){
	var myEuropcarCalendar = new EuropcarCalendar(where, buildCompareDate(date),where+"calendar");
	if(where==CONST_CHECKOUT)
		myEuropcarCalendar.setMaxDate(this.maxDateCheckout);
	else
		myEuropcarCalendar.setMaxDate(this.maxDateCheckin);
	myEuropcarCalendar.show();
	myEuropcarCalendar.addParentListener(this);	
}


EuropcarForm.prototype.closeCalendar = function(where) {
	var myEuropcarCalendar = new EuropcarCalendar(where, new Date(),where+"calendar");	
	myEuropcarCalendar.show();
	myEuropcarCalendar.hide();
}

EuropcarForm.prototype.setDateFromCalendar = function(date){
	this.setSelect(this.srcEvent.id,date);
	this.verifyRules(this.srcEvent.id);
	this.eventFromChangeDay(CONST_CHECKOUT);
}

EuropcarForm.prototype.eventFromSelect = function(where){
	var date = this.getDate(where);
	this.setSelect(where,date);
	this.verifyRules(where);
}

EuropcarForm.prototype.eventFromSelectDay = function(where){
	var date = this.getDate(where);
	this.verifyRules(where);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EuropcarForm.prototype.eventFromChangeDay = function(where){
	var date = this.getDate(where);
	var now = new Date();
	//alert(now.getDate());
	if (findDay(date)==now.getDate())
		if (findMonth(date)==now.getMonth())
			if (findYear(date)==now.getYear()){
				var selectHour		= CONST_PREFIX+where+CONST_SELECT_HOUR;
				var selectMinute	= CONST_PREFIX+where+CONST_SELECT_MINUTE;
				var hours = (now.getHours()+2)%23;
				
				setValue(selectHour, hours );
				setValue(selectMinute, Math.round(now.getMinutes()/15) * 15);
				
			}
					
}
EuropcarForm.prototype.show = function(where){
	this.createEuropcarCalendar(where, buildDate(this.getDate(where)));
}

EuropcarForm.prototype.verifyRules = function(where){
	if(this.getDate(CONST_CHECKOUT)>this.getDate(CONST_CHECKIN))
	{
		var myDate = buildDate(this.getDate(where));
		if(where == CONST_CHECKOUT)	{
		var now = new Date();
		//alert(now.getDate());
		if (findDay(myDate)==now.getDate())
			if (findMonth(myDate)==now.getMonth())
				if (findYear(myDate)==now.getYear()){
					var selectHour		= CONST_PREFIX+where+CONST_SELECT_HOUR;
					var selectMinute	= CONST_PREFIX+where+CONST_SELECT_MINUTE;
					var hours = (now.getHours()+2)%23;
					
					setValue(selectHour, hours );
					setValue(selectMinute, Math.round(now.getMinutes()/15) * 15);
					
				}		
		myDate.setDate(myDate.getDate()+CONST_DIFF);
		this.setSelect(CONST_CHECKIN,buildCompareDate(myDate));
		} 
		else {			
//			myDate.setDate(myDate.getDate()-CONST_DIFF);
//			this.setSelect(CONST_CHECKOUT,buildCompareDate(myDate));
		}
	}		
}

EuropcarForm.prototype.setSelect = function(where,date){
	var day		= findDay(date);
	var month	= findMonth(date);
	var year	= findYear(date);
	var selectDay		= CONST_PREFIX+where+CONST_SELECT_DAYS;
	var selectMonthYear	= CONST_PREFIX+where+CONST_SELECT_MONTHYEAR;
	getObj(selectDay).options.length = 0;
	var firstDay = 0;
	/** uncomment this part to make the first month beginning at the current day */
	//if((new Date()).getMonth()==month && (new Date()).getFullYear()==year)
	//	firstDay = (new Date()).getDate()-1;
	for(var count=firstDay;count<getLength(month,year);count++)
		getObj(selectDay).options[count-firstDay] = new Option(count+1,count+1);
	setValue(selectDay, day);
	setValue(selectMonthYear,((month<10)?"0"+month:month)+"_"+year);
}

EuropcarForm.prototype.init = function(where){
	var obj = getObj(where+"Month");
	var selectMonthYear	= CONST_PREFIX+where+CONST_SELECT_MONTHYEAR;
	var dateTime = new Date();
	
	//Current year
	var year = dateTime.getFullYear();
		
	var yearHasChanged = false;
	var maxDate = (CONST_CHECKOUT==where)?this.maxDateCheckout:this.maxDateCheckin;
	
	//10663 Starting year of the promotion
	var year2 = getObj(where + "Year").options[0].value;
	var incrementYear=false;
	//
	
	for(var count=0;count<obj.options.length;count++)
	{		
		if(count>0){
			if(parseInt(obj.options[count].value.replace("_",""),10)<parseInt(obj.options[count-1].value.replace("_",""),10)) {
				year++;
				yearHasChanged = true;
			}
		}
		var value = parseInt(obj.options[count].value.replace("_",""),10);
		
		//10663 Manage the year to display
		if(incrementYear) { //January --> year2 is a new year
			year2++;
			incrementYear=false;
		}
		else if(value==11) { //December --> year2 will be increased at the following loop
			incrementYear=true;
		}
		//
		
		var concatStr = year + "" + ((value<10)?"0"+value:value) + "00";
		var correspondingDate = concatStr;
		if(maxDate != null && correspondingDate>maxDate)
			break;

		//getObj(selectMonthYear).options[count] = new Option(eval("CONST_MONTHS_"+currentLocale)[value] + " " + year,((value<10)?"0"+value:value)+"_"+year);
		//getObj(selectMonthYear).options[count] = new Option(getMonths(getCurrentLocale(),getDefaultLocale())[value] + " " + year,((value<10)?"0"+value:value)+"_"+year);
		
		//10663
		getObj(selectMonthYear).options[count] = new Option(getMonths(getCurrentLocale(),getDefaultLocale())[value] + " " + year2,((value<10) ? "0"+value : value) + "_" + year2);
	}
	var selectedIndex = parseInt(obj.selectedIndex,10);
	
	var newDate = new Date();
	newDate.setMonth(getSelectValue(where+"Month"));
	newDate.setFullYear(getSelectValue(where+"Year"));
	var currentDate = new Date();
	var oneMonthPerMillesecond = 1000*3600*24*30;
	
	// nb of month between the current date and the start of the promotion
	//selectedIndex = Math.round((newDate.getTime()-currentDate.getTime()) /oneMonthPerMillesecond);
	
	//*****  10663 Choice of the month to pre-select in the list ********
	
	//1st case: the opening date of the promotion is a future date
	// ==> this opening date is selected in the list
	if(newDate.getTime()>currentDate.getTime()) {
		selectedIndex = 0;
	}
	
	//2nd case: the opening date is past
	// ==> the current month is selected 
	else {
		//Nb of month between the current date and the opening promotion date
		nbMonthes = Math.round((currentDate.getTime() - newDate.getTime()) / oneMonthPerMillesecond);
		selectedIndex = nbMonthes;
	}
	
	getObj(selectMonthYear).selectedIndex = selectedIndex;
}


EuropcarForm.prototype.getDate = function(from){
	var days	= getSelectValue(CONST_PREFIX+from+CONST_SELECT_DAYS);
	var month	= getSelectValue(CONST_PREFIX+from+CONST_SELECT_MONTHYEAR).split("_")[0];
	var year	= getSelectValue(CONST_PREFIX+from+CONST_SELECT_MONTHYEAR).split("_")[1];	
	var concatDat = year+month+((days<10)?"0"+days:days);
	return parseInt(concatDat,10);
}

EuropcarForm.prototype.getMaximumDate = function(from){
	var days	= getMaxValue(CONST_PREFIX+from+CONST_SELECT_DAYS);
	var month	= getMaxValue(CONST_PREFIX+from+CONST_SELECT_MONTHYEAR).split("_")[0];
	var year	= getMaxValue(CONST_PREFIX+from+CONST_SELECT_MONTHYEAR).split("_")[1];
	return parseInt(year+month+days,10);
}


/*----------------------------*/
function getMaxValue(id) {
	return getObj(id).options[getObj(id).options.length-1].value;
}


function getSelectValue(id)
{
	var returnValue = "";
	if(getObj(id).options[getObj(id).selectedIndex].value!="")
		returnValue = getObj(id).options[getObj(id).selectedIndex].value;
	else
		returnValue = getObj(id).options[0].value;
	
	return returnValue;
}

function setValue (id, val){
	for(var i=0;i<getObj(id).options.length;i++)
	{		
		if(getObj(id).options[i].value == val)
		{
			getObj(id).selectedIndex = i;			
			break;
		}
	}
}

function getCurrentLocale() {
	try {
		return currentLocale;		
	} catch(e1) {
		//alert("getCurrentLocale() not found");
		return getDefaultLocale();
	}
}

function getDefaultLocale() {
	try {
		return defaultLocale;		
	} catch(e1) {
		//alert("getDefaultLocale() not found");
		return "en";
	}
}



