var sableUser, errors, edtUserName, edtPassword, scannedSPL, cachedIndex = null;

function redirect(page)
{
	window.location = '/themes/sable/offline/'+page+'.html'
}

function userLogin()
{
	deleteCookie('sableUser'); //keep it secure.
	errors = false; //initialise
	validate_edtUserName();
	validate_edtPassword();	
	if (!errors)
	{
		sableFindRow("user_email", edtUserName, validateLogin);
	}
} //function login()

function validateLogin(rec)
{
	if (rec)
	{
		var hash = md5(edtPassword); // "2063c1608d6e0baf80249c42e2be5804"
		if (rec.user_password === hash)
		{
			setCookie('edtUserName', edtUserName, 90);
			//setCookie('sableUser', JSON.stringify(rec), 90);
			var usrid = getRecordId(rec);
			setCookie('sableUser', usrid, 90);
			redirect('inspection')
		}
		else
		{
			handleError('edtPassword', 'Invalid user name and/or password.');
		}
	}
	else 
	{
		console.error('Record not found.');
		handleError("edtPassword", "Invalid user or account not activated.");
	}	
}

function checkAuthentication()
{
	var cookieUser = getCookie('sableUser');
	if (cookieUser) 
	{
		sableUser = cookieUser; //JSON.parse(cookieUser); 
	} else redirect('login');
}

function validate_edtUserName(){edtUserName = validateRequiredText("edtUserName", "Please enter your email address.")};
function validate_edtPassword(){edtPassword = validateRequiredText("edtPassword", "Please enter your password.")};

function getRecordId(rec)
{
	return rec.sableID.split('|')[1];
}

function loadJobCardOptions(sableRows)
{
	var html = '';
	var selJobCardId = document.getElementById('selJobCardId');
	var userCode = sableUser; //getRecordId(sableUser);
	var jcid = null;
	for (var i in sableRows)
	{
		if (sableRows[i].user_code === userCode)
		{
			jcid = getRecordId(sableRows[i]);
			html += '<option value="'+jcid+'">'+sableRows[i].job_card_name+'</option>';
		}
	}
	selJobCardId.innerHTML = html;
	updateCacheIndex();
}

function startInspectionPage()
{
	checkAuthentication();
	sableRows = [];
	sableGetRows("job_card", loadJobCardOptions);
	setLubricantData();
	document.getElementById('ajaxDiv').style.display = 'none';
}

function setLubricantData()
{
	sableGetRows('lubricant', updateLubricantsSelection);
}

function updateLubricantsSelection(rec)
{
	var html = '';
	var sel = document.getElementById('selLubricantId');
	for (var i in rec)
	{
		html += '<option value="'+getRecordId(rec[i])+'">'+rec[i].lubricant_name+'</option>';
	}
	sel.innerHTML = html;
}

function getSPLLubricants()
{
	sableFindRow('spl_model_no', document.getElementById('hddnInspectionModel').value);
}

function updateCacheIndex()
{
	sableGetRows('offline_inspections', getIndex);
}

function getIndex(recs)
{
	var len = recs.length;
	cachedIndex = (len === undefined) ? 0 : len;
}

function saveInspection()
{
	var idx = (cachedIndex === null || cachedIndex === undefined) ? 0 : cachedIndex;

	errors = false;
	validate_selJobCardId();
	validate_edtInspectionModel();
	validate_edtInspectionSerialNo();
	validate_selSplId();
	validate_selConditionStatusId();
	validate_txtInspectionRemarks();
	validate_edtApplication();
	validate_edtInspectionEquipmentNo();
	validate_selLubricantId();
	validate_edtInspectionTemperature();
	validate_edtInspectionVibration();
	validate_edtInspectionDecibel();
	
	if (!errors)
	{
		var data 	= {};
		data.dummy 	= ""; //we seem to get errors from the first value, so always add a dummy value first.
		data.action = 5;
		
		if (document.getElementById("hddnInspectionId") 	!== null) 
			data.hddnInspectionId 	= document.getElementById("hddnInspectionId").value;
		if (document.getElementById("hddnInspectionModel") 	!== null)
			data.hddnInspectionModel = document.getElementById("hddnInspectionModel").value;

		data.selJobCardId 				= selJobCardId;
		data.edtInspectionSerialNo 		= edtInspectionSerialNo;
		data.selSplId 					= selSplId;
		data.selConditionStatusId		= selConditionStatusId;
		data.txtInspectionRemarks 		= txtInspectionRemarks;
		data.edtApplication 			= edtApplication;
		data.edtInspectionEquipmentNo 	= edtInspectionEquipmentNo;
		data.selLubricantId 			= selLubricantId;
		data.edtInspectionTemperature 	= edtInspectionTemperature;
		data.edtInspectionVibration 	= edtInspectionVibration;
		data.edtInspectionDecibel 		= edtInspectionDecibel;
		data.sableID					= 'inspectionRecord'+idx;
		data.table						= 'offline_inspections';
		data.timestamp					= parseInt(Date.now() / 1000);
		data.hddnUserCode				= sableUser;//getRecordId(sableUser);
		
		if (navigator.onLine)
		{
			//console.log('We are online - sending data directly.');
			callModule("inspection/inspection_val.php", data);
		}
		else
		{
			//console.log('We are adding the offline record to IndexedDB.');
			data.offline = true;
			sableAddRow("readwrite", data);
			cleanJobCardRecord(selJobCardId);
		}
	}
	else	
	{
		console.error('There are validation errors to be corrected.');
	}
}

function cleanJobCardRecord(selJobCardId)
{
	/*** REMOVE THE JOB CARD RECORD ***/
	sableRemoveRow("readwrite", "job_card|"+selJobCardId, startOver);
}

function startOver()
{
	alert('Inspection successfully added for synchronisation when online.');
	redirect('inspection');
}
