// Dependencies
// 		window.js
// 		VNWindow
//		CMqURIUtils
// 		MqWebSessionURL

//--------------------------------------------------------------------------------------------------------------
//
// Parameters
// 	objMainDocRef: reference to censusmain (main doc with constants.js, etc. referenced.
// 	objControlsSs:	reference to a MqControlsServerSide object
// 	objFrames: reference to a MqFrames object
// 	objLoadDataMgr:  reference to a CMqLoadDataMgr object
//
//--------------------------------------------------------------------------------------------------------------

function CMqRecord(objMainDocRef, objControlsSs, objFrames, objLoadDataMgr){
	
	var _me=this;
	var m_objRecordId;
	var m_objRecordDisplay;
	var m_objFormElement=new objMainDocRef.CMqFormElement();
	
	var m_objMainDocRef=objMainDocRef; // e.g. CensusMain
	var m_objControlsSs=objControlsSs;
	var m_objFrames=objFrames;
	var m_objLoadDataMgr=objLoadDataMgr;
	var m_oTabs=new VNTabs();
	var MAIN_RECFORM_BASEURL="wcRecord.asp?";
	
	var LOAD_REC_CTNR="loadRec";
	var LOAD_REC_OVERLAY_CTNR = "loadRecOverlay";
	
	function Initialize(oCtrlRecordID,oCtrlRecordDisplay)
	{			
		m_objRecordId=oCtrlRecordID;
		m_objRecordDisplay=oCtrlRecordDisplay;	
	}
	
	function SetRecordId(lngRecordId)
	{		
		if ((m_objRecordDisplay) && (m_objRecordId)){
			if (lngRecordId=="") {
				lngRecordId=m_objMainDocRef.NO_CURRENT_RECORD;
			}
			m_objRecordId.value=lngRecordId;
			// Sync with new RecordMgr
			g_VWS.RecordMgr().CurrentRecord().SetRecID(lngRecordId);
			if (lngRecordId>0) {
				m_objRecordDisplay.value=lngRecordId;
			}else{
				m_objRecordDisplay.value="";
			}
		}	
	}
	
	function GetRecordId()
	{		
		return _me._GetRecordId(m_objMainDocRef, m_objRecordDisplay, m_objRecordId);
	}
		
	function GetVisibleRecordId()
	{
		if ((m_objRecordDisplay) && (m_objRecordId)){
			return Number(m_objRecordDisplay.value);
		}else{
			return m_objMainDocRef.NO_CURRENT_RECORD;		
		}
	}
		
	
	function DisableRecord(blnDisable)
	{		
		if(m_objRecordDisplay){
			m_objFormElement.Disable(blnDisable, m_objRecordDisplay);				
		}
	}

	function SynchronizeWithIntern()
	{
		var varRecordId;
		//get internally record ID
		varRecordId=this.GetRecordId();
		//set the internal record ID to the visible one
		this.SetRecordId(varRecordId);
		
	}
	function SynchronizeWithVisible()
	{
		var varRecordId;
		//get the visisible record ID
		varRecordId=this.GetVisibleRecordId();
		//set the visble record ID to the internal one
		this.SetRecordId(varRecordId);
	}
	
	function Resize()
	{
		var objLoadRec=objMainDocRef.document.getElementById(LOAD_REC_CTNR);
		if(objLoadRec){
			if(objLoadRec.style.display===""){
				_me.Show();
			}
		}
	}
	
	function OnBeforeLoad()
	{
		_me.ShowLoadingUI(true);
	}
	
	function OnAfterLoad()
	{
		_WriteTitleInfo(m_objMainDocRef, m_objControlsSs, m_objRecordDisplay, m_objRecordId);
		
		_HandleHistoryButton(m_objMainDocRef, m_objControlsSs, m_objFrames);
	}
	
	function Show()
	{
		if(m_objMainDocRef){
			// LoadRec contains the Tabs + RecordForm + CommandBar + LoadData (hidden)
			var objLoadRec=m_objMainDocRef.document.getElementById(LOAD_REC_CTNR);
			
			if(objLoadRec){			
				var arrWinSize=m_objMainDocRef.GetWindowSize(m_objMainDocRef.WIN_MODE_MAXIMIZED, null, null, true);
				var lngWidth=arrWinSize[0];
				var lngHeight=arrWinSize[1];
				var intBodyWidth=arrWinSize[2];
				var intBodyHeight=arrWinSize[3];
				var intBrowserWidth=arrWinSize[4];
				var intBrowserHeight=arrWinSize[5];
				var BORDER_WIDTH=4;
				
				if(parent.document.location.href.toLowerCase()==document.location.href.toLowerCase()){
					//open same URL
					objLoadRec.style.marginTop=(((((intBrowserHeight-lngHeight)/2)-((intBrowserHeight-intBodyHeight)/2))/2)+BORDER_WIDTH)+"px";
					objLoadRec.style.marginLeft=(((((intBrowserWidth-lngWidth)/2)-((intBrowserWidth-intBodyWidth)/2))/2)+BORDER_WIDTH)+"px";
				}else{
					//opened a new view
					lngHeight=intBodyHeight;
					lngWidth=intBodyWidth;
				}
			}
			objLoadRec.style.height=lngHeight+"px";
			objLoadRec.style.width=lngWidth+"px";
			
			_SetRecordTabHeight(lngHeight, m_objMainDocRef);
			
			objLoadRec.style.display="";
		}
	}
	

	function Load(iRecordID, iSelTabID)
	{
	
		var oRecFormWin;
		
		ga('send', 'event', g_VWS.ViewName() , 'Load', iRecordID);
		
		_me.OnBeforeLoad();
					
		oRecFormWin= m_objMainDocRef.objFrames.GetFrameWindow(objMainDocRef.RECORD_FRAME_ID);
			
		//Make sure the form is ready to interact with us.
		if (oRecFormWin != null)
		{	
				
			//If the user is loading a different record...
			if(_me.GetRecordId() != iRecordID)
			{
				if (_me.OnBeforeNavigate)
				{
					// todo: move the event constant to a class
					_me.OnBeforeNavigate(CLOSE_SCENARIO_USER_LEAVES_ISSUE_CONTEXT);
				
				}
			}
				
			_me.SetRecordId(iRecordID);

			// Load the Record form from the correct URL. 
			// This should only be needed once since the form stays open but hidden 
			
			if (oRecFormWin.location.href.indexOf(MAIN_RECFORM_BASEURL)==-1)
			{
				oRecFormWin.location.replace(MAIN_RECFORM_BASEURL);
			}
			
			//SetState(COMMANDBAR_FRAME_ID, BUSY_STATE);
			//if(objFeatures.getFeature(FEATURE_RECORD)){
			
			// TODO: move controlsaction.View to here
				objControls.View(null, iSelTabID);
			//}else{
				// not implemented yet ExpandSLItem(intRecordID);
			//}
			//SetState(COMMANDBAR_FRAME_ID, IDLE_STATE);
			
		} else {
			// just kill some time to let the command bar load
			// and then call the same function again
			var DELAY = 5;
			setTimeout(function(){
						_me.Load(iRecordID,iSelTabID);
					}, DELAY);
					
		}		
	}

	function Hide()
	{
		_me.ShowLoadingUI(false);
		
		var objLoadRec=m_objMainDocRef.document.getElementById(LOAD_REC_CTNR);
		if(objLoadRec){
			objLoadRec.style.display="none";
		}
	}

	function ShowLoadingUI(blnVisible, blnForceToFront)
	{
		var objLoadRecOverlay=m_objMainDocRef.document.getElementById(LOAD_REC_OVERLAY_CTNR);
		if(objLoadRecOverlay){
			if(blnForceToFront){
				objLoadRecOverlay.style.zIndex=9999;
			}else{
				objLoadRecOverlay.style.zIndex=1001;
			}
			if(blnVisible){
				objLoadRecOverlay.style.display="";
			}else{
				objLoadRecOverlay.style.display="none";
				
			}
		}
	}
	
	function Tabs()
	{
		return m_oTabs;
	}
	

	
	this._GetRecordId=_GetRecordId;
	this.Initialize=Initialize;
	this.OnBeforeLoad=OnBeforeLoad;
	this.OnAfterLoad=OnAfterLoad;
	this.Show=Show;
	this.Hide=Hide;
	this.SetRecordId=SetRecordId;
	this.GetRecordId=GetRecordId;
	this.DisableRecord=DisableRecord;
	this.GetVisibleRecordId=GetVisibleRecordId;
	this.SynchronizeWithVisible=SynchronizeWithVisible;
	this.SynchronizeWithIntern=SynchronizeWithIntern;
	this.Resize=Resize;
	this.ShowLoadingUI=ShowLoadingUI;
	this.Tabs=Tabs;
	this.OnBeforeNavigate=null; // to be set from the outside
	this.Load=Load;
	
	//private static functions

	function _ResolveIssueID(strString, objMainDocRef, objRecordDisplay, objRecordId)
	{
		if(strString){
			var regExp=new RegExp("<ValOfField>1</ValOfField>","g");
			return strString.replace(regExp,_me._GetRecordId(objMainDocRef, objRecordDisplay, objRecordId));
		}
	}

	//private and static version of GetRecordId
	function _GetRecordId(objMainDocRef, objRecordDisplay, objRecordId)
	{
		if ((objRecordDisplay) && (objRecordId)){
			if (objRecordId.value===""){
				objRecordId.value=objMainDocRef.NO_CURRENT_RECORD;				
			}
			return Number(objRecordId.value);
		}else{
			return objMainDocRef.NO_CURRENT_RECORD;
		}
	}
	
	function _WriteTitleInfo(objMainDocRef, objControlsSs, objRecordDisplay, objRecordId)
	{
		var objTitle=objMainDocRef.document.getElementById("wizTitle");
		var objDesc=objMainDocRef.document.getElementById("wizDesc");
		var objMacros=new objMainDocRef.CMqMacros();
		var strTitleTemplate;
		var strDescTemplate;
		var objExistingIssueBtns=objMainDocRef.document.getElementById("ExistingIssueButtons");
		
		if(!objMainDocRef.g_VWS.RecordMgr().CurrentRecord().IsNewRecord()){
			strTitleTemplate=objMainDocRef.WIZARD_TITLE_EDIT;
			strDescTemplate=objMainDocRef.WIZARD_DESCRIPTION_EDIT;
			if(objExistingIssueBtns){
				objExistingIssueBtns.style.display="";
			}
		}else{
			strTitleTemplate=objMainDocRef.WIZARD_TITLE;
			strDescTemplate=objMainDocRef.WIZARD_DESCRIPTION;
			if(objExistingIssueBtns){
				objExistingIssueBtns.style.display="none";
			}
		}
		
		strTitleTemplate=_ResolveIssueID(strTitleTemplate, objMainDocRef, objRecordDisplay, objRecordId);
		strDescTemplate=_ResolveIssueID(strDescTemplate, objMainDocRef, objRecordDisplay, objRecordId);

		if(objMacros){	
			if(objTitle){			
				objTitle.innerHTML=objMacros.ResolveFieldMacros(strTitleTemplate,m_objLoadDataMgr,false, true);
			}
			if(objDesc){			
				objDesc.innerHTML=objMacros.ResolveFieldMacros(strDescTemplate,m_objLoadDataMgr,false, true);
			}
		}
	}

	function _HandleHistoryButton(objMainDocRef, objControlsSs, objFrames)
	{
		var HISTORY_BTN_NAME="cmdViewHistory";
		var objTabsFrame=objFrames.GetFrameWindow(objMainDocRef.TABS_FRAME_ID);
		if(objTabsFrame){
			var objHistButton=objTabsFrame.document.getElementById(HISTORY_BTN_NAME);
			if(objHistButton){
				if(!objMainDocRef.g_VWS.RecordMgr().CurrentRecord().IsNewRecord()){
					objHistButton.style.display="";
				}else{
					objHistButton.style.display="none";
				}
			}
		}
	}


	function _SetRecordTabHeight(lngWinHeight, objMainDocRef)
	{
		var iRecHeaderHeight=125; // same as in objMainDocRef.document.getElementById("RecHeader").offsetHeight;
		var BUFFER_NO_SCROLL=2; //make the document smaller than the iframe so there's no scrollbar
		var intRecHeight=lngWinHeight-iRecHeaderHeight-objMainDocRef.DEFAULT_TABS-objMainDocRef.DEFAULT_COMMANDBAR-objMainDocRef.DEFAULT_LOADDATA;
		var objRecFrame=objMainDocRef.document.getElementById(objMainDocRef.RECORD_FRAME_NAME);
		var objDivRec=objMainDocRef.document.getElementById("mbliOSRec");
					
		if(objRecFrame){
			objRecFrame.style.height=intRecHeight+"px";
			objRecFrame.style.width=100+"%";
			
			objRecFrame=m_objFrames.GetFrameWindow(objMainDocRef.RECORD_FRAME_ID);
			if(objDivRec != undefined) {
				if(objMainDocRef.DEFAULT_TABS == 0) {
					objDivRec.style.top = "103px"; // its the toolbar height plus the margins plus the borders without the tabs height
				}
			}
			if(objRecFrame){
				var objRecBody;
				
				if(objRecFrame.document){
					objRecBody=objRecFrame.document.body;
					if(objRecBody){
						objRecBody.style.height=intRecHeight-BUFFER_NO_SCROLL+"px";
					}
				}
			}
		}
	}
}





