﻿<html>
<head>
	<script type="text/javascript" language="javascript" src="../ClientGlobalContext.js.aspx"></script>
	<meta charset="utf-8">
	<script type="text/javascript">
		var RTLlocaleArray = new Array(1025, 1037);
		var dir = "ltr";
		var locale = "1033";
		var clientUrl = "";

		try {
			var context = GetGlobalContext();
			if (context != null) {
				locale = context.getUserLcid();
				clientUrl = context.getClientUrl();
			}
		}
		catch (e) { }

		if (RTLlocaleArray.indexOf(locale) > -1) {
			dir = "rtl";
		}
		USD = {};
		USD.Context = {
			"dir": dir,
			"lcid": locale,
			"clientUrl": clientUrl
		};
		//load style based upon "RTL" and "LTR" language
		if (USD.Context.dir == "rtl") {
			addStyleSheet("styles/CustomizationFilesStyle_RTL.css");
		}
		else {
			addStyleSheet("styles/CustomizationFilesStyle_LTR.css");
		}
		function addStyleSheet(filename) {
			var fileref = document.createElement("link");
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", filename)

			if (typeof fileref != "undefined")
				document.getElementsByTagName("head")[0].appendChild(fileref);
		}
	</script>
</head>
<body>
	<div id="loadingContainer" class="ms-usd-LoadingContainer">
	</div>
	<div id="parentDiv" style="display: none;">
		<span class="title" id="fileLabel"></span>
		<div id="divContent" class="divContent">
			<b class="border-notch notch"></b><b class="notch"></b>
			<div class="footer">
				<span class="actionArea">
					<div id="attachAction" style="display: none;" class="attachAction">
						<img class="attachImage" src="Images/Attachment_16.gif">
						<button title="" class="attachLink" id="attachButton" onclick="showUploadFile();" onmouseover="buttonMouseOver('attachButton');" onmouseout="buttonMouseOut('attachButton');"
							alt="" href="#">
						</button>
						<iframe class="notesAttachmentIframe" style="display: none;" id="customizationFilesIframe"
							src="about:blank" frameborder="0" scrolling="no"></iframe>
					</div>
					<div id="showAction" style="display: none;" class="showAction" onmouseover="downloadFileMouseHover();"
						onmouseout="downloadFileMouseOut();">
						<img class="attachImage" src="Images/Attachment_16.gif">
						<a class="attachmentSpacer" title="" id="downloadFile" onclick="downloadAttachment()"
						   href="#"></a>
						<div class="deleteAttachmentAction">
							<a id="deleteAttachmentLink" href="#" onclick="deleteAttachment();" style="display: none;">
								<img id="deleteAttachmentImage" style="border: none;" title="" alt="" src="Images/Delete_16.png" />
							</a>
						</div>
					</div>
					<div id="doneAction" style="display: none;" class="doneAction">
						<button title="" class="attachLink" id="doneButton" onclick="uploadAttachment();" onmouseover="buttonMouseOver('doneButton');" onmouseout="buttonMouseOut('doneButton');"
							alt="" href="#">
						</button>
					</div>
				</span>
			</div>
		</div>
	</div>
	<script type="text/javascript">
	    var attachButtonText = "";
	    var attachButtonAltText = "";
	    var doneButtonText = "";
	    var doneButtonAltText = "";
	    var deleteButtonAltText = "";
		var fileValidationText = "";
		var fileLabelText = "";
		var deleteConfirmationText = "";
		var attachmentFailureText = "";
		var attachmentName = "";
		var parentIframeTabIndex = "";
		var deleteAttachmentTitleText = "";

		var body = document.getElementsByTagName("body")[0];
		var loadingDiv = document.getElementById("loadingContainer");

		var parentDocument = window.parent.document;
		if (parentDocument != null) {
			var parentIframe = parentDocument.getElementById("IFRAME_CustomizationFiles");
			if (parentIframe != null) {
				parentIframeTabIndex = parentIframe.tabIndex;
			}
		}

		function addScript(path) {
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.onerror = handleLocError;
			script.src = path;
			body.appendChild(script);
		}

		function handleLocError() {
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = "scripts/SettingsPageStrings.js";
			body.appendChild(script);
		}

		USD.OnPageLoad = function () {
			try {
				var getResourceStrings = USD.Resources.CustomizationFilesPage;
				attachButtonText = getResourceStrings.attachButton;
				attachButtonAltText = getResourceStrings.attachButtonAltText;
				doneButtonText = getResourceStrings.doneButton;
				doneButtonAltText = getResourceStrings.doneButtonAltText;
				deleteButtonAltText = getResourceStrings.deleteButtonAltText;
				fileValidationText = getResourceStrings.fileValidation;
				fileLabelText = getResourceStrings.fileLabel;
				deleteConfirmationText = getResourceStrings.deleteConfirmation;
				attachmentFailureText = getResourceStrings.attachmentFailure;
				deleteAttachmentTitleText = getResourceStrings.deleteAttachmentTitle;

				var fileLabel = document.getElementById("fileLabel");
				if (fileLabel != null) {
					fileLabel.innerHTML = fileLabelText;
				}
				var attachButton = document.getElementById("attachButton");
				if (attachAction != null) {
					attachButton.innerHTML = attachButtonText;
					attachButton.title = attachButtonAltText;
					attachButton.alt = attachButtonAltText;
				}
				var doneButton = document.getElementById("doneButton");
				if (doneButton != null) {
					doneButton.innerHTML = doneButtonText;
					doneButton.title = doneButtonAltText;
					doneButton.alt = doneButtonAltText;
				}
				var deleteAttachmentImage = document.getElementById("deleteAttachmentImage");
				if (deleteAttachmentImage != null) {
					deleteAttachmentImage.title = deleteButtonAltText;
					deleteAttachmentImage.alt = deleteButtonAltText;
				}

				loadCustomizationFilesAttachment();
				setDisplayProperty("loadingContainer", "none");
			}
			catch (e) { }
		}
		addScript("scripts/SettingsPageStrings" + (locale == 1033 ? "" : "_" + locale) + ".js");

		//For RTL languages this will change the body direction
		body.setAttribute("dir", USD.Context.dir);
		body.setAttribute("onload", showLoadingIcon());

		function showLoadingIcon() {
			//set iframe source dynamically to avoid issues in non-default organization
			setCustomizationIframeSource();

			var loadingText = window.parent.document.getElementById("loading");
			if (loadingText != null) {
				loadingText = loadingText.alt;
			}

			if (loadingDiv != null) {
				var loadingTable = "<table class='ms-usd-LoadingContainer'>";
				loadingTable += "<tr class='ms-usd-LoadingContainer'><td align='center'><img id='DialogLoadingDivImg' alt='' src='/_imgs/AdvFind/progress.gif' /> <br/> <span style='font-size:11px;'>" + loadingText + "</span></td></tr>";
				loadingTable += "</table>"
				loadingDiv.innerHTML = loadingTable;
			}
		}

		//If attachment is already attached to record it will display the attachment link
		//if not it will just show the options to upload the file
		function loadCustomizationFilesAttachment() {
			var result = retriveAttachment();
			if (result != "") {
				var file = result.ReturnValue.AnnotationCollection.AnnotationUI;
				if (file != null) {
					var fileName = file.FileName;
					showDowloadFile(fileName);
				}
			}
			else {
				setDisplayProperty("attachAction", "inline-block");
				setDisplayProperty("doneAction", "inline-block");
			}
			document.getElementById("attachButton").tabIndex = parentIframeTabIndex;
			setDisplayProperty("parentDiv", "inline");
		}

		//Retrives the attachment using parent record id
		function retriveAttachment() {
			var parentId = checkForParentRecord();
			if (parentId != "") {
				window._sWebServicesNamespace = window.parent._sWebServicesNamespace;
				if (window._aWrpcTokens == null) {
					window._aWrpcTokens = {};
				}
				window._aWrpcTokens = window.parent._aWrpcTokens;

				var command = new RemoteCommand("Annotation", "RetrieveNotesCollection");
				command.SetParameter("parentEntityId", parentId);
				command.SetParameter("pageNumber", 1);
				command.SetParameter("pageSize", 1);
				command.SetParameter("pagingCookie", "");
				var result = command.Execute();

				if (checkRemoteCommandResult(result)) {
					if (result.ReturnValue.AnnotationCollection.AnnotationUI != null) {
						return result;
					}
					else {
						return "";
					}
				}
			}
			return "";
		}

		//This function returns the files control iframe document object
		function getIframeObject() {
			var iframeObject = null;
			if (window.frames["customizationFilesIframe"] != null) {
				iframeObject = window.frames["customizationFilesIframe"];

				if (iframeObject.contentDocument) {
					return iframeObject.contentDocument;
				}
				else if (iframeObject.document) {
					return iframeObject.document;
				}
			}
			return iframeObject;
		}

		//Onclick of done button it will upload the attachment to the customiztionfiles entity current record
		function uploadAttachment() {
			var customizationFrame = getIframeObject();
			if (customizationFrame != null) {
				var isValidFileExtension = false;
				var notesText = "";
				var fileControl = customizationFrame.getElementById("userFile");
				if (fileControl != null) {
					if (fileControl.files != undefined) {
						var file = fileControl.files[0];
						if (file != null) {
							if (file.type != null && file.name != null) {
								//Javascript file.type is not working in some specific environment hence using file name to identify the file extension(.zip)
								//file extension can be renamed to CAPS("Zip or ZIP") so converting to lowercase to avoid attachment failure
								if (file.type.match("zip.*") || file.name.split('.').pop().toLowerCase() == "zip") {
									isValidFileExtension = true;
									notesText = file.name;
								}
							}
						}
					}
					else {
						//IE9 browser is not supporting property ".files" hence validating file extension through input control ".value" property
						var strFileName = fileControl.value;
						var fileExtention = strFileName.substring(strFileName.lastIndexOf(".") + 1, strFileName.length).toLowerCase();
						if (fileExtention == "zip") {
							isValidFileExtension = true;
							notesText = strFileName.split(/(\\|\/)/g).pop();
						}
					}
				}
				if (isValidFileExtension) {
					var parentId = checkForParentRecord();
					if (parentId != "") {
						customizationFrame.getElementById("IsSPDocument").value = "false";
						customizationFrame.getElementById("OverwriteExistingFile").value = "false";
						attachmentName = notesText;
						var ParentEntityType = "msdyusd_customizationfiles";
						var UserId = GetGlobalContext().getUserId();
						var downloadUrl = customizationFrame.getElementById("crmAttachment").getAttribute("url") + '?AttachmentType=' + CrmEncodeDecode.CrmUrlEncode(customizationFrame.getElementById("AttachmentType").value) + '&AttachmentId=' + CrmEncodeDecode.CrmUrlEncode("") + '&IsNotesTabAttachment=' + CrmEncodeDecode.CrmUrlEncode("0") + customizationFrame.getElementById("crmAttachment").getAttribute("wrpctokenurl");

						var Submitxml = "<annotation><isdocument>0</isdocument><notetext>" + CrmEncodeDecode.CrmXmlEncode(notesText) + "</notetext><objectid>" + CrmEncodeDecode.CrmXmlEncode(parentId) + "</objectid><objecttypecode>" + ParentEntityType + "</objecttypecode><subject>" + CrmEncodeDecode.CrmXmlEncode(downloadUrl) + "</subject><ownerid type='8'>" + UserId + "</ownerid></annotation>";
						customizationFrame.getElementById("crmFormSubmitXml").value = Submitxml;
						if (customizationFrame.getElementById("Attachments") != null) {
							//Since Attachments are deleted we must clear the attachment id
							if (customizationFrame.getElementById("AttachmentId").value != "") {
								var sue = customizationFrame.getElementById("SuccessURL").value;
								var osu = Mscrm.CrmUri.create(sue.value);
								delete osu.get_query()["id"];
								customizationFrame.getElementById("AttachmentId").value = "";
							}
							try {
								customizationFrame.getElementById("Attachments").submit();
								customizationFrame.onload = handleAttachmentError;
							}
						    catch (e) {
						        showAlertDialog(USD.Resources.CustomizationFilesPage.fileValidationTitle, attachmentFailureText, USD.Resources.ConfigurationPage.okButton, '');
							}
						}
					}
				}
				else {
				    showAlertDialog(USD.Resources.CustomizationFilesPage.fileValidationTitle, fileValidationText, USD.Resources.ConfigurationPage.okButton, '');
				}
			}
		}

		//Download's the current attachment and also shows the option to delete the current attachment and add new attachment
		function downloadAttachment() {
			var result = retriveAttachment();
			if (result != "") {
				if (checkRemoteCommandResult(result)) {
					if (result.ReturnValue.AnnotationCollection != null &&
						result.ReturnValue.AnnotationCollection.AnnotationUI != null) {
						var durl = result.ReturnValue.AnnotationCollection.AnnotationUI.Title;
						//replacing the <Title> tag and extra spaces/escape characters.
						durl = durl.replace(/amp;/g, '').replace("<Title>", "").replace("</Title>", "");
						var osu = Mscrm.CrmUri.create(durl);
						var attachmentId = result.ReturnValue.AnnotationCollection.AnnotationUI.NoteId;
						osu.setQueryParameter("AttachmentId", attachmentId);
						window.location.href = Mscrm.CrmUri.create(osu.toString());
					}
				}
			}
		}

		//Delete's the current attachment from the current record
		function deleteAttachment() {
		    showConfirmDialog(deleteAttachmentTitleText, deleteConfirmationText, USD.Resources.ConfigurationPage.OK, USD.Resources.ConfigurationPage.Cancel, deleteCallBack);
		}

		function deleteCallBack(returnValue) {
		    if (returnValue) {
		        yesDeleteCallback();
		    }
		    else {
		        noDeleteCallback();
		    }
		}

		function noDeleteCallback() {
		    return true;
		}

		function yesDeleteCallback() {
		    var id = "";
		    var result = retriveAttachment();
		    if (result != "") {
		        if (checkRemoteCommandResult(result)) {
		            if (result.ReturnValue.AnnotationCollection.AnnotationUI != null) {
		                id = result.ReturnValue.AnnotationCollection.AnnotationUI.NoteId;
		            }
		        }
		    }
		    if (id != "") {
		        var command = new RemoteCommand("Annotation", "DeleteAnnotation");
		        command.SetParameter("id", id);
		        var result = command.Execute();
		        if (checkRemoteCommandResult(result)) {
		            setDisplayProperty("showAction", "none");
		            setDisplayProperty("doneAction", "inline-block");
		            setDisplayProperty("attachAction", "inline-block");
		            setDisplayProperty("attachButton", "inline-block");
		            setDisplayProperty("customizationFilesIframe", "none");
		            changeFooterBackground(false);
		            //After delete of attachement need to reload the notes control iframe to delete existing query string values
		            attachmentName = "";
		            setCustomizationIframeSource();
		        }
		    }
		}

		//helper function
		function showAlertDialog(title, message, okText, cancelText) {
		    var options = new Xrm.DialogOptions;
		    options.width = 550;
		    options.height = 205;
		    var url = Mscrm.CrmUri.create("$Webresource:msdyusd_/ConfirmDialog.html?Data=");
		    Xrm.Internal.openDialog(url + encodeURIComponent("title=" + title + "&message=" + message + "&ok=" + okText + "&cancel=" + cancelText + "&cancelTitle=" + USD.Resources.ConfigurationPage.Cancel), options, window, null, null);
		}

	    //helper function
		function showConfirmDialog(title, message, okText, cancelText, callback) {
		    var options = new Xrm.DialogOptions;
		    options.width = 550;
		    options.height = 205;
		    var url = Mscrm.CrmUri.create("$Webresource:msdyusd_/ConfirmDialog.html?Data=");
		    Xrm.Internal.openDialog(url + encodeURIComponent("title=" + title + "&message=" + message + "&ok=" + okText + "&cancel=" + cancelText + "&cancelTitle=" + USD.Resources.ConfigurationPage.Cancel), options, window, null, callback);
		}

		//helper function
		function setDisplayProperty(elementName, elementValue) {
			var elementName = document.getElementById(elementName);
			if (elementName != null) {
				elementName.style.display = elementValue;
			}
		}

		//helper function
		function checkRemoteCommandResult(result) {
			if (result != null) {
				if (result.Success) {
					return true;
				}
			}
			return false;
		}

		//helper function
		function showDowloadFile(fileName) {

			setDisplayProperty("attachAction", "none");
			setDisplayProperty("doneAction", "none");
			setDisplayProperty("showAction", "inline-block");
			setDisplayProperty("downloadFile", "inline-block");

			var downloadFile = document.getElementById("downloadFile");
			if (downloadFile != null) {
				downloadFile.title = fileName;
				downloadFile.innerHTML = fileName;
				downloadFile.tabIndex = parentIframeTabIndex;
			}
			changeFooterBackground(true);
		}

		//helper function
		function downloadFileMouseHover() {
			if (window.parent != null && typeof (window.parent.Xrm) != 'undefined' && window.parent.Xrm != null && window.parent.Xrm.Page != null
				&& window.parent.Xrm.Page.ui != null) {
				var formType = window.parent.Xrm.Page.ui.getFormType();
				var XRM_FORM_TYPE_READONLY = 3;
				var XRM_FORM_TYPE_DISABLED = 4;
				if (formType != XRM_FORM_TYPE_READONLY && formType != XRM_FORM_TYPE_DISABLED) {
					var downloadFileDiv = document.getElementById("showAction");
					if (downloadFileDiv != null) {
						setDisplayProperty("deleteAttachmentLink", "inline-block");
						downloadFileDiv.style.background = "#d7e8f9";
					}
				}
			}
		}

		//helper function
		function downloadFileMouseOut() {
			var downloadFileDiv = document.getElementById("showAction");
			if (downloadFileDiv != null) {
				setDisplayProperty("deleteAttachmentLink", "none");
				downloadFileDiv.style.background = "#ffffff";
			}
		}

		//helper function
		function showUploadFile() {
			var parentId = checkForParentRecord();
			if (parentId != "") {
				setDisplayProperty("attachButton", "none");
				setDisplayProperty("customizationFilesIframe", "inline-block");
				setTabIndex();
			}
		}

		function setTabIndex() {
		    var customizationFrame = getIframeObject();
		    if (customizationFrame != null) {
		        var userFile = customizationFrame.getElementById("userFile");
		        if (userFile != null) {
		            userFile.tabIndex = parentIframeTabIndex + 1;
		        }
		    }
		}

		//helper function
		function setCustomizationIframeSource() {
			var noteurl = "/Notes/NotesV2Attach.aspx";
			var notesControl = document.getElementById("customizationFilesIframe");

			if (notesControl != null) {
			    notesControl.src = USD.Context.clientUrl + noteurl;
			    //if attachment size is exceed than limit need to retrive "PopUpErrorURL" from query string
                //and show the error dialog
			    notesControl.onload = handleAttachmentError;
			}
		}

		function handleAttachmentError() {
		    var customizationFrame = getIframeObject();
			if (customizationFrame.location.pathname.toLowerCase().indexOf("/notes/notesv2attach.aspx") == -1) {
				//If the file size limit exceeds or any other error is thrown.
				if (!IsNull(customizationFrame.getElementById("PopupErrorUrl")) && customizationFrame.getElementById("PopupErrorUrl").value != "") {

					setDisplayProperty("attachButton", "inline-block");
					setDisplayProperty("customizationFilesIframe", "none");

					options = new Xrm.DialogOptions;
					options.width = 550;
					options.height = 260;
					var url = Mscrm.CrmUri.create(customizationFrame.getElementById("PopupErrorUrl").value);
					Xrm.Internal.openDialog(url.toString(), options, null, null, null);
				}
				else {
					setDisplayProperty("showAction", "none");
					setDisplayProperty("doneAction", "inline-block");
					setDisplayProperty("attachAction", "inline-block");
					setDisplayProperty("attachButton", "inline-block");
					setDisplayProperty("customizationFilesIframe", "none");
					attachmentName = "";
					setCustomizationIframeSource();

					options = new Xrm.DialogOptions;
					options.width = 550;
					options.height = 260;
					var url = Mscrm.CrmUri.create("_common/error/dlg_error.aspx?dType=1&hresult=");
					Xrm.Internal.openDialog(url.toString(), options, null, null, null);
				}
			}
		    else {
		        if (attachmentName != "") {
		            showDowloadFile(attachmentName);
		        }
		    }
		}

		//helper function
		function checkForParentRecord() {
			var parentId = window.parent.Xrm.Page.data.entity.getId();
			if (parentId != null && parentId != "") {
				return parentId;
			}
			else {
				var attachButton = document.getElementById("attachButton");
				var doneButton = document.getElementById("doneButton");
				if (attachButton != null && doneButton != null) {
					attachButton.disabled = true;
					doneButton.disabled = true;
				}
				return "";
			}
		}

		function buttonMouseOver(buttonId) {
			var getButton = document.getElementById(buttonId);
			if (getButton != null) {
				if (getButton.disabled) {
					getButton.style.backgroundColor = "#fdfdfd";
				}
				else {
					getButton.style.backgroundColor = "#d7e8f9";
				}
			}
		}

		function buttonMouseOut(buttonId) {
			var getButton = document.getElementById(buttonId);
			if (getButton != null) {
				getButton.style.backgroundColor = "#fdfdfd";
			}
		}

		//helper function
		function changeFooterBackground(flag) {
			var footerDiv = document.getElementById("footer");
			if (footerDiv != null) {
				if (flag) {
				    footerDiv.style.backgroundColor = "#ffffff";
				}
				else {
					footerDiv.style.backgroundColor = "#f8f8f8";
				}
			}
		}
	</script>
</body>
</html>
