
//confirm every parameter is correct, called when user click the submit or update button
function confirmSubmit()
{
	return_bool=false;
	//check event name is blank or not 
	if(document.event.name.value!='')
	{
		//check start date
		if(date_validate(document.event.start_date))
		{
			if(document.event.end_date.value)
			{
				if(date_validate(document.event.end_date))
				{
					if(compareDate(convert_date_format(document.event.end_date.value), convert_date_format(document.event.start_date.value) ))
					return_bool=true;
					else
					{
						//message=message_string01;
						// as requested by Kennametal , "When adding an event to the calendar when the start date is > end date make the end date the start date "
						document.event.end_date.value=document.event.start_date.value;
						return_bool=true;
					}
				}			
			}
			else
			{
				document.event.end_date.value=document.event.start_date.value;
				return_bool=true;
			}
		}
	}
	else
	{
		message=message_string02;
	}

	
	if(return_bool)
	{
		if(document.event.hasrepeat.value==1)
		confirmRepeatDate();
	}
	
	if(return_bool)
	{
		
		document.event.repeat_pattern.value=recur_pattern_string;
		datetime_finalize_js(document.event);
	}
	else
	{
		alert(msg_header+message);
	}
	
	// if this is Update action, then will confirm the user to update all related events or just this one only
	if(is_update==1 && return_bool)
	{
		//check if this event is a recurring event already, if it is not, it will generate recurring event
		if(global_repeat_pattern!='')
		{
			//check if recurring condition got changed or not, if it is , it need to delete old ones and create new ones
			if(recur_pattern_string!=global_repeat_pattern)
			{
				if(confirm(message_string03+". \n "+message_string04+"?   \n\n "+message_string05+". "))
				{
					document.event.need_delete_old.value='2';
				}
				else
				{
					//if user choose Cancel, then restore old values and return
					onLoadUpdate();
					return_bool=false;
				}
			}
			else
			{
				if(document.event.updateType[1].checked)
				{
					//check if the date and time of both start or end get changed, 
					//as we cannot update the whole series of recurring events with 
					//date and time get changed, we only allow user to change current event
					//for date and time
					if(!isDateTimeChanged())
					{
						//if datetime is NOT changed
						if(confirm(message_string06+".    \n\n "+message_string07+". "))
						document.event.need_delete_old.value='1';
						else
						return_bool=false;
					}
					else
					{	//if datetime is changed 
						alert(message_string20);
						if(confirm(" "+message_string07+". "))
						document.event.need_delete_old.value='2';
						else
						return_bool=false;
					}
				}
			
			}
		}
		else
		{
			//if this event is not a recurring event, then user add recurring info
			if(recur_pattern_string!='')
			document.event.need_delete_old.value='2';
		
		}
	}
	//alert(document.event.ids.value);
	//alert(document.event.need_delete_old.value);
	//return false;
	return return_bool;
}

//convert the date format always to MM/DD/YYYY when processing
function convert_date_format(in_date)
{
	var out_date="";
	if(global_date_format=="MM/DD/YYYY")
		out_date= in_date;
	else if(global_date_format=="DD/MM/YYYY")
		out_date= ""+in_date.substr(3,2)+"/"+in_date.substr(0,2)+"/"+in_date.substr(6,4);
	else if(global_date_format=="YYYY/MM/DD")
		out_date= ""+in_date.substr(5,2)+"/"+in_date.substr(8,2)+"/"+in_date.substr(0,4);
	else
		out_date= "ERROR CONVERT DATE FORMAT JS";
	
	return out_date;
}

//convert the date format from the MM/DD/YYYY to what ever it is
function convertBack_date_format(in_date)
{
	var out_date="";
	if(global_date_format=="MM/DD/YYYY")
		out_date= in_date;
	else if(global_date_format=="DD/MM/YYYY")
		out_date= ""+in_date.substr(3,2)+"/"+in_date.substr(0,2)+"/"+in_date.substr(6,4);
	else if(global_date_format=="YYYY/MM/DD")
		out_date= ""+in_date.substr(6,4)+"/"+in_date.substr(0,2)+"/"+in_date.substr(3,2);
	else
		out_date= "ERROR CONVERT DATE FORMAT JS";
	
	return out_date;
}


//if changed return true
function isDateTimeChanged()
{
	if(document.event.end_time.value!=end_time_old)
	return true;
	if(document.event.start_time.value!=start_time_old)
	return true;
	if(document.event.end_date.value!=end_date_old)
	return true;
	if(document.event.start_date.value!=start_date_old)
	return true;

	return false;	
}