function CMqRecordMgr(objLoadData, objRequest, strFieldDelim, strFieldValueDelim)
{
	var _me=this;
	var m_objLoadData=objLoadData;
	var m_objRequest=objRequest;

	var m_oRecord;	// VNRecord
	var m_oVWS;
	_me.SaveOnlyChangedFields=false;
	var objFieldVals=m_objLoadData.GetObjFieldValues();
	
	if(objFieldVals){
		if(strFieldDelim){
			objFieldVals.SetFieldDelimiter(strFieldDelim);
		}
		
		if(strFieldValueDelim){
			objFieldVals.SetFieldValueDelimiter(strFieldValueDelim);
		}
	}
	
	function Save(lngRecordID, lngRevisionNumber, blnOnlyChangedFields, 
	strSaveURL, strAddRecQS, blnForceSave, lngSaveOnConflict, blnPropStrEnc)
	{
		var strResult="";
		var strQueryString="";
		
		ga('send', 'event', g_VWS.ViewName() , 'Save', lngRecordID);
		
		if(strAddRecQS){
			strQueryString += strAddRecQS;
		}

		if (blnOnlyChangedFields==null)
		{
			blnOnlyChangedFields=_me.SaveOnlyChangedFields;
		}

		strQueryString += m_objLoadData.GetDataForSave(blnOnlyChangedFields, blnPropStrEnc);
		if(strQueryString!=""){			
			var strReturn="";
			var strSaveURL;
			var strPostData;
		
			if(!lngSaveOnConflict){
				lngSaveOnConflict=0;
			}
			
			strPostData ="nId="+lngRecordID+"&nRevisionNumber="+lngRevisionNumber +
						"&bAcceptSave="+blnForceSave+"&bQueryString="+g_MqRef.MqStr.MqEncodeURIComponent(strQueryString) + 
						"&SOC="+lngSaveOnConflict;
			
			strReturn=m_objRequest.Post(strSaveURL,strPostData);

			if (strReturn!=m_objRequest.CANCEL_PROCESS){
				
									
				var objResponse=m_objRequest.Response(strReturn);
				if (objResponse){
					if (objResponse.HasErrors()){
						var objErrors=objResponse.GetErrors();
						if(objErrors){
							if(objErrors.Count()>0){
								var objErr=objErrors.Item(0);
								if(objErr){
									 if(String(objErr.GetNumber())=="-2147211944"){
										strResult="";
										if(window.confirm(objErr.GetText())){
											Save(lngRecordID,lngRevisionNumber,blnOnlyChangedFields, strSaveURL, strAddQS, blnForceSave, 1);
										}
									}else{
										strResult=objErr.GetText();
									}
								}
							}
						}
					}else{
						var objMsgContent=objResponse.GetContent();

						if(objMsgContent){
							strResult=objMsgContent.GetText();
							
							// Special case for required fields
							var re=new RegExp("The field (.+) is a required field. Please enter the required field before saving.","g");
							var arrMatches = re.exec(strResult);
							
							if (arrMatches)
							{
								strResult=g_MqRef.MqStr.Format(g_MqRef.RESX["WARNING_MESSAGE_REQUIRED_FIELD"], arrMatches[1]);
							}
							
						}
					}
				}
			}
		}
		
		return strResult;
	}
	
	
	function Fields()
	{
		return objFieldVals;
	}
	
	function OpenInNewSession(iID) 
	{

		var oWVO=new WebViewOpener(m_oVWS.URL(), m_oVWS.HTTPRequest() );
		
		if (this.WebViewOpenInNewSession!=="")
		{
			oWVO.Open(this.WebViewOpenInNewSession,false,iID);
		}
	
	}

	function CurrentRecord()
	{
		return m_oRecord;
	}

	function SetVecWebSession(oVWS)
	{
		m_oVWS = oVWS;
		
		// Initialize the CurrentRecord object
		m_oRecord = new VNRecord(m_oVWS);	
		
	}

		//** Save the specified fields to all the specified dts records 
	//**  Returns a string with a message if not full success.
	function SaveBatch( sRecIDs, sDataForSave )
	{
		var ret="";
					//debugger;
		if ( m_objRequest && sDataForSave)
		{
			var url=g_VWS.MainWindow().ViewFolderURL() +"/html/wcCmdBar.asp?wci=wciCommand&Command=Batch";
			var sPost ="nId="+ sRecIDs + "&bQueryString="+ encodeURIComponent(sDataForSave);
			
			var co=m_objRequest.Post(url, sPost);
		
			if (co!=m_objRequest.CANCEL_PROCESS){					
				var objResponse=m_objRequest.Response(co);
				if (objResponse.HasErrors()){
					objResponse.ProcessErrors("",true);
				}else
				{
					var objMsg=objResponse.GetContent();
					if (objMsg){
						ret=objMsg.GetText();					
					}		
				}
			}			
		}	
		return ret;		
	}  


	
	this.WebViewOpenInNewSession="";	// e.g. "HelpDesk/Edit HelpDesk Ticket"
	this.Save=Save;
	this.Fields=Fields;
	this.CurrentRecord=CurrentRecord;
	this.SetVecWebSession=SetVecWebSession;
	this.OpenInNewSession=OpenInNewSession;
	this.SaveBatch=SaveBatch;
	
}



	

