//  JavaScript Document



// handle user keypress to close the UI

function handleUserKeyEvent(e)

{

    var code = e.keyCode ? e.keyCode : e.which;

    

    // esc keycode = 27 ; return keycode = 13

    if ( code == 27 || code == 13 )

        window.projectHello.hostAppNotifyDoneWithDialog();

}



/**

 * IE doesn't handle the jQuery "keyup" event in the same way as

 * other browsers - so we need to do a little bandaging to get

 * things to work properly as other browsers dont process esc

 * as part of the keypress binding like IE does, so we needed

 * a solution that handled both.  In order to do that we need 

 * to detect IE correctly - but with IE11 they changed the 

 * userAgent strings so we need a little incantation here...

 * @see http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx

 */

var isIE = (( navigator.userAgent.indexOf("MSIE") > -1 && !window.opera ) || ( !!navigator.userAgent.match(/Trident.*rv[ :]*[1-9][0-9]\./) ));



if ( isIE )

{

    // IE based browser

	$(document).keypress(function(e) { handleUserKeyEvent(e); });

}

else

{

    // non-IE based browser

	$(document).keyup(function(e) { handleUserKeyEvent(e); });

}



$(document).bind( 'touchmove', function(e) { e.preventDefault(); } );



var personalizationProperties;



// Process Click on the New Document Buttons

function processNewDocClick( e, docType )

{

	var doSuppressUI = e.altKey;



	window.projectHello.hostAppCreateNewDoc( docType, doSuppressUI );

}



// Process Click on the Recent Document Buttons

function processRecentDocClick( e, docPath )

{

	window.projectHello.hostAppOpenDoc( docPath );

}



// Process the XML file

function processXMLFile(xmlData)

{

	var xmlDoc;



	// .each or .find isn't working in IE8

	// @see https://forum.jquery.com/topic/each-or-find-isn-t-working-in-ie8

	// 

 	if ( window.DOMParser )

    {

        parser = new DOMParser();

        xmlDoc = parser.parseFromString( xmlData,"text/xml" );

    }

    else // Internet Explorer

    {

        xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );

        xmlDoc.async = "false";

        xmlDoc.loadXML( xmlData );

    }



	// Build a selector based on the user type and do the selection

	$('InfoSet[type=' + personalizationProperties.accountType + ']',xmlDoc).each( function(i) 

	{

		// Substitute strings

		$('#welcomeTemplateCreateNewTitle').html( $(this).find("string[name=createNewTitle]").text() );

		$('#welcomeTemplateOpenRecentTitle').html( $(this).find("string[name=openRecentTitle]").text() );

		$('#welcomeTemplateResourcesTitle').html( $(this).find("string[name=marketingItemsTitle]").text() );

		$('#welcomeTemplateDontShowAgain').siblings('label').html( $(this).find("string[name=dontShowAgainTitle]").text() );



		// Find the Tutorial Items and loop over each of them

		$(this).find("tutorialItem").each( function(k) 

		{

	

			// Fill in the link address, image source, and text copy for the item

			$('#welcome_template_content_container a:eq('+k+')').attr("href", $(this).find("url").text());

			$('#welcome_template_content_container img:eq('+k+')').attr("src", $(this).find("imageSrc").text());

			$('#welcome_template_content_container h2:eq('+k+')').html( $(this).find("string[name=headline]").text() );

			$('#welcome_template_content_container p:eq('+k+')').html( $(this).find("string[name=body]").text() );

		});

	});

}



// Do several inialization steps immediately after the DOM is ready