function getDayofWeek(dow)
{
	var tempS="";
	switch (dow){
  	case 1: 
	      	tempS="Monday";
      		break;
   	case 2: 
      		tempS="Tuesday";
      		break;
   	case 3: 
      		tempS="Wednesday";
      		break;
   	case 4: 
      		tempS="Thursday";
      		break;
   	case 5: 
      		tempS="Friday";
      		break;
   	case 6: 
		tempS="Saturday";
      		break;
   	case 7: 
      		tempS="Sunday";
      		break;

   	default : tempS="ERROR No DAY ";
	}
	return tempS;
}

//get the recurring pattern and determine  the start date
function confirmRepeatDate()
{

		var ISO_date=YMD_To_YWD(convert_date_format(document.event.start_date.value));		
		var recur_pattern=document.event.RecurrencePattern.value;
		recur_pattern_string="";
		var start_end_diff=DiffDays(convert_date_format(document.event.end_date.value), convert_date_format(document.event.start_date.value))
		
		if(recur_pattern==1)
		{
			var field=document.event.week_weekday;
			var i=0;
			recur_pattern_string="W"+document.event.week_every.value+" ";
			var week_weekday_no='';
			 for(i = 0; i < field.length; i++)
        		{
        			if(field[i].checked)
				{
					recur_pattern_string+=field[i].value.substring(0,2)+" ";
					week_weekday_no+=field[i].value.substring(3,4);
				}
			}
			
			//alert("week_weekday_no ="+week_weekday_no);
			
			if(week_weekday_no!='')
			{
				if(isOverLap(week_weekday_no,start_end_diff))
				{
					var converted_date1=convert_date_format(document.event.start_date.value);
					var converted_date2=convert_date_format(document.event.end_date.value);
					var newStartDateNo=getNearestDateNo(week_weekday_no,converted_date1,ISO_date[2]);
					var tempDate= addDate(converted_date1, newStartDateNo);
					document.event.start_date.value= convertBack_date_format(tempDate);
					tempDate  = addDate(converted_date2, newStartDateNo);
					document.event.end_date.value  = convertBack_date_format(tempDate);
				}
				else
				{
					message=" "+message_string10+" "+(start_end_diff+1)+" "+message_string11+". \n "+message_string12+". \n "+message_string09+".";
					return_bool=false;
				}
				
			}
			else
			{
				message=" "+message_string08+".";
				return_bool=false;
			}
			
		
		}
		else if(recur_pattern==2)
		{
			if(start_end_diff>28)
			{
				return_bool=false;		
					message=" "+message_string10+" "+start_end_diff+" "+message_string11+". \n "+message_string12+". \n "+message_string09+".";
			}
			else if(document.event.monthType[0].checked)
			{
				recur_pattern_string="MD"+document.event.month_every.value+" ";
				
				if(document.event.DayOfMonth.value>28)
				{
					if(confirm("Some months have fewer than "+document.event.DayOfMonth.value+" days. For these months, the occurrence will fall on the last day of the month."))
					{
						recur_pattern_string+=document.event.DayOfMonth.value+" ";
						var tempDate=getDatebyDayNo( convert_date_format(document.event.start_date.value), document.event.DayOfMonth.value);
						document.event.start_date.value=convertBack_date_format(tempDate);
						tempDate=addDate(convert_date_format(document.event.start_date.value), start_end_diff);
						document.event.end_date.value=convertBack_date_format(tempDate);
					}					
					else
					return_bool=false;
				}
				else
				{
					recur_pattern_string+=document.event.DayOfMonth.value+" ";
					var tempDate=getDatebyDayNo(convert_date_format(document.event.start_date.value) ,document.event.DayOfMonth.value);
					document.event.start_date.value=convertBack_date_format(tempDate);
					tempDate=addDate(convert_date_format(document.event.start_date.value), start_end_diff);
					document.event.end_date.value=convertBack_date_format(tempDate);
				}
			}
			else
			{
				recur_pattern_string="MP"+document.event.n_month_every.value+" ";
				recur_pattern_string+=document.event.n_week.value+"+ ";
				
				var tempDate=getNearestMP(document.event.n_dayOfWeek.value.substring(3,4), convert_date_format(document.event.start_date.value),document.event.n_week.value);
				document.event.start_date.value=convertBack_date_format(tempDate);
				tempDate=addDate(convert_date_format(document.event.start_date.value), start_end_diff);
				document.event.end_date.value=convertBack_date_format(tempDate);
				
				recur_pattern_string+=document.event.n_dayOfWeek.value.substring(0,2)+" ";
			}
		
		}
		else if(recur_pattern==3)
		{
			if(start_end_diff>364)
			{
				return_bool=false;		
				message=" "+message_string10+" "+start_end_diff+" "+message_string11+". \n "+message_string12+". \n "+message_string09+".";
			}
			else if(document.event.yearType[0].checked)  //yearly by day
			{
				recur_pattern_string="YD1"+" ";
			}
			else  //by month
			{
				recur_pattern_string="YM1"+" ";
				recur_pattern_string+=document.event.year_n_week.value+"+ ";
				
				var convert_date1=convert_date_format(document.event.start_date.value);
				var convert_date2=getNearestMP(document.event.year_dow.value.substring(3,4),
							     document.event.startmonth.value+'/01/'+convert_date1.substr(6,4),
							     document.event.year_n_week.value);
				document.event.start_date.value=convertBack_date_format(convert_date2);

				convert_date2=addDate(convert_date1, start_end_diff);
				document.event.end_date.value=convertBack_date_format(convert_date2);

				recur_pattern_string+=document.event.year_dow.value.substring(0,2)+" ";
				
			}
			
			
		
		}
		
		if(return_bool)
		confirmEndDate();
}

