// JavaScript Document
window.onload = function()
{
	GetSysClock(); 
	setInterval("updateClockLocal()",1000);
	document.getElementById("SntpStatus").value = 1;
//  This line moved to last since the visibility property is not supported in IE
	DisableSntpServerFields("SntpMainIPRow","SntpBackupIPRow","UtcOffset","SntpSyncIntRow","SntpSyncTORow","SntpLastSyncRow","SynchronizeNow");
}
function changelist()
{
  if($("#newtimeflag").attr("checked"))
  {
	$("#NewTimeYear").attr("disabled",false);
	$("#NewTimeMonth").attr("disabled",false);
	$("#NewTimeDay").attr("disabled",false);
	$("#NewTimeHour").attr("disabled",false);
	$("#NewTimeMinute").attr("disabled",false);
	$("#NewTimeSecond").attr("disabled",false);
  }
  else
  {
	$("#NewTimeYear").attr("disabled",true);
	$("#NewTimeMonth").attr("disabled",true);
	$("#NewTimeDay").attr("disabled",true);
	$("#NewTimeHour").attr("disabled",true);
	$("#NewTimeMinute").attr("disabled",true);
	$("#NewTimeSecond").attr("disabled",true);
  }
}

function getSNTPStatus()
{
	var listValue = parseInt(document.getElementById("SntpStatus").value);
	return listValue;
}
function handleSyncStatus()
{
	DisableSntpServerFields("SntpMainIPRow","SntpBackupIPRow","UtcOffset","SntpSyncIntRow","SntpSyncTORow","SntpLastSyncRow","SynchronizeNow");
}
function DisableSntpServerFields()
{
	var i,v,obj;
	var args = DisableSntpServerFields.arguments;
	for(i = 0; i < (args.length); i++)
	{
		obj = document.getElementById(args[i]);
		if(obj != null)
		{
			if(getSNTPStatus() == 0)
			{
				obj.style.display = "none";
			}
			else if(getSNTPStatus() == 1)
			{
				obj.style.display= "";//enable 
			}
			
		}
	}
}
function getMonthValue(currentTime)
{
	var monthArr = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
	var index;
	var timeArr = currentTime.split(" ");
	var sMonth = timeArr[1].toUpperCase();

	for(index = 0; index < 12; index++)
	{
		if(sMonth == monthArr[index])
		{
			return (index + 1);
		}
	}
	return -1;
}
function getDayValue(currentTime)
{
	var dayArr = new Array("MON","TUE","WED","THU","FRI","SAT","SUN");
	var index;
	dayArr = currentTime.split(" ");
	var sDay = dayArr[0].toUpperCase();
	document.getElementById("CurrentTimeDate").value = parseInt(dayArr[2],10);

	for(index = 0; index < 7; index++)
	{
		if(sDay == dayArr[index])
		{
			return (index + 1);
		}
	}
	return -1;
}
function PopulateModifiedClockPage(response_array)//assignment after getting parameter
{
    var sCurrTime1 = response_array[1];
    var sCurrTimeHour = response_array[2];
    var sCurrTimeMins = response_array[3];
	var sCurrTimeSecs = response_array[4];
    var sCurrTimeYear = response_array[5];

   $("#currTime").html(sCurrTime1 + " " + sCurrTimeHour + ":" + sCurrTimeMins + ":" + sCurrTimeSecs + " " + sCurrTimeYear);
   $("#CurrentTimeHour").val(sCurrTimeHour);
   $("#CurrentTimeMinute").val(sCurrTimeMins);
   $("#CurrentTimeSecond").val(sCurrTimeSecs);
   $("#CurrentTimeYear").val(sCurrTimeYear);
   $("#CurrentTimeMonth").val((getMonthValue(sCurrTime1)));
  	$("#CurrentTimeDay").val((getDayValue(sCurrTime1)));
   
    var sSntpStatus = response_array[6];
    var nSntpStatus = parseInt(sSntpStatus, 10);
	$("#SntpStatus").val(nSntpStatus);

    var sSntpMainServerIP = response_array[7];
    $("#SntpMainServerIP").val(sSntpMainServerIP);

    var sSntpBackupServerIP = response_array[8];
    $("#SntpBackupServerIP").val(sSntpBackupServerIP);

    var sUtcOffset = response_array[9];
    var nUtcOffset = parseInt(sUtcOffset);
    $("#UtcOffsetList").val(nUtcOffset);

    var sSyncInterval = response_array[10];
   	$("#SyncInterval").val(sSyncInterval);

    var sSyncTimeout = response_array[11];
    $("#SyncTimeout").val(sSyncTimeout);

    var sLastSyncTime = response_array[12];
    $("#LastSyncTime").val(sLastSyncTime);

    $("#prevTimeZone").val(response_array[9]);
	<!--NEW time assign null!-->
	$("#newtimeflag").attr("checked","");
	changelist();
	$("#NewTimeYear").val("");
	$("#NewTimeMonth").val("");
	$("#NewTimeDay").val("");
	$("#NewTimeHour").val("");
	$("#NewTimeMinute").val("");
	$("#NewTimeSecond").val("");
	
    DisableSntpServerFields("SntpMainIPRow","SntpBackupIPRow","UtcOffset","SntpSyncIntRow","SntpSyncTORow","SntpLastSyncRow","SynchronizeNow");
}
function getHTTPObject()
{
	var aHttpObject = false;
	try
	{
		aHttpObject = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			aHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E)
		{
			aHttpObject = false;
		}
	}
	if ((!aHttpObject) && (typeof XMLHttpRequest != "undefined"))
	{
		try
		{
			aHttpObject = new XMLHttpRequest();
		}
		catch(e)
		{
			aHttpObject = false;
		}
	}

	return aHttpObject;
}
function GetSysClock()
{
	var xmlhttp = getHTTPObject();
	var getParams = "cmd=1&getSystemClock=1";
	
	xmlhttp.open("POST", "/goform/mcuTimeSync", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", getParams.length);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if((xmlhttp.status>=200&&xmlhttp.status<300)||xmlhttp.status==304)
			{
				var response = xmlhttp.responseText.slice(7, -8);
				var response_array = response.split("&");
				PopulateModifiedClockPage(response_array);
			}
			else
			{
				alert("Request was unsuccessful:"+xmlhttp.status);
			}
		}
	}
	xmlhttp.send(getParams);
	return true;
}
function GatherSyncFieldValues()
{
    var sSntpMainServerIP = document.getElementById("SntpMainServerIP").value;
    var sSntpBackupServerIP = document.getElementById("SntpBackupServerIP").value;
    var sUtcOffset = document.getElementById("UtcOffsetList").value;
    var sSyncInterval = document.getElementById("SyncInterval").value;
    var sSyncTimeout = document.getElementById("SyncTimeout").value;
	var sSntpStatus	 = document.getElementById("SntpStatus").value;

    var sValueString = "," + sSntpMainServerIP + "," + sSntpBackupServerIP;
    sValueString += "," + sUtcOffset + "," + sSyncInterval + "," + sSyncTimeout + "," + sSntpStatus;

    return sValueString;
}
function FormSynchString()
{
    var sSyncString = "SYNC" + GatherSyncFieldValues();
    return sSyncString;
}
function GatherFieldValues()
{
	if($("#newtimeflag").attr("checked"))
	{
    	var sNewTimeYear = $("#NewTimeYear").val();
		var sNewTimeMonth = $("#NewTimeMonth").val();
	 	var sNewTimeDay = $("#NewTimeDay").val();
		var sNewTimeHour = $("#NewTimeHour").val();
		var sNewTimeHour = $("#NewTimeHour").val();
		var sNewTimeMinute = $("#NewTimeMinute").val();
		var sNewTimeSecond = $("#NewTimeSecond").val();
	}
	else
	{
		var sNewTimeYear = $("#CurrentTimeYear").val();
		var sNewTimeMonth = $("#CurrentTimeMonth").val();
		var sNewTimeDay = $("#CurrentTimeDate").val();
		var sNewTimeHour = $("#CurrentTimeHour").val();
		var sNewTimeMinute = $("#CurrentTimeMinute").val();
		var sNewTimeSecond = $("#CurrentTimeSecond").val();
	}
    var sSntpStatus = $("#SntpStatus").val();
    var sSntpMainServerIP = $("#SntpMainServerIP").val();
    var sSntpBackupServerIP = $("#SntpBackupServerIP").val();
    var sUtcOffset = $("#UtcOffsetList").val();
    var sSyncInterval = $("#SyncInterval").val();
    var sSyncTimeout = $("#SyncTimeout").val();
    var sPrevTimeZone =$("#prevTimeZone").val();

    var sValueString = "," + sNewTimeYear + "," + sNewTimeMonth + "," + sNewTimeDay;
    sValueString += "," + sNewTimeHour + "," + sNewTimeMinute + "," + sNewTimeSecond;
    sValueString += "," + sSntpStatus + "," + sSntpMainServerIP + "," + sSntpBackupServerIP ;
    sValueString += "," + sUtcOffset + "," + sSyncInterval + "," + sSyncTimeout + "," + sPrevTimeZone;

	return sValueString;
}
function FormUpdateString()
{
    var sUpdateString = "UPDATE" + GatherFieldValues();
    return sUpdateString;
}
function SetSysClock(sValueString)
{
	var getParams = "cmd=2&clockSetString=" + sValueString;

	var xmlhttp = getHTTPObject();	
	xmlhttp.open("POST", "/goform/mcuTimeSync", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", getParams.length);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		{
			if((xmlhttp.status>=200&&xmlhttp.status<300)||xmlhttp.status==304)
			{
				GetSysClock();
			}
			else
			{
				alert("Request was unsuccessful:"+xmlhttp.status);
			}
		}
	}
	xmlhttp.send(getParams);
	return true;
}
function ApplySntp_onclick()//submit parameters
{
	var flag;
	var sUpdateString;

	if(ValidateSntp() == false)
	{
		return;
	}
	flag = ValidateClkParam();
	if(flag == false)
	{
		return;
	}
  	sUpdateString = FormUpdateString();
	if(flag == 63)//didn't set the new time
	{
		if($("#newtimeflag").attr("checked"))
		{
			alert("Please input valid <New Time>!");
			return;
		}
		sUpdateString += "," + 0;
	}
	else
	{
		sUpdateString += "," + 1;
	}
  	SetSysClock(sUpdateString);
}
function ResetSntp_onclick()
{	
	GetSysClock();
}