$(document).ready( function () {

	try {



		// Retrieve the personalation properties from Muse

		personalizationProperties = jQuery.parseJSON( window.projectHello.hostAppGetPersonalizationInfo() );

		

		// Change the base font definition if the language is Korean, Chinese, or Japanese

		if ( personalizationProperties.language == "ja_JP" ) {

			$("#welcome_template_overall_container").removeClass('welcome_template_base_font_def').addClass('welcome_template_ja_font_def');

		}

		else if ( personalizationProperties.language == "ko_KR" ) {

			$("#welcome_template_overall_container").removeClass('welcome_template_base_font_def').addClass('welcome_template_ko_font_def');

		}

		else if ( personalizationProperties.language == "zh_TW" ) {

			$("#welcome_template_overall_container").removeClass('welcome_template_base_font_def').addClass('welcome_template_zh_font_def');

		}

        

        // Handle new doc types

        if ( "newDocTypes" in personalizationProperties )

        {

            var newDocTypes     = personalizationProperties.newDocTypes;

            var numNewDocTypes  = newDocTypes.length;

            

            for ( index = 0; index < numNewDocTypes; index++ )

            {

                var docType     = newDocTypes[index].docType;

                var docTypeName = newDocTypes[index].name;

                var docTypeTip  = newDocTypes[index].tip;

                

                $("#welcomeTemplateCreateNewContainer").append( '<a class="new_site_button"'

                    + ' title="' + docTypeTip + '"'

                    + ' onClick="processNewDocClick(event,\'' + docType + '\')" style="text-decoration:none; color: #000;"><p> <img src="resources/images/' + newDocTypes[index]["icon"]

                    + '.png" style="position: relative; top: 2px; height: 15px;" /> ' + docTypeName + '</p></a>');

            }

        }

        // Handle recent files

        if ( "recentFiles" in personalizationProperties )

        {

            var recentFiles     = personalizationProperties.recentFiles;

            var numRecentFiles  = recentFiles.length;



            /**

             * Ellipsis a text string in the middle based on a certain pixel width.

             *

             * @param str               string object to ellipsize

             * @param maxPxWidth        width to clip the string to in pixel units

             * @return A string object containing the ellipsized string.

             */

            var middleEllipsis = function( str, maxPxWidth )

            {

                  var ellipsisStr = "";



                if ((typeof str !== "undefined" && typeof maxPxWidth !== "undefined") && (( str.length > 1 ) && ( maxPxWidth > 0 )))

                {

                    /**

                    * Determine the pixel width of a string object on the current page.  This

                    * method requires the 'pxtextruler' tag object in the page to be setup

                    * with the proper font face and point size before the results will be

                    * accurate.

                    *

                    * @param str               string object to measure width in pixel units

                    * @return Integer value indicatating the width of the string in pixel units.

                    */

                    var strPixelLength = function( str )

                    {

                        var ruler = document.getElementById("pxtextruler");



                        if ( (typeof ruler === "undefined") || (typeof str === "undefined") ) { return 0; }



                        ruler.innerHTML = str;



                        return ruler.offsetWidth;

                    }



                    var pxWidth  = strPixelLength( str );

                  alert("px:"+pxWidth);

                    ellipsisStr  = str;

                  alert("len:"+ellipsisStr.length);

                    if ( pxWidth > maxPxWidth )

                    {

                        var middle    = Math.ceil( ellipsisStr.length / 2 );

                        var remainder = ellipsisStr.length - middle;

                        var subLeft   = ellipsisStr.substring( 0, remainder );

                        var subRight  = ellipsisStr.substring( middle );



                        for ( var i = 0; i < remainder; i++ )

                        {

                            ellipsisStr = subLeft + "..." + subRight;

                            pxWidth     = strPixelLength( ellipsisStr );



                            if ( pxWidth > maxPxWidth )

                            {

                                subLeft  = subLeft.substring( 0, subLeft.length - 1 );

                                subRight = subRight.substring( 1 );

                            }

                            else { break; }

                        }

                    }

                }

                return ellipsisStr;

            }



            for ( index = 0; index < numRecentFiles; index++ )

            {

                var fullFilePath    = recentFiles[index].fullpath;

//                  var displayName     = middleEllipsis( recentFiles[index].name, 254 );

                  var displayName     = recentFiles[index].name;

                var recentTip       = recentFiles[index].tip;

                

                $("#welcomeTemplateOpenRecentContainer").append( '<a class="recent-file open_site_button"'

                    + ' title="' + recentTip + '"'

                    + ' onClick="processRecentDocClick(event,\'' + fullFilePath + '\')" style="text-decoration:none; color: #000;"><p> <img src="resources/images/' + recentFiles[index]["icon"]

                    + '.png" style="position: relative; top: 2px; height: 15px;" /> '

                    + displayName + '</p></a>');

            }

        }

        // Set the dont show again checkbox value

        var dontShowAgainCheckbox = document.getElementById("welcomeTemplateDontShowAgain");

        

        if ( dontShowAgainCheckbox !== undefined )

        {

            dontShowAgainCheckbox.checked = ( 'dontShowAgain' in personalizationProperties ) ?

            ( ( personalizationProperties.dontShowAgain === "true" ||  personalizationProperties.dontShowAgain === "TRUE" ) ? true : false ) : false;

            

            $('#welcomeTemplateDontShowAgain').change( function() { window.projectHello.hostAppSetDoNotShowAgainPreference( $('#welcomeTemplateDontShowAgain').is(':checked') ); } );

        }

        

        // Load the contents of the Resource section from XML

        $.get("resources/" + personalizationProperties.language + "/WelcomeV1.xml", {}, processXMLFile )

        .fail(function() {

            $.get("resources/en_US/WelcomeV1.xml", {}, processXMLFile )

        });

	}

	catch (e) {

		alert( e.message );

	}

});