// Represents a VN Record . 
// Right now, the instance stays but is loaded with different ID and Revision when the 
// DTS Rec is loaded
function VNRecord(oVecWebSession)
{
	var _me=this;
	var m_oLoadDataMgr;	
	var m_oViewFlds;
	// Array of VNFormFields, one per field
	var m_arrFrmFlds = new Array();
	var m_iRecID=-1;
	var m_lngRevisionNumber=-1;
	var m_oVecWebSession=oVecWebSession;
	
	if (oVecWebSession)
	{
		m_oLoadDataMgr=oVecWebSession.LoadDataMgr();	
		m_oViewFlds=oVecWebSession.ViewFields();
	}
	
	function GetFormField(iFldID)
	{

		if (iFldID)
		{
			
			var oFrmFld=m_arrFrmFlds[iFldID];
			
			if (!oFrmFld)
			{
				// create a vn form field from the field definition
				var oFld=m_oViewFlds.Field(iFldID);
				
				if (oFld)
				{
					// Add to array
					oFrmFld= new VNFormField(oFld,m_oLoadDataMgr.GetDataHTMLDocumentObject());
					m_arrFrmFlds[iFldID]=oFrmFld;

				}	
					
			}
			
			return oFrmFld;
								
		}
	}

	// Shortcut to returns the value form element of a dts field
	function FldVals(iFldID)
	{

		if (iFldID)
		{
			// Get the vn form field
			var oVNFrmFld=_me.GetFormField(iFldID);
			
			return oVNFrmFld.GetValueControl();
								
		}
	}
	
	//g_VWS.RecordMgr().CurrentRecord().IsNewRecord()
	function IsNewRecord() 
	{
		if (this.GetRevisionNumber() > 0) 
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	//g_VWS.RecordMgr().CurrentRecord().SetRecID(x);
	function SetRecID(iRecID)
	{
		m_iRecID=iRecID;
	}
	
	//g_VWS.RecordMgr().CurrentRecord().GetRecID();
	function GetRecID()
	{
		return m_iRecID;
	}
	
	//g_VWS.RecordMgr().CurrentRecord().SetRevisionNumber(x);
	function SetRevisionNumber(lngRevisionNum)
	{
		m_lngRevisionNumber=lngRevisionNum;
	}
	
	//g_VWS.RecordMgr().CurrentRecord().GetRevisionNumber();
	function GetRevisionNumber()
	{
		return m_lngRevisionNumber;
	}
	
	// TODO: pass LoadDataMgr in constructor instead
	function ResolveMacros(sStr,oLoadDataMgr,bResolveChoiceIDsToText)
	{
		if (sStr && oLoadDataMgr && m_oVecWebSession.Macros){
			sStr=m_oVecWebSession.Macros.ResolveFieldMacros(sStr,oLoadDataMgr,
													true,bResolveChoiceIDsToText);
			        
		}
		return sStr;
	
	}
	
	function GetHTMLDocObj()
	{
		if (m_oLoadDataMgr)
		{
			return m_oLoadDataMgr.GetDataHTMLDocumentObject();
		}
	}
	
	this.GetHTMLDocObj=GetHTMLDocObj;	
	this.IsNewRecord = IsNewRecord;
	this.FldVals=FldVals;
	this.GetFormField=GetFormField;
	this.SetRecID=SetRecID;
	this.GetRecID=GetRecID;
	this.SetRevisionNumber=SetRevisionNumber;
	this.GetRevisionNumber=GetRevisionNumber;
	this.ResolveMacros=ResolveMacros;
}

// Represents a VN Record Form
// TODO: consider initializing VNRec inside
function VNRecForm(oVNRec, oLoadDataMgr, oVecWebSession)
{
	var _me=this;
	var m_oVecWebSession=oVecWebSession;
	var m_oLoadDataMgr=oLoadDataMgr;	
	var m_oVNRec=oVNRec;
	
	
	function GetRecord()
	{
		return m_oVNRec;
	}

	
	function OpenURL(strURL,sWinName, oWinProp, blnAsChildWin)
	{               
		var MAX_URL_LEN=2020;
		if (!sWinName){
			sWinName="_blank";
		}

		// Resolve field macros to the current values if needed 
		m_oVNRec.ResolveMacros(strURL,m_oLoadDataMgr,_me.ResolveChoiceIDsToText);
		
		var objURIUtils=new CMqURIUtils();
		if(objURIUtils){
			strURL=objURIUtils.AddURIProtocol(strURL);
		}

	
		if (strURL.length>MAX_URL_LEN){
			strURL=strURL.substr(0,MAX_URL_LEN);
		}

		if(blnAsChildWin)
		{
			var oWin = new VNWindow(oWinProp.Modal);
			oWin.Open(strURL, sWinName, oWinProp.Width, oWinProp.Height, null, null, oWinProp.SizeMode);
			
		}else{
			window.open(strURL,sWinName);
		}
    }
	
	this.ResolveChoiceIDsToText=false;
	this.GetRecord=GetRecord;
	this.OpenURL=OpenURL;

}

function VNTabs()
{

	this.Visible=true;

}