function getNearestMP(dow_start, startDate, no_week)  //DayofWeek ,  startDate,  n_week
{
	var first_day_month_ISO_date=startDate.substr(0,2)+'/01/'+ startDate.substr(6,4);
	var first_day_month_dow=YMD_To_YWD(first_day_month_ISO_date)[2];
	var add_diff=0;
	
	if (first_day_month_dow <= dow_start)
	add_diff=parseInt(no_week)*7 + parseInt(dow_start)- first_day_month_dow - 7;
	else
	add_diff=parseInt(no_week)*7+ parseInt(dow_start)-first_day_month_dow;
	
	return addDate(first_day_month_ISO_date, add_diff);

}

//this function finds out the shortest duration between the recurring pattern and 
//compare to Date_diff to find out is it overlapping involved
function isOverLap(stringRecurringPattern, duration)
{
	if(duration==0)
	return true;
	
	if(stringRecurringPattern.length==1)
	return (duration<7);
	else 
	{
		var tempNo_0=stringRecurringPattern.substr(0,1);
		for (var i=1; i<stringRecurringPattern.length; i++)
		{
			var tempNo_next=stringRecurringPattern.substr(i,1);
			var final_diff=parseInt(tempNo_next)-parseInt(tempNo_0);
			//if diff >3 then it can shorted in reverse order
			if( final_diff>3)
			final_diff=7-final_diff;
			
			if(duration>=final_diff)
			return false;
		}
		return true;
	
	}
}


// get the nearest date of the sDate in Day of Week pattern
function getNearestDateNo(stringDOW, startDate, sDateDOW)
{
	
	var index1=stringDOW.indexOf(sDateDOW);
	if(index1>=0)
	return 0;
	else 
	{
		for(var i = 1; i <7; i++)
		{
			var dow1=sDateDOW+i;
			
			if(dow1>7)
			dow1=dow1-7;
			
			if(stringDOW.indexOf(dow1)>=0)
			{
				return i;//addDate(startDate, i);
			}
			
		}
	}
	return "ERROR DATE";

}