function updateClockLocal()
{
    var nTimeSec = document.getElementById("CurrentTimeSecond").value;
    var nTimeMin = document.getElementById("CurrentTimeMinute").value;
    var nTimeHrs = document.getElementById("CurrentTimeHour").value;

    var tmpSec = "";
    var tmpMin = "";
    var tmpHrs = "";

    if((++nTimeSec) == 60)
    {
        nTimeSec = 0;
        if((++nTimeMin) == 60)
        {
            nTimeMin = 0;
            if((++nTimeHrs) == 24)
            {
                nTimeHrs = 0;
				//Get the new day information from the board on midnight
				GetSysClock(); 
			}
        }
    }

    var prevTime = document.getElementById("currTime").innerHTML;
    var timearr = prevTime.split(" ");

    if(parseInt(nTimeSec,10) < 10)
	{
    	tmpSec = "0" + (parseInt(nTimeSec,10)); //*10) / 10;
	}
    else
	{
    	tmpSec = nTimeSec;
	}
    if(parseInt(nTimeMin,10) < 10)
	{
    	tmpMin = "0" + (parseInt(nTimeMin,10)); //*10) / 10;
	}
    else
	{
    	tmpMin = nTimeMin;
	}
    if(parseInt(nTimeHrs,10) < 10)
	{
    	tmpHrs = "0" + (parseInt(nTimeHrs,10)); //*10) / 10;
	}
	else
	{
		tmpHrs = nTimeHrs;
	}

	timearr[3] = tmpHrs + ":" + tmpMin + ":" + tmpSec;

    document.getElementById("currTime").innerHTML = timearr.join(" ");
    document.getElementById("CurrentTimeSecond").value = nTimeSec;
    document.getElementById("CurrentTimeMinute").value = nTimeMin;
    document.getElementById("CurrentTimeHour").value = nTimeHrs;
}
function checkLeapYear(data)
{
	data = parseInt(data,10);
	if((data % 4) == 0)
	{
		if((data % 100) != 0)
		{
			return true;
		}
		else
		{
			if((data % 400) == 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	return false;
}
function  ValidateClkParam()
{
	var shift_flag;
	var status_flag = 0;
	var obj;
    var sNewTime;

    /* Validate the new time clock fields */
    obj = document.getElementById("NewTimeYear");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
	{
		shift_flag = 1;
		status_flag = status_flag | shift_flag;
	}
	else
	{
		if(validateYear(obj) != true)
		{
			return false;
		}
	}

	obj = document.getElementById("NewTimeMonth");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
	{
		shift_flag = 1 << 1;
		status_flag = status_flag | shift_flag;
	}
    else
	{
		if(validateMonth(obj) != true)
		{
			return false;
		}
	}

	obj = document.getElementById("NewTimeDay");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
	{
		shift_flag = 1 << 2;
		status_flag = status_flag | shift_flag;
	}
	else
	{
		if(validateClkDay(obj) != true)
		{
			return false;
		}
	}
	
    obj = document.getElementById("NewTimeHour");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
    {
		shift_flag = 1 << 3;
		status_flag = status_flag | shift_flag;
	}
	else
	{
		if(validateHour(obj) != true)
		{
			return false;
		}
	}

	obj = document.getElementById("NewTimeMinute");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
    {
		shift_flag = 1 << 4;
		status_flag = status_flag | shift_flag;
	}
	else
	{
		if(validateMinutes(obj) != true)
		{
			return false;
		}
	}

	obj = document.getElementById("NewTimeSecond");
	sNewTime = obj.value;
	if(sNewTime.length == 0)
    {
		shift_flag = 1 << 5;
		status_flag = status_flag | shift_flag;
	}
	else
	{
		if(validateSeconds(obj) != true)
		{
			return false;
		}
	}

	if((status_flag != 63) && (status_flag != 0))
	{
		alert("Please enter a value in each of the date/time fields");
		return false;
	}

	if(status_flag == 63)
	{
		return 63;
	}
	else
	{
		return 2;
	}
}
function ValidateSntp()
{
	for(var i = 0; i < 4; i++)
	{
		var id = i + 1;
		if(ValidateThisSntp(id) == false)
		{
			 return false;
		}
	}
	return true;
}

function ValidateThisSntp(id)
{
	var obj;
	if(getSNTPStatus() == 1)
	{
		if(id == 1)
		{
			obj = document.getElementById("SntpMainServerIP");
			if(Validate_IP_Format(obj.value) == false)
			{
				alert("Please input valid <Main SNTP Server IP Address>!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
		}
		else if(id == 2)
		{
			obj = document.getElementById("SntpBackupServerIP");
			if(Validate_IP_Format(obj.value) == false)
			{
				alert("Please input valid <Backup SNTP Server IP Address>!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
		}
		else if(id == 3)
		{
			obj = document.getElementById("SyncInterval");
			if(validateNumber(obj.value) == false)
			{
				alert("Please input valid <Synchronization Interval (min)>!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
			if((obj.value < 1) || (obj.value > 65535))
			{
				alert("<Synchronization Interval (min)> must be between 1 and 65535!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
		}
		else if(id == 4)
		{
			obj = document.getElementById("SyncTimeout");
			if(validateNumber(obj.value) == false)
			{
				alert("Please input valid <Synchronization Timeout (ms)>!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
			if((obj.value < 1) || (obj.value > 65535))
			{
				alert("<Synchronization Timeout (ms)> must be between 1 and 65535!");
				setTimeout(function () {obj.focus()}, 50);
				obj.select();
				return false;
			}
		}
	}
	return true;
}

function validateClkDay(obj)
{
	var number_flag;
    var sNewTime;
    
	sNewTime = obj.value;
	number_flag = parseInt(sNewTime, 10);
	if(validateDate(obj) != true)
	{
		return false;
	}
	else
	{
		/* Check the year is leap year or not */
		var NewMonth = parseInt(document.getElementById("NewTimeMonth").value, 10);
		switch(NewMonth)
		{
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				/* Check the max value */
				if(number_flag > 31)
				{
					alert("Maximum number of days in this month is 31!");
					setTimeout(function () {obj.focus()}, 50);
					obj.select();
					return false;
				}
				break;
			case 2:
				/* Febraury Leap year */
				if(checkLeapYear(sNewTime) == true)
				{
					if(number_flag > 29)
					{
						alert("Maximum number of days in this month is 29!");
						setTimeout(function () {obj.focus()}, 50);
						obj.select();
						return false;
					}
				}
				else
				{
					if(number_flag > 28)
					{
						alert("Maximum number of days in this month is 28!");
						setTimeout(function () {obj.focus()}, 50);
						obj.select();
						return false;
					}
				}
				break;
			default:
				/* Check the max value */
				if(number_flag > 30)
				{
					alert("Maximum number of days in this month is 30!");
					setTimeout(function () {obj.focus()}, 50);
					obj.select();
					return false;
				}
				break;
		}
	}
	return true;	
}
function Validate_IP_Format(IPAddress)
{
	var IPAddr_Fields = IPAddress.split(".");
	var Field_Value;
	
	// make sure there are 4 octets
	if(IPAddr_Fields.length != 4)
	{
		return false;
	}
	for(var i = 0; i < IPAddr_Fields.length; i++)
	{
		if(validateNumber(IPAddr_Fields[i]) == false)
		{
			return false;
		}
		Field_Value = parseInt(IPAddr_Fields[i], 10);
		if((Field_Value < 0) || (Field_Value > 255))
		{
			return false;
		}
	}
	
	return true;
}

function validateNumber(input)
{
	var len = input.length;

	if(len == 0)
	{
		return false;
	}

	for(index = 0; index < len; index++)
	{
		if(isNaN(parseInt(input.charAt(index))))
		{
			return false;
		}
	}

	return true;
}
function checkIfNumber(param)
{
	if(validateNumber(param.value) == false)
	{
		alert("Invalid number. Please enter a valid numeric value!");
		setTimeout(function () {param.focus()}, 50);
		param.select();
		return false;
	}
	return true;
}
function validateYear(yearCtrl)
{
	retValue = true;
	yearValue = yearCtrl.value;
	if(validateNumber(yearValue) == false)
	{
		alert("Please input valid year!");
		retValue = false
	}

	if((parseInt(yearValue,10) < 1970) || (parseInt(yearValue,10) > 2100))
	{
		alert("Year must be between 1970 and 2100!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {yearCtrl.focus()}, 50);
		yearCtrl.select();
	}

	return retValue;
}
function validateMonth(monthCtrl)
{
	retValue = true;
	monthValue = monthCtrl.value;

	if(validateNumber(monthValue) == false)
	{
		alert("Please input valid month!");
		retValue = false
	}

	if((parseInt(monthValue,10) < 1) || (parseInt(monthValue,10) > 12))
	{
		alert("Month must be between 1 and 12!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {monthCtrl.focus()}, 50);
		monthCtrl.select();
	}

	return retValue;
}

function validateDate(dateCtrl)
{
	retValue = true;
	dateValue = dateCtrl.value;
	if(validateNumber(dateValue) == false)
	{
		alert("Please input valid day!");
		retValue = false
	}
//	In future, date should be validated w.r.t month value
	if((parseInt(dateValue,10) < 1) || (parseInt(dateValue,10) > 31))
	{
		alert("Day must be between 1 and 31!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {dateCtrl.focus()}, 50);
		dateCtrl.select();
	}

	return retValue;
}

function validateHour(hourCtrl)
{
	retValue = true;
	hourValue = hourCtrl.value;

	if(validateNumber(hourValue) == false)
	{
		alert("Please input valid hour!");
		retValue = false
	}

	if((parseInt(hourValue,10) < 0) || (parseInt(hourValue,10) > 23))
	{
		alert("Hour must be between 0 and 24!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {hourCtrl.focus()}, 50);
		hourCtrl.select();
	}

	return retValue;
}

function validateMinutes(minCtrl)
{
	retValue = true;
	minValue = minCtrl.value;

	if(validateNumber(minValue) == false)
	{
		alert("Please input valid minute!");
		retValue = false
	}

	if((parseInt(minValue,10) < 0) || (parseInt(minValue,10) > 59))
	{
		alert("Hour must be between 0 and 59!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {minCtrl.focus()}, 50);
		minCtrl.select();
	}

	return retValue;
}

function validateSeconds(secCtrl)
{
	retValue = true;
	secValue = secCtrl.value;

	if(validateNumber(secValue) == false)
	{
		alert("Please input valid second!");
		retValue = false
	}

	if((parseInt(secValue,10) < 0) || (parseInt(secValue,10) > 59))
	{
		alert("Second must be between 0 and 59!");
		retValue = false;
	}

	if(retValue == false)
	{
		setTimeout(function () {secCtrl.focus()}, 50);
		secCtrl.select();
	}

	return retValue;
}