// Using  CMqHTTPRequest

var DISABLE_UPLOADS=1;
var DISABLE_LINKS=2;
var DISABLE_REMOVE=4;
var DISABLE_ALFRESCO=8;
var DISABLE_SHAREPOINT=16;

function MqAttachment(objDocument, attachmentsGrid)
{
	var FLD_FILE_UPLOAD = "MqUploadFile";
	var FLD_FILE_LINK_NAME = "MqLinkFileName";
	var FLD_FILE_LINK = "MqLinkFile";
	
	var m_objDocument=objDocument;
	
	var m_objUploadProps=new MqUploadProps();
	var m_objRequest=new CMqHTTPRequest_js();
	var m_objAttachmentUI=new MqAttachmentUI(m_objDocument, m_objUploadProps);
	var m_attachmentsGrid=attachmentsGrid;
	
	var m_bSuccess = false;
	var strUploadFile = "upload";
	var strLinkFile = "link";
	var varNewList = "";
	//var m_ar_strFileName ="";
	var m_strFilesLst="";
	var FILE_LIST_DELIM=";";
	
	var m_integrationWindow;
	var m_integrationInterval;
	
	//var UPLOAD_TYPE_PICTURE = 'pic';
	
	function MqUploadProps()
	{
		this.ParentID="";
		//this.AttachmentType="";
		this.Field=null;
		this.MaxFiles=-1;
	}
	
	function MqAttachmentUI(objDocument, objUploadProps)
	{
		//
		//  0=Nothing disabled. Uploads and Links enabled [default]
		//  1=Uploads disabled
		//  2=Links disabled
		//  3=Uploads & Links disabled
		//  4=Remove disabled
		//  7=All disabled
		//

		var m_objDocument=objDocument;
		var m_objUploadProps=objUploadProps;
		
		function DisableFormButtons()
		{
			//m_objDocument.getElementById("a_Upload").disabled = true;
			//m_objDocument.getElementById("a_Link").disabled = true;
			//m_objDocument.getElementById("a_Alfresco").disabled = true;
			//m_objDocument.getElementById("a_Close").disabled = true;
			
			
			//m_objMqButton.DisableButton("Upload");
			//m_objMqButton.DisableButton("Link");
			//m_objMqButton.DisableButton("Close");
		}
		
		function DisableAttachmentMode(intMode)
		{
			if ((intMode & DISABLE_UPLOADS)==DISABLE_UPLOADS){
				HideButton("UploadTab", m_objDocument);
			}
			if ((intMode & DISABLE_LINKS)==DISABLE_LINKS){
				HideButton("LinkTab", m_objDocument);
			}
			
			if ((intMode & DISABLE_ALFRESCO)==DISABLE_ALFRESCO){
				HideButton("AlfrescoTab", m_objDocument);
			}
			
			if ((intMode & DISABLE_SHAREPOINT)==DISABLE_SHAREPOINT){
				HideButton("SharePointTab", m_objDocument);
			}
			
			if(((intMode & DISABLE_LINKS)==DISABLE_LINKS) && ((intMode & DISABLE_UPLOADS)==DISABLE_UPLOADS) && 
					((intMode & DISABLE_ALFRESCO)==DISABLE_ALFRESCO) && ((intMode & DISABLE_SHAREPOINT)==DISABLE_SHAREPOINT)){
				var oTabsStrip=m_objDocument.getElementById("tabs");
			    if (oTabsStrip){
			    	oTabsStrip.style.visibility="hidden";
					oTabsStrip.style.display="none";
			    }
			}
			
			if ((intMode & DISABLE_REMOVE)==DISABLE_REMOVE){
				if(m_attachmentsGrid){
					m_attachmentsGrid.setColumnHidden(4,true);
				}

			}
		}
				

		this.DisableAttachmentMode=DisableAttachmentMode;
		this.DisableFormButtons=DisableFormButtons;
		
		function HideButton(strButtonName, objDocument)
		{
			var oBtn=objDocument.getElementById(strButtonName);
			if (oBtn){
				oBtn.style.visibility="hidden";
				oBtn.style.display="none";
			}			
		}
	}
	
	
	
	//public
	function AddUpload() 
	{
		var strFile=m_objDocument.getElementById(FLD_FILE_UPLOAD).value;
		if (strFile != ""){
			if(m_objUploadProps.MaxFiles > 0){
				if(m_objUploadProps.MaxFiles <= GetNumFilesInList()){
					g_MqRef.MsgHlpr.DisplayMessage(g_MqRef.RESX["ATT.MSG_ONLY_ONE_FILE_ALLOWED"]);
					return false;
				}
	 		}
 			//if (!FileAlreadyExists(strFile, strUploadFile)){
				if(strFile.indexOf(FILE_LIST_DELIM) > 0 ){
					g_MqRef.MsgHlpr.DisplayMessage(g_MqRef.RESX["ATT.MSG_FILE_CONTAINS_SEMICOLON"]);
				}else{
					/*if(m_objUploadProps.AttachmentType == UPLOAD_TYPE_PICTURE){
						m_ar_strFileName = strFile.split('\\');
						m_ar_strFileName = m_ar_strFileName[m_ar_strFileName.length - 1];
	
						varNewList = addItemToCsv (varNewList, m_ar_strFileName, FILE_LIST_DELIM);					
						SetFilesList(varNewList);
						
						m_bSuccess = true;
					}*/
				
					m_objAttachmentUI.DisableFormButtons();
					
					m_MainWin.OpenChildWindow('TmplUploading.htm', 'Uploading', 'width=250,height=125');
					m_objDocument.frmUpload.action= "attachments.asp?WCI=wciAttachment&src=1" + "&file=" + g_MqRef.MqStr.MqEncodeURIComponent(strFile) + GetContextQS(); 
					m_objDocument.frmUpload.method="post";
					m_objDocument.frmUpload.enctype="multipart/form-data";
					
					m_objDocument.frmUpload.submit();
				}
		}
		return m_bSuccess;
	}
	
	
	//private
	function SaveContext(current_VD, parent_ID, attachment_FldID)
    {        
	    m_objDocument.cookie = "currentVD=" + current_VD + ";Path=/";
        m_objDocument.cookie = "parentID=" + parent_ID + ";Path=/";
        m_objDocument.cookie = "attachFldID=" + attachment_FldID + ";Path=/";
	}

	//public
	function ConnectToExternalService(strServiceURL, strServiceName)
    {        
        var currentVD = window.location.href;
        currentVD = currentVD.substring(0, currentVD.lastIndexOf('/') +1);
        
        var parentID = m_oAttachment.UploadProps.ParentID;
        var attachFldID = m_oAttachment.UploadProps.Field.GetID();
        
        SaveContext(currentVD, parentID, attachFldID);
        
        var width = 1200;
        var height = 550;
        var left = (screen.width / 2)-(width / 2);
        var top = (screen.height / 2)-(height / 2);
        
        m_integrationWindow = window.open(strServiceURL, strServiceName, "width=" + width + ", height=" + height + ", left=" + left + ", top=" + top + ",toolbar=no,resizable=yes,directories=no,scrollbars=yes");

        if(m_integrationWindow){
			m_integrationInterval = window.setInterval(this.CheckIntegrationWindow, 1000);
		}

	}
	
	//public
	function CheckIntegrationWindow()
	{		
		if (m_integrationWindow.closed)
		{
			window.clearInterval(m_integrationInterval);
			Reload();
		}
	}
	
	//public
	function AddLink()
	{
	    var AttachmentSource_Linked = 0;
		var varFileName = m_objDocument.getElementById(FLD_FILE_LINK_NAME).value;
		var varFile = m_objDocument.getElementById(FLD_FILE_LINK).value;
		
		if (varFile.length > 0){
			
			varFile = CheckLink(varFile);
			
			if(varFileName.length == 0){
				varFileName = varFile;
			}
			
			//if (!FileAlreadyExists(varFile, strLinkFile)){
				if(varFile.indexOf(FILE_LIST_DELIM) > 0 ){
					g_MqRef.MsgHlpr.DisplayMessage(g_MqRef.RESX["ATT.MSG_FILE_CONTAINS_SEMICOLON"]);
				}else{
					m_objAttachmentUI.DisableFormButtons();
					var strUrl = "attachments.asp?WCI=AddLink&src=" + AttachmentSource_Linked + "&file=" + g_MqRef.MqStr.MqEncodeURIComponent(varFileName)
									+ "&uri=" + g_MqRef.MqStr.MqEncodeURIComponent(varFile) + GetContextQS(); 
					
					m_objRequest.Get(strUrl);
					
					m_objDocument.getElementById(FLD_FILE_LINK_NAME).value = "";					
					m_objDocument.getElementById(FLD_FILE_LINK).value = "";
					Reload();

				}
		}
	}
	
	function GetTempParentID()
	{
		var strTempID=m_MainWin.GetHiddenAttachFields("txtUploadDir");
		if(strTempID=="" || strTempID=="INIT"){
			strTempID=-Math.floor(Math.random()*1000001)
		}
		m_MainWin.SetHiddenAttachFields("txtUploadDir", strTempID);
		
		return strTempID;
	}
	
	//private
	function CheckLink(varFile)
	{
		var link = varFile;
		link=g_MqRef.MqStr.TrimString(link);
		if(g_MqRef.MqStr.Left(link, 1)=="\"" && g_MqRef.MqStr.Right(link, 1)=="\""){
			link=g_MqRef.MqStr.StripLeading(link, "\"");
			link=g_MqRef.MqStr.StripTrailing(link, "\"");
		}
		if(link.substring(0,7) == "http://" || link.substring(0,8) == "https://" || link.indexOf(":\\") >= 0)
		{
			return link;
		}
		
		else if(link.substring(0,2) == "\\\\")
		{
			link = link.replace(/\\/g,"/");
			
			return "file:" + link
		}
		
		else
		{
			return "http://" + link;
		}
	}
	
	//public
	function Remove(iAttachmentID)
	{
		if(iAttachmentID){
			if(window.confirm(g_MqRef.RESX["ATT.CONFIRM_REMOVE"])){
				var strUrl = "attachments.asp?WCI=Remove&attid=" + g_MqRef.MqStr.MqEncodeURIComponent(iAttachmentID)
								+ GetContextQS();
				m_objRequest.Get(strUrl);

				Reload();
			}
		}
	}
	
	function Reload()
	{
		$("#tabs").tabs({active:false});
		m_attachmentsGrid.clearAll();
		m_attachmentsGrid.load("attachments.asp?WCI=GetListXML" + GetContextQS(),"xml");
	}

	function GetContextQS()
	{
		var strQS="&ParentID=" + g_MqRef.MqStr.MqEncodeURIComponent(m_objUploadProps.ParentID)
				+ "&Fld=" + g_MqRef.MqStr.MqEncodeURIComponent(m_objUploadProps.Field.GetID());
		return strQS;
	}
	
	
	//private
	function GetToken(strFrom, intWhich, strSeparator)
	{
		var intPos = 0;
		var intPos1;

		for (var intCount = 0; intCount < intWhich; intCount++) {
			intPos1 = strFrom.indexOf(strSeparator, intPos + 1);
			if (intPos1== -1){  //not found
				intPos1 = strFrom.length + 1;
			}
			if (intCount != intWhich - 1){
				intPos = intPos1;
			}
		}

		if (intPos1 > intPos){
			var intLength;
			intLength = intPos1 - intPos;
			if (strFrom.charAt(intPos) == strSeparator){
				return (strFrom.substr(intPos + 1, intLength-1));
			}else{
				return (strFrom.substr(intPos, intLength));
			}
		}else{
			return ("");
		}
	}
	
	//private 
	function addItemToCsv(strList, strItem, strSeparator)
	{

		var nLength;
		var strNewList;

		nLength = strList.length;

		strNewList = strList;

		if (nLength == 0) {
		    strNewList = strItem;
		} else {

		    // check if the last character is already the separator
		    var strLastChar;

		    strlastChar = strList.substr(nLength-1, 1);

		    if (strLastChar == strSeparator) {
		        strNewList = strNewList + strItem;
		    } else {
		        strNewList = strNewList + strSeparator + strItem;
		    }
		}

	    return strNewList;
	}

	//private 
	/*function FileAlreadyExists(strFileName, strType)
	{
		if (strType.toLowerCase() == strUploadFile){
			//if it's being uploaded, we need to get just the file name
			var strBackSlash = "\\";
			var intIndex = strFileName.lastIndexOf(strBackSlash)+strBackSlash.length;
			var intLen = strFileName.length;
			strFileName = strFileName.substring(intIndex, intLen);
		}
		var strListOfFiles = GetFilesList();
		var blnExists = false;
		var arrFiles;
		arrFiles = strListOfFiles.split(FILE_LIST_DELIM);

		var intLen = arrFiles.length;
		var i;
		for(i=0; i<intLen; i++){
			if (arrFiles[i].toLowerCase() == strFileName.toLowerCase()){
				//the file exists already, return true
				blnExists = true;
				i=intLen;
			}
		}

		return blnExists;
	}	
	*/

	function GetFilesInList()
	{
		var strFiles="";
		if(m_attachmentsGrid){
			var arrRows=new Array();
			var strRows=m_attachmentsGrid.getAllRowIds(";");
			if(strRows!=""){
				var arrRowsTemp=strRows.split(";");
				for(x=0;x<arrRowsTemp.length;x++){
					var strFile=m_attachmentsGrid.cellById(arrRowsTemp[x],5).getValue();
					strFiles+= strFile + ";";
				}
			}
		}
		strFiles=g_MqRef.MqStr.StripTrailing(strFiles, ";");
		
		return strFiles;
	}
	
	function GetNumFilesInList()
	{
		var intNum=0;
		if(m_attachmentsGrid){
			intNum=m_attachmentsGrid.getRowsNum();
		}
		
		return intNum;
	}
	
	/*function GetFilesList()
	{
		return m_strFilesLst;
	}

	function SetFilesList(strFilesLst)
	{
		m_strFilesLst=strFilesLst;
	}*/
		
	function SetFieldCaption(strBaseCaption, strFilesList, strButtonName, objMqBtn)
	{
		var lngNumFiles=0;
		if(strFilesList!=""){
			var arrFiles=g_MqRef.MqStr.DecodeHTML(strFilesList).split(";");
			lngNumFiles=arrFiles.length;
		}
		
		var strNewCaption=strBaseCaption;
		
		if(lngNumFiles>0){
			strNewCaption+=" (" + lngNumFiles + ")";
		}
		objMqBtn.SetTextButtonCaption(strButtonName, strNewCaption);
	}
	
	this.AddLink = AddLink;
	this.Remove=Remove;
	this.AddUpload=AddUpload;
	this.Reload=Reload;
			
	this.ConnectToExternalService=ConnectToExternalService;
	this.CheckIntegrationWindow=CheckIntegrationWindow;
	
	//this.GetFilesList=GetFilesList;
	//this.SetFilesList=SetFilesList;
	
	this.AttachmentUI=m_objAttachmentUI;
	this.UploadProps=m_objUploadProps;
	this.SetFieldCaption=SetFieldCaption;
	this.GetFilesInList=GetFilesInList;
	this.GetTempParentID=GetTempParentID;
}