//add the specific days to certain Date
function addDate(sDate, add_days)
{
		if(add_days==0)
		return sDate;
		
		// Strip out the month, day and year, JavaScript stores months as 0-11 as opposed to 1-12
		var EnteredMonth = sDate.substr(0,2) - 1;
		var EnteredDay = sDate.substr(3,2);
		var EnteredYear = sDate.substr(6,4);
		
		// Create a new date object with the entered month, day and year
		var EnteredDate = new Date(EnteredYear, EnteredMonth, EnteredDay, 0, 0, 0);
		// Determine the milliseconds in the timespan ,  Set the default (1 day)
		var MilliSecondsBase = 86400000 
		
		// If the timespan is weeks, multiply the default by 7
		//	MilliSecondsBase *= 7;

		// Multiply the millisecons by the period entered 
		MilliSecondsToAdd  = MilliSecondsBase * add_days;
		
		// Create the new date using the correct operation
		var NewDateAsNumber = EnteredDate.getTime() + MilliSecondsToAdd;
		//substract 	var NewDateAsNumber = EnteredDate.getTime() - MilliSecondsToAdd;
		
		// Create the new date object
		var NewDate = new Date(NewDateAsNumber);
		// Get the month, day and year values from the new date object
		// Set the month and day to two digits if they are less than 10
		var NewMonth = NewDate.getMonth() + 1;
		if (NewMonth < 10)
		{
			NewMonth = "0" + NewMonth;
		}
		var NewDay = NewDate.getDate();
		if (NewDay < 10)
		{
			NewDay = "0" + NewDay;
		}
		var NewYear = NewDate.getFullYear();
		
		return NewMonth + "/" + NewDay + "/" + NewYear;
}

function confirmEndDate()
{

	if(document.event.enddatetype[0].checked)
	{
		var field_v=document.event.RecurrenceEnd.value;
	
		if(field_v=="")
		{
			message=" "+message_string13+".";
			return_bool=false;
			return;
		}
		
		if(date_validate(document.event.RecurrenceEnd))
		{
		
			field_v=convert_date_format(field_v);
			recur_pattern_string+=field_v.substr(6,4)+field_v.substr(0,2)+field_v.substr(3,2)+"T000000Z ";
			document.event.generate_until.value=field_v;
		}
		else 
		{
			return_bool=false;
		}
		
	}
	else if(document.event.enddatetype[1].checked)
	{
		if(document.event.end_after_x.value==""||NotInteger(document.event.end_after_x.value)|| document.event.end_after_x.value<1)
		{
			return_bool=false;
			message=message_string14+"."; 
		}
		else	
		recur_pattern_string += '#' + document.event.end_after_x.value +' ';
	}
	else if(document.event.enddatetype[2].checked)
	{
		recur_pattern_string+="#0 ";
		var no_end_date=convert_date_format(document.event.start_date.value);
		no_end_date = no_end_date.substr(0,2) +'/'+no_end_date.substr(3,2)+'/'+(parseInt(no_end_date.substr(6,4))+1);
		document.event.generate_until.value=no_end_date;
		document.event.repeat_until.value=no_end_date;
	}
	
	return;
}



function doPattern()
{
		//alert("RecurrencePattern is " +document.event.RecurrencePattern.value);
	  	var repeatElemnet, repeatId;
		for (i=1; i < 4; i++)
		{
			repeatId="repeatpattern"+i;
			hideLayer(repeatId);
			//repeatElement = getDiv(repeatId);
   			//repeatElement.style.display = "none";
		}
		repeatId="repeatpattern"+document.event.RecurrencePattern.value;
		showLayer(repeatId);
		//repeatElement = getDiv(repeatId);
		//repeatElement.style.display = "";
}

function showLayer(nameOfLayer)
// Needs to be sent the fully qualified name of the layer.  
{
	if (document.all)
	{
		var thisElement = getDiv(nameOfLayer);
		thisElement.style.display = "";
	}
	else 
		eval ("document.layers."+nameOfLayer + '.visibility = "show";');	
}

function hideLayer(nameOfLayer)
// Needs to be sent the fully qualified name of the layer.  
{
	if (document.all)
	{
		var thisElement = getDiv(nameOfLayer);
		thisElement.style.display = "none";
	}
	else 
		eval ("document.layers."+nameOfLayer + '.visibility = "hide";');
}


function compareDate(date1,date2)
{
			var Month1 = date1.substr(0,2);
			var Day1 = date1.substr(3,2);
			var Year1 = date1.substr(6,4);
			var Month2 = date2.substr(0,2);
			var Day2 = date2.substr(3,2);
			var Year2 = date2.substr(6,4);

			if(Year1<Year2)
				return false;
			else if(Year1==Year2&&Month1<Month2)
				return false;
			else if(Year1==Year2&&Month1==Month2&&Day1<Day2)
				return false;
			
			
			return true;
}


