<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>In App Message</title>
    <link href="../../InAppWalkthrough/styles/iam.css" rel="stylesheet" type="text/css">

    <script src="../../Shared/Common/Scripts/UsageTracking.js"></script>
	<script src="../../InAppWalkthrough/scripts/jquery.min.js"></script>
	<script src="../../InAppWalkthrough/scripts/jquery.i18n.properties-1.0.9.js"></script>
	<script src="../../InAppWalkthrough/scripts/handlebars-v3.0.0.js"></script>

	<script id="handlebars-template" type="text/x-handlebars-template">

        <div class="container">
            <div class="content"> 
				<!-- Title -->
				<h4 class="featureTitle"> {{I18n UPDATES_TITLE}} 
					<span class="featureTag hintComponent size_tag"> {{I18n UPDATES_SIZE}} </span>
					<span class="featureTag hintComponent hintInstalledComponent success_tag"> {{I18n UPDATES_TAG_INSTALLED}} </span>
					<span class="featureTag hintComponent hintErrorComponent error_tag"> {{I18n UPDATES_TAG_ERROR}} </span>
				</h4>

				<!-- Updates -->
				{{#list UPDATES}} <p class="secondary_heading" data-link="{{{LINK}}}"> {{TITLE}} </p> <p class="description"> {{DESC}} </p> {{/list}}

				<!-- Error banner -->
				<div class="banner hintComponent hintErrorComponent">
					<p class="description banner_text error_banner error_text">{{{I18n UPDATES_CTA_ERROR_BANNER}}}</p>
				</div>

				<!-- Call to action -->
				<div id="hintConsent" class="hintComponent">

					<!-- Update -->
					<div id="hintUpdateButton" class="button_large">
						<a href="#" button_large-hover="{{I18n UPDATES_CALL_TO_ACTION}}"> <span>{{I18n UPDATES_CALL_TO_ACTION}}</span></a>
					</div>

					<!-- Later -->
					<p id="hintLaterButton" class="later">{{I18n UPDATES_REMINDER}}</p>
				</div>

                <!-- Downloading -->
                <div id="progress_bar" class="downloading hintComponent"> {{I18n UPDATES_CTA_PROGRESS}} <span>.</span><span>.</span><span>.</span></div>

                <!-- Download complete -->
				<div id="hintDownloaded" class="hintComponent">
					<div class="banner">
					  <p class="description banner_text"> {{I18n UPDATES_CTA_SUCCESS_BANNER}} </p>
					</div>
					<div class="success_label">{{I18n UPDATES_CTA_SUCCESS}}</div>
				</div>

                <!-- Installation complete -->
				<div class="hintComponent hintInstalledComponent">
					<div id="hintSuccessLabel" class="success_label hintComponent">{{I18n UPDATES_INSTALL_SUCCESS}}</div>
					<div id="hintSuccessButton" class="button_large hintComponent">
						<a href="#" button_large-hover="{{I18n UPDATES_INSTALL_CALL_TO_ACTION}}"> <span>{{I18n UPDATES_INSTALL_CALL_TO_ACTION}}</span></a>
					</div>
				</div>
            </div>
        </div>

	</script>

	<script>
		$(function() {

			var autoCloseTimer;
            
            function getQueryVariables() {
				var result = {};
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i=0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair.length === 2){
						result[pair[0]] = pair[1];
					}
				}
				return result;
			}

			// Get query variables
			var vars = getQueryVariables();
			vars.state = vars.state || "consent"; // Various states - consent, progress, downloaded, installed, error
			vars.installCTA = false;

			function isKeyDefined (key) {

				// If key is returned as [key], its not defined
				if ($.i18n.prop(key) === "[" + key + "]") {
					return false;
				}
				return true;
			}

			// Generate HTML from template
			function renderHTML() {

				// Register for localized strings
				Handlebars.registerHelper('I18n', function(str){

					// If I18n is available, return localized string
					return ($.i18n ? $.i18n.prop(str) : str);
				});

				// To list all updates available
				Handlebars.registerHelper('list', function(items, options) {
					var out = "";

					for(var i=0, l=items.length; i<l; i++) {
						out = out + options.fn(items[i]);
					}

					return out;
				});

				// Build context
				var context = {
					UPDATES_TITLE: "UPDATES_TITLE",
					UPDATES_SIZE: "UPDATES_SIZE",
					UPDATES_TAG_INSTALLED: "UPDATES_TAG_INSTALLED",
					UPDATES_TAG_ERROR: "UPDATES_TAG_ERROR",
					UPDATES_CALL_TO_ACTION: "UPDATES_CALL_TO_ACTION",
					UPDATES_REMINDER: "UPDATES_REMINDER",
					UPDATES_CTA_PROGRESS: "UPDATES_CTA_PROGRESS",
					UPDATES_CTA_SUCCESS_BANNER: "UPDATES_CTA_SUCCESS_BANNER",
					UPDATES_CTA_SUCCESS: "UPDATES_CTA_SUCCESS",
					UPDATES_CTA_ERROR_BANNER: "UPDATES_CTA_ERROR_BANNER",
					UPDATES_INSTALL_SUCCESS: "UPDATES_INSTALL_SUCCESS",
					UPDATES_LOCALE: "UPDATES_LOCALE",
					UPDATES_INSTALL_CALL_TO_ACTION: "UPDATES_INSTALL_CALL_TO_ACTION_EN_US",
					UPDATES_INSTALL_CALL_TO_ACTION_SCRIPT: "UPDATES_INSTALL_CALL_TO_ACTION_SCRIPT",
					UPDATES: []
				};

				var updateCount = parseInt($.i18n.prop("UPDATES_COUNT"), 10) || 0;
				if (updateCount > 0) {

					for (var i=0; i < updateCount; i++) {

						var prefix = "UPDATE_" + i + "_";
						var title = "",
							version = "",
							desc = "",
							link = "";

						if (isKeyDefined(prefix + "TITLE")) {
							title = $.i18n.prop(prefix + "TITLE");
						}
						if (isKeyDefined(prefix + "VERSION")) {
							version = " " + $.i18n.prop(prefix + "VERSION");
						}
						if (isKeyDefined(prefix + "DESC")) {
							desc = $.i18n.prop(prefix + "DESC");
						}
						if (isKeyDefined(prefix + "LINK")) {
							link = $.i18n.prop(prefix + "LINK");
						}

						if (title !== "" || desc !== "") {
							var update = {};

							update["TITLE"] = title + version;
							update["DESC"] = desc;
							update["LINK"] = link;

							context.UPDATES.push(update);
						}
					}
				}

				// Determine install success CTA
				if (isKeyDefined(context.UPDATES_LOCALE)) {
					var locale = $.i18n.prop(context.UPDATES_LOCALE);
					locale = locale.toUpperCase();
					var cta = "UPDATES_INSTALL_CALL_TO_ACTION_" + locale;
					// Update localized Call To Action only if it is defined.
					if (isKeyDefined(cta)) {
						context.UPDATES_INSTALL_CALL_TO_ACTION = cta;
					}
				}

				// If only one update is available, CTA and script are defined, show installCTA
				if (updateCount === 1
					&& isKeyDefined(context.UPDATES_INSTALL_CALL_TO_ACTION)
					&& isKeyDefined(context.UPDATES_INSTALL_CALL_TO_ACTION_SCRIPT)) {
					vars.installCTA = true;
				}

				// Handlebar template
				var source = $("#handlebars-template").html();
				var template = Handlebars.compile(source);
				var html = template(context);

				// Append HTML to body tag
				$( "body" ).append(html);
			}

			function autoCloseFunction () {
				autoCloseTimer = undefined;
				if (window.notify) {
					window.notify("close");
				}
			}
            
            function updateVisibility () {

				// First hide all hintComponents
				$(".hintComponent").hide();

				// Show components based on the state
				if (vars.state === "consent" || vars.state === "error") {
					$("#hintConsent").show();
					if (vars.state === "error") {
						$(".hintErrorComponent").show();
					}
				} else if (vars.state === "progress") {
					$("#progress_bar").show();
				} else if (vars.state === "downloaded") {
					$("#hintDownloaded").show();
				} else if (vars.state === "installed") {
					$(".hintInstalledComponent").show();
					if (vars.installCTA) {
						$("#hintSuccessButton").show();
					} else {
						$("#hintSuccessLabel").show();
					}
				}

				// If no other tag is visible, then show size tag
				if($(".featureTitle > .success_tag").first().is(':hidden') 
				   && $(".featureTitle > .error_tag").first().is(':hidden')) {
					$(".featureTitle > .size_tag").show();
				}

				if (window.notify) {

					// Notify NFWHint that the size is changed.
					window.notify("sizeChanged");

					// Update visibility of the close button
					if (vars.state === "consent") {
						window.notify("hideCloseButton");
					} else {
						window.notify("showCloseButton");
					}
				}

				// Start auto-timer for success messages
				if (vars.state === "downloaded" || vars.state === "installed") {
					if (autoCloseTimer) {
						clearTimeout(autoCloseTimer);
					}
					autoCloseTimer = setTimeout(autoCloseFunction, 60000);
				}

			}

			$.i18n.properties({
				name: ['updates', 'updatesInfo', 'updatesAction'],
				language: ' ',
				path: 'Strings/',
				mode: 'both',
				callback: function () {
					renderHTML();
					updateVisibility();
				}
			});

			// Watch out for marker file.
			function watchMarkerFile() {
				var htmlUrl = window.location.href.split('?')[0];
				var updatesDirUrl = htmlUrl.split('/').slice(0, -2).join('/');
				var markerFileUrl = updatesDirUrl + "/Marker/processComplete";
				var repeater;

				function doWatch() {
					$.get(markerFileUrl)
						.done(function(data) {
							if ((typeof data === "string") && (data === "Success")) {
								vars.state = "downloaded";
							} else {
								vars.state = "error";

								// Delete install directory and marker file
								if (window.evalJS) {
									var script = "var updatesDirURL = dw.getUserConfigurationPath() + \"Updates\";";
									script = script + "var instllDirURL = updatesDirURL + \"/Install\";";
									script = script + "DWfile.remove(instllDirURL);";
									script = script + "var markerFileURL = updatesDirURL + \"/Marker/processComplete\";";
									script = script + "DWfile.remove(markerFileURL);";
									window.evalJS(script);
								}
							}
							updateVisibility();
						}).fail(function() {
							repeater = setTimeout(doWatch, 2000);
						})
				}

				doWatch();
			}

			// Actions
			// Update button click
			$("#hintUpdateButton").click( function() {

				if (window.evalJS) {

					// 1. Show progress
					vars.state = "progress";
					updateVisibility();

					// 2. Log highbeam
					var script = "dw.logEvent(\"" + UT_UPDATES_SUBCATEGORY + "\",\"" + UT_UPDATES_UPDATE_CLICKED + "\");";
                    window.evalJS(script);

					// 3. Execute download script
					var scriptUrl = "file://DW_USER_CONFIG/Updates/Core/Download.js";
                    window.evalJS(scriptUrl);

					// 4. Watch out for marker file
					watchMarkerFile();
				}
			});

			// Later button click
			$("#hintLaterButton").click( function() {

				if (window.evalJS) {

					// Remind after 4 days
					var laterDays = 4;
					var laterDate = new Date();
					laterDate.setDate(laterDate.getDate() + laterDays);
					var seconds = Math.floor(laterDate.getTime() / 1000);

					var script = "dw.setPreferenceString(\"Updates\", \"Reminder Time For Updates\", \"" + seconds.toString() + "\");";
					script = script + "dw.logEvent(\"" + UT_UPDATES_SUBCATEGORY + "\",\"" + UT_UPDATES_REMIND_LATER_CLICKED + "\");";
                    window.evalJS(script);
				}

				if (window.notify) {
					window.notify("close");
				}
			});

			// Install success button click
			$("#hintSuccessButton").click( function() {

				// First hide current window and then execute any script. Generally script would open a dialog e.g. NDD 
				// and if current window is closed after executing script, it will be closed after the dialog is closed.

				if (window.notify) {
					window.notify("close");
				}

				if (window.evalJS) {
					if (isKeyDefined("UPDATES_INSTALL_CALL_TO_ACTION_SCRIPT")) {
						var script = $.i18n.prop("UPDATES_INSTALL_CALL_TO_ACTION_SCRIPT");
						if (script) {
							window.evalJS(script);
						}
					}
				}
			});

			$(".secondary_heading").click( function() {

				if (window.evalJS) {

					var link = event.currentTarget.getAttribute("data-link");
					if (link && (typeof link === "string") && (link !== "")) {
						var script = "dw.browseDocument('" + link + "', \"HelloSysDefault\");";
						window.evalJS(script);
					}
				}
			});

			// Special function: 'onCloseButtonClicked' function on window object gets called on Close button click
			window.onCloseButtonClicked = function() {
				if (autoCloseTimer) {
					clearTimeout(autoCloseTimer);
				}
			}

		});
	</script>

	</head>

	<body>

	</body>

</html>