function date_validate(element)  //date_validate DATE
{
	var Proceed = 0;
	// Create a variable to hold the correct format.

	var CorrectFormat = /[0-1][0-9]\/[0-3][0-9]\/[0-9][0-9][0-9][0-9]/;
	// If the field has value, date_validate the date.
	 message = "[ "+ element.id + " ]  "+message_string15+". ";
	
	//alert("message_string19 :"+message_string19);
	
	var element_date=element.value;
	
	if (element_date)
	{
		if(element_date.length>10 || element_date.length < 8||DateFormatNotCorrect(element_date))
		{
			message="[ "+ element.id + " ]  "+message_string16+". ";
			return false;
		}

		if(element_date.length==9 || element_date.length == 8)
		{
			element_date=convertDateTo10Char(element_date);
		}			

		//convert date to standard MM/DD/YYYY then process
		element_date=convert_date_format(element_date);
		element.value=convertBack_date_format( element_date);
		
		
		// Test to see if the format of the date is correct , this date format is always MM/DD/YYYY.
		if (CorrectFormat.test(element_date))
		{
			// Split out the month, day and year variables.
			var Month = element_date.substr(0,2);
			var Day = element_date.substr(3,2);
			var Year = element_date.substr(6,4);
			// Ensure all the values are greater than 0
			if (Month > 0 && Day > 0 && Year > 0)
			{
				// Find the max day for the month,  default max day is 31
				var maxDays = 31;
				// If the month is April, June, September or November the max day is 30
				if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
				{
					maxDays = 30;
				}
				if (Month == 2)
				{
					if (Year % 4 > 0)
						maxDays =28;
					else
					if (Year % 100 == 0 && Year % 400 > 0)
						maxDays = 28;
					else
						maxDays = 29;
				}
				// Determine if the day entered is less than the max days for that month.
				if (Day <= maxDays)
				Proceed = 1;
				else
				message = "[ "+ element.id + " ]  "+message_string18+". ";
				
				if (Month >12 )
				{
					Proceed = 0;
					message = "[ "+ element.id + " ]  "+message_string17+". ";
				}

			}
		}
		else
		{
			message = "[ "+ element.id + " ]  "+message_string19+". ";
		}
	}
	if (Proceed == 0)
	{

		return false;
	}
	else
	{
		return true;
	}
}

function getDatebyDayNo(element_date, dayNo)  //date_validate DATE
{
	// Split out the month, day and year variables.
	var Month = element_date.substr(0,2);
	var Day = element_date.substr(3,2);
	var Year = element_date.substr(6,4);

		// Find the max day for the month,  default max day is 31
		var maxDays = 31;
		// If the month is April, June, September or November the max day is 30
		if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
		{
			maxDays = 30;
		}
		if (Month == 2)
		{
			if (Year % 4 > 0)
			maxDays =28;
			else
			if (Year % 100 == 0 && Year % 400 > 0)
			maxDays = 28;
			else
			maxDays = 29;
		}
		// Determine if the day entered is less than the max days for that month.
		
		if (dayNo <= maxDays)
		{
			if (dayNo < 10)
			{
				dayNo = "0" + dayNo;
			}
			return Month+'/'+dayNo+'/'+Year;
		}
		else
		return Month+'/'+maxDays+'/'+Year;
}


function DiffDays(S2, S1) {
 	
	
 	var X=[S2.substr(6,4),S2.substr(0,2),S2.substr(3,2)];
 	var Y=[S1.substr(6,4),S1.substr(0,2),S1.substr(3,2)];
 
 	return (Date.UTC(X[0], X[1]-1, X[2])-Date.UTC(Y[0], Y[1]-1, Y[2]))/86400000
 }


function YMD_To_YWD( dateS) {

	var S=[dateS.substr(6,4),dateS.substr(0,2),dateS.substr(3,2)];

	 with (new Date(S[0], S[1]-1, S[2])) 
	 { var DoW = getDay()
 		 setDate(getDate() - (DoW+6)%7 + 3 ) // Nearest Thu
		  var ms = valueOf() // GMT
		  setMonth(0) ;
		  setDate(4) // In Week 1
		  var WN = Math.round( (ms-valueOf()) / (7*86400000) ) + 1
		  if (DoW==0) DoW = 7 // JS to ISO DoW
		  //alert("DoW= "+DoW);
		  return [getFullYear(), WN, DoW] 
  	} 

}

function isEmpty(s)
{   
	return ((s == null) || (s.length == 0));
}


function NotInteger (s)

{   
	var i;
    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return true;
    }

    // All characters are numbers.
    return false;
}  

// Returns true if character c is a digit 
// (0 .. 9).
function isDigit (c)
{   
	return ((c >= "0") && (c <= "9"));
}
