/******************************************************************************************************
 * Mod Log
 * Version  Author            Date           Description
 *  1.0     Jim Lamoureaux    Dec 21, 2007
 *  2.0     Guravaiah_P       Aug 07, 2008   MODIFICATION IN preHandle()FOR HOME PAGE,WELCOME TEXT 
 *                                           CHARACTER ENCODING PROBLEM
 *  3.0     Guravaiah_P       Aug 12, 2008   IS WORK REQUEST : 13279
 *                                           Modification for Display of Last Name to Japanese Users.
 *  4.0     Guravaiah_P       Nov 17, 2008   REMEDY TICKET NO: INC000000130129 
 *                                           SPACE ISSUE AT FIRST NAME AND LAST NAME 
 *  5.0     Samapika_Guru     Jan 27, 2009   Modified for 9.2.1 - SEO title changes and myanalog saves.
 *  6.0     Pratyusha Ghosh   Aug 18, 2009   Site-redesign: Modified as part of myAnalog Integration for
 *                                           the new site interface and behavior.
 *  7.0     Dhamotharan   Dec 03, 2009   Site-redesign: Modified for the work request 15595 as part of 10.1.2 release.
 *  8.0     Dhamotharan   Jan 06, 2010   Site-redesign: Modified for the work request 15024 as part of 10.1.2 release.
 * 
 ******************************************************************************************************/


/*
 * JS module for integrating with myAnalog.
 */

/**
 * The MyAnalogRemote object.
 *
 */
var MyAnalogRemote = { name: "MyAnalogRemote" };

/**
 * This is the module initialization function.	It will run when this script
 * file is loaded.
 *
 */
(function(m) {

	/**
	 * This variable can be set from the calling page.  The initialization will try to
	 * discover it hidden in a non-visible div tag.
	 */
	var MYANALOG_URI		 = "https://my.analog.com";

	/**
	 * This variable can be set from the calling page.  The initialization will try to
	 * discover it hidden in a non-visible div tag.
	 */
	var REGISTRATION_URI	 = "https://registration.analog.com";

	/**
	 * This variable will be initialized in the $(document).ready function
	 * near the end of this initialization sequence.
	 */
	var DEFAULT_WELCOME		 = 'NOT_SET';

	/** The element ID of the Log In / Logout link in the header. */
	var LOGIN_LOGOUT_ID		 = "#login_logout_link";

	/** The element ID of the ajax login form container. */
    // Start: Site-redesign changes
    var LOGIN_PARENT        = "#my_analog_mega";

    var LOGIN_PARENT_CONTENT_AREA        = "my_analog_area";
    // End: Site-redesign changes
    
	/**
	 * The name of the myAnalog cookie which holds the name|username if user
	 * previously logged in.<b>
	 * This variable might be initialized in the $(document).ready function
	 * near the end of this initialization sequence.
	 */
	var MYANALOG_COOKIE_NAME = "myAnalog_id";

	/** Derived from the myAnalog Cookie */
	var MYANALOG_FIRST_NAME;
	
	/** Derived from the myAnalog Cookie */
	var MYANALOG_LAST_NAME;

	/** Derived from the myAnalog Cookie */
	var MYANALOG_USERNAME;

	/**
	 * Used to ignore the unauthorized response.  This may be needed
	 * when the page first loads and a fetch of the user profile is
	 * attempted to assess login state, but the user is not logged in.
	 */
	// Site-redesign modified
	var DISABLE_LOGIN = false;

    // Site-redesign added
    /**
     * Used to ignore profileFetch when set to true. Used mainly when
     * only CALLER reset in done.
     */
    var DISABLE_PROFILE_FETCH = false;

	/**
	 * Flag which controls whether the popup message should be displayed.
	 */
	var DISPLAY_POPUP = true;

	/**
     * Name of the calling page (e.g., "main" or "savetomyanalog").  Most pages
     * can simply use "main".  When invoked from 'saveToMyAnalog' function, uses "savetomyanalog"
	 */
	var CALLER = "main";

	/**
	 * The message catalog object.  Will be initialized in the $(document).ready
	 * function.
	 */
	var MSG_CAT;

	//START: Site Redesign 10.1.2 release: Work Request 15595
	/**
	 * Flag which controls whether the loggedin view should be displayed or not.
	 */
	var DISPLAY_LOGGEDIN_VIEW = true;
	//END: Site Redesign 10.1.2 release: Work Request 15595

	/**
	 * Interpolates values from the array 'arr' into the string 'text' in a manner similar to java.text.MessageFormat.
	 *
	 * text - the format string, for example, "Hello {0}!"
	 * arr  - the array of items to be interpolated into the text string, e.g., ["Jim"]
	 * returns the text argument with the {0}, {1}, etc. placeholders replaced by values from the arr array.
	 */
	function msgFormat(text, arr) {
		for (var i=0; i < arr.length; i++) {
			var re = new RegExp('\\{' + i + '\\}', 'g');
			text = text.replace(re, arr[i]);
		}
		return text;
	}

	/**
	 * Handles the response for myAnalog info when the user is not yet
	 * logged in to myAnalog.  Delegates processing to the handler.
	 *
	 * @see onUnauthorizedResponse.handler
	 */
	function onUnauthorizedResponse(event) {
		event.caller = CALLER;
		triggerLoginLogout("logout"); // Making sure that the UI displays properly
		if (!DISABLE_LOGIN) {
			onUnauthorizedResponse.handler(event);
		}
		DISABLE_LOGIN = false;
	}
	
	/**
	 * Handler for unauthorized responses.	Calling pages can override
	 * this function.
	 *
	 */
	onUnauthorizedResponse.handler = function (event) {
        // If the calling page has no 'welcome_user' element,
		// then this section has no effect.
        // Start: Site-redesign modified
        $("div#welcome_user").hide(1, function () {
			setWelcomeText();
			$(this).show();
		});
		// Call the response's run() function to display the login form.
		// Site-redesign: Setting the default handler area as the Main myAnalog
		// login area in the header.
        event.run(LOGIN_PARENT, LOGIN_PARENT_CONTENT_AREA);
        // End: Site-redesign modified
	}

	/**
	 * Main entry point for fetching the user profile data.	 Calling pages
	 * can override the pre() and post() functions, if desired.
	 *
	 * @see fetchProfile(cb)
	 */
	function getUserProfile(cb) {

		getUserProfile.pre();

		fetchProfile(cb);

		getUserProfile.post();
	}
	getUserProfile.pre	= function () {}
	getUserProfile.post = function () {}

    // Start: Site-redesign Added
	/**
     * If log in is successful, draws the logged in user view.
     */
    function drawLoggedinState(firstName) {
        var regUrl = buildRegistrationLink();
        var myanalogUrl = MYANALOG_URI + '/index.html';
        var loggedInView = '<table width="200" border="0" cellpadding="0" cellspacing="0">';
        loggedInView = loggedInView.concat('<tr><td>', msgFormat(MSG_CAT['myanalog.logged.hello'], [firstName]));
        loggedInView = loggedInView.concat(' | <a href="#" id="my_analog_logout">', MSG_CAT['myanalog.logout.label'],  '</a></td></tr>');        loggedInView = loggedInView.concat('<tr><td>', '<span class="arrow_right"><a href="', myanalogUrl, '">', MSG_CAT['myanalog.go.to'], '</a></span></td></tr>');
        loggedInView = loggedInView.concat('<tr><td>', msgFormat(MSG_CAT['myanalog.logged.diffuserlogin'], [regUrl]), '</td></tr>');
        loggedInView = loggedInView.concat('</table>');
        
        var parentDiv = $(LOGIN_PARENT);
        $(parentDiv).empty();
        parentDiv.append('<div class="mega_top"></div><div id="' + LOGIN_PARENT_CONTENT_AREA + '"></div><div class="div_clear"></div><div class="mega_bottom"></div>');
        var loginDiv = $('#' + LOGIN_PARENT_CONTENT_AREA, parentDiv);
        loginDiv.append(loggedInView.toString());
        
        // Registering the '#my_analog_logout' Logout link with the main '#login_logout_link' 
        // logout link to fake a 'click' event on the main logout.
        $("#my_analog_logout", loginDiv).click(function () {
            $("div#welcome_user " + LOGIN_LOGOUT_ID).click();
        });        
        return false;
    }
    // End: Site-redesign Added
    
    /**
	 * Callback invoked when a valid user profile response is returned.
	 * Delegates to the handler.  Callers can override the
	 * onProfileResponse.handler function.
	 *
	 */
	function onProfileResponse(event) {		
		//Start 9.3.1: INC000000160682 'Please wait' message box not disappearing fix
        $('#savepopup').hide();
		//End 9.3.1: INC000000160682 'Please wait' message box not disappearing fix		
	
		triggerLoginLogout("login"); // Making sure the login/logout link displays properly.
    	onProfileResponse.handler(event);
	}
	onProfileResponse.handler = function (event) {
		var json = event.response;
		var msgCat = MSG_CAT;
		var name = json.ADIRegUser.firstName;
		var lastName = json.ADIRegUser.lastName;
		var locale = obtainLocaleFromPath(location.pathname);
		if (locale == "jp"){name = lastName;}
        // Start: Site-redesign changes
        var welcomeNote = msgFormat(msgCat['myanalog.welcome'], [name]);

		// This block will run if the calling page has a block with id='welcome_user'.
        $("div#welcome_user").hide(1, function () {
            $("span#user").html(welcomeNote);
			$(this).show();
		});

	//START: Site Redesign 10.1.2 release: Work Request 15595
	if (DISPLAY_LOGGEDIN_VIEW) {
		// Drawing the logged in view
		drawLoggedinState(name);
	}
	//END: Site Redesign 10.1.2 release: Work Request 15595

        // End: Site-redesign changes
	}

	/**
	 * Called by the getUserProfile function to do the work of making
	 * the user profile request.
	 *
	 * @param cb - the name of a callback function to override the default
	 *             if desired.
	 */
	function fetchProfile(cb) {
		var callback = m.name + ".onProfileResponse";
		if (typeof cb == 'function') {
			callback = cb;
		}
		setTimeout(function () {
			$.ajax({
			url: MYANALOG_URI + "/secure/user-profile-ajax.js?callback=" + callback,
			processData: false,
			dataType: "script",
			cache: true
		  });
		}, 500);
	}

	/**
	 * Makes an Ajax request to the url specified as a field in the event object.
	 * Callers may override the handler (onRedirectResponse.handler).
	 */
	function onRedirectResponse(event) {
		var url = event.response;
		// Call getUserProfile if the redirect-to url matches
		if (url.match(/user-profile-ajax/)) {
			getUserProfile();
			//START: Site Redesign 10.1.2 release: Work Request 15595
			var myanalogUrl = MYANALOG_URI + '/index.html';
			window.location=myanalogUrl;
			DISPLAY_LOGGEDIN_VIEW = false;
			//END: Site Redesign 10.1.2 release: Work Request 15595
		} else {
			$.ajax({
			url: url,
			processData: false,
			dataType: "script"
			});
		}
		onRedirectResponse.handler(event);
	}
	// Start: Site-redesign: Implemented this handler
	onRedirectResponse.handler = function (event) {
		var redirectUrl = event.response;
		if (!redirectUrl.match(/ajax-login-form/)) {
		    $("#errorCaller", document).html('');
		    //START: Site Redesign 10.1.2 release: Work Request 15595
		    if (DISPLAY_LOGGEDIN_VIEW) {
			drawLoggedinState(getMyAnalogName());
		    }
		    //END: Site Redesign 10.1.2 release: Work Request 15595
		}
	}

	/**
	 * Sends a request to logout from myAnalog.  Calling pages
	 * can override the logout.pre and logout.post functions
	 * if desired.
	 */
	function logout(event) {
        logout.pre(event, CALLER);
        
		sendLogoutMessage();
		
		logout.post(event);
	}
	logout.pre  = function (event) {
	   // Site-redesign: modified method call
		showMessagePopup(event, MSG_CAT['myanalog.please.wait'], CALLER);
	}
	// Site-redesign: defined this implementation
	logout.post = function (event) {
		if(DISABLE_LOGIN) {
            DISABLE_LOGIN = false;
        }
		registerListenerForEvent(getUserProfile, 'logoutEvent');
	}

	/**
	 * Sends the request to logout to the server.
	 */
	function sendLogoutMessage() {
		$.ajax({
			url: MYANALOG_URI + "/ajax-logout",
			processData: false,
			success: function () {
				$('#savepopup').hide();
				triggerLoginLogout("logout");
			},
			dataType: "script"
		});
	}

	/**
	 * JQuery-style CSS object used in the showMessagePopup function.
	 */
	var dialogCloseStyle = {
		width: '16px',
		height: '16px',
		background: 'url(/baseweb/images/dialog-titlebar-close.gif) no-repeat',
		position: 'absolute',
		top: '6px',
		right: '7px',
		cursor: 'default'
	};

	/**
	 * Displays a localized 'please wait...' message in a 'popup' div.
	 *
	 * @param event - the JavaScript event used to calculate the top left
	 *                offset for the popup 'window'.
	 * @param message - the text to display in the popup 
	 */
	// Start: Site-redesign - modified method signature to add the parameter 'caller'
	// and added corresponding handle in method
	function showMessagePopup(event, message, caller) {
		if (!DISPLAY_POPUP) { return; }

        var pdiv;
        if (caller == "savetomyanalog") {
	        pdiv = $('#savepopup').empty();
			pdiv.prepend('<div><h2>myAnalog</h2></div><div id="dialog-close"></div>');
			$('#dialog-close', pdiv).click(function () { pdiv.hide(); }).css(dialogCloseStyle);
			pdiv.append('<div id="savepopupcontent"></div>');
			$('#savepopupcontent', pdiv).html('<div>' + message + '</div>');
		} else {
            pdiv = $(LOGIN_PARENT).empty();
            pdiv.append('<div class="mega_top"></div><div id="' + LOGIN_PARENT_CONTENT_AREA + '"><div class="div_clear"></div></div><div class="mega_bottom"></div>');
            $('#' + LOGIN_PARENT_CONTENT_AREA, pdiv).html('<div>' + message + '</div>');
		}
        pdiv.show();
	}
	// End: Site-redesign 

	/**
	 * Implementation of the 'Save to myAnalog' request.
	 *
	 * @param type - TODO InfoSys please document
	 * @param sectionName - TODO InfoSys please document
	 * @param scid - TODO InfoSys please document
	 * @param scname - TODO InfoSys please document
	 */
	function saveToMyAnalog(type, sectionName, scid, scname,displayPage) {
       // Start: Site-redesign additions
       // Setting caller to 'savetomyanalog'
        if (CALLER != 'savetomyanalog') {
             initHook({caller:'savetomyanalog', disableProfileFetch:true});
        }
        // Overriding unauthorized response handler to savepopup details
        // onClick of 'Save to myAnalog'
        onUnauthorizedResponse.handler = function (event) {
            $("div#welcome_user").hide(1, function () {
                setWelcomeText();
                $(this).show();
            });
            event.run("#savepopup", "savepopup");
        }
       // End: Site-redesign additions
		var pref = type ? type : 'favorites';
		var id = scid ? scid : 0;
		var section = sectionName ? sectionName : '';
		var scn = scname ? scname : '';
		var url = window.location.pathname;
		var host = window.location.host;
		var protocol = window.location.protocol;
		var pageToDisplay = displayPage ? displayPage : 'others';		
		var startIndex = 0;
		var pipeIndex = document.title.indexOf('|');

		//THIS WILL APPEND QUERYSTRING TO THE URL BEING SAVED IN MYANALOG
		//NEEDED FOR PARAMETRIC SEARCH AND STATIC TOOLS
		var querystring = window.location.search;
		url = url + encodeURIComponent(querystring);
		/* START: Modification for 9.2.1 - SEO */
		/* WR15024: Page heading and title override */
		if (pipeIndex == -1)
			var title = document.title;
		else if (pageToDisplay == 'subcategory')
			var title = document.title.substring(startIndex, pipeIndex-1);
		else if (pageToDisplay == 'category')
			var title = document.title.substring(startIndex, pipeIndex-1);
		else if (pageToDisplay == 'designtools') {
			if (startIndex != -1 && pipeIndex != -1)
				var title = document.title.substring(startIndex, pipeIndex-1);
			else
				var title = document.title;
		}
		else if (pageToDisplay == 'applications') {
			var title = document.title.substring(startIndex, pipeIndex-1);
		}
		else
			var title = document.title;
		/* END: Modification for 9.2.1 - SEO */
		
		title = title.replace(/(^\s*|\s*$)/, "");
		section = encodeURIComponent(section);
		
		$.ajax({
			url: MYANALOG_URI + "/secure/preferences/"+pref+"/ajax-save.html?callback=" + m.name + ".onSaveResponse&type="+pref+"&sectionName="+section+"&url="+url+"&host="+host+"&protocol="+protocol+"&title="+title+"&scid="+id+"&scname="+scn,
			processData: false,
			dataType: "script"
		});
		
	}
	
	/**
	 * Implementation of the 'Save to myAnalog' request.
	 *
	 * @param type - THIS IS FOR IDENTIFYING THE TYPE OF DATA TO BE SAVED. WILL BE 'PRODUCTS' FOR ISC
	 * @param sectionName - PART#
	 * @param appTitle - TITLE OF THE CALLING PAGE. FOR ISC, THIS WILL BE THE OPENER'S TITLE
	 * @param appPath - PATH OF THE CALLING PAGE. FOR ISC, THIS WILL BE THE OPENER'S URL
	 */
	function saveISCToMyAnalog(type, sectionName, appTitle, appPath) {
	
		var pref = type ? type : 'favorites';
		var id = 0;
		var section = sectionName ? sectionName : '';
		var scn = '';
		var url = appPath ? appPath : window.location.pathname;
		var title = appTitle ? appTitle: document.title;
		var host = window.location.host;
		var protocol = window.location.protocol;
		
		title = encodeURIComponent(title);
		section = encodeURIComponent(section);
		
		try
		{
		$.ajax({
			url: MYANALOG_URI + "/secure/preferences/"+pref+"/ajax-save.html?callback=" + m.name + ".onSaveResponse&type="+pref+"&sectionName="+section+"&url="+url+"&host="+host+"&protocol="+protocol+"&title="+title+"&scid="+id+"&scname="+scn,
			processData: false,
			dataType: "script"
		});
		}
		catch(err){}
	}
		
	/**
	 * Delegates to the handler (onSaveResponse.handler) function.
	 * Callback which handles the 'Save to myAnalog' response from the server.
	 * Calling pages should override the onSaveResponse.handler function.
	 */
	function onSaveResponse(event) {
		// If we got here, we must have logged in
		triggerLoginLogout('login');
		// Start: Site-redesign: Resetting the caller to 'main' upon successful
		// completion of "Save to myAnalog" request.
		initHook({caller:'main', disableProfileFetch:true});
		// End: Site-redesign
		onSaveResponse.handler(event);
	}
	onSaveResponse.handler = function (event) {
		if (event.response != 'Notification') {
	        var divs = document.getElementsByTagName('div');
	        var htmlCode;
			for(var i = 0;i < divs.length; i++) {
            	if (divs[i].id == 'savepopup') {
					divs[i].innerHTML= "";
	                htmlCode = '<div style="background: #e6e7e9; font-color: white;"><h2>myAnalog</h2></div>';
	                htmlCode = htmlCode + '<div style="background: white;padding-left: 5px;"><br /><br />'+ msgFormat(MSG_CAT[event.response], [event.value]) +'<br /><br/>';
	                if (event.id != 'Non-Notification') {
	                	/* START: VC myAnalog changes */
	                	var notifyMessageKey = event.metaData == "CircuitNode" ? "savetomyanalog.NotifymeofnewCircuits" : "savetomyanalog.Notifymeofnewproducts";
	                	htmlCode = htmlCode + '<input type="checkbox" id="chkNotify" checked="checked">'+ MSG_CAT[notifyMessageKey] + '</input><br /><br/>';
	                	/* END: VC myAnalog changes*/
					}
	                htmlCode = htmlCode + '<a style="text-decoration:none;" onclick="goToMyAnalog(\''+event.id+'\');" href="' + MYANALOG_URI + '">' + MSG_CAT['savetomyanalog.GoToMyAnalog'] + '&nbsp;<img src="/baseweb/images/bigorangebullet.gif" /></a><br /> <br />';
	                htmlCode = htmlCode + '<div style="background: white; margin-left: 165px;"><input type="button" value="'+ MSG_CAT['savetomyanalog.Close'] +'" onclick="hidePopUp(\''+event.id+'\');" /></div></div>';
	                divs[i].innerHTML= htmlCode;
	                divs[i].style.display = "block";
				}
			}
		}
	}

	/**
	 * Handles the response for the message catalog request.  Triggers the 'messageCatLoaded'
	 * event so that any registered listeners for that event will get a chance to run.
	 *
	 * @see registerMsgCatListener 
	 */
	function onMessageCatResponse(event) {
    	MSG_CAT = event.response;
    	$(document).trigger('messageCatLoaded');
	}

	/**
	 * Build the link to the Registration/Login page.
	 *
	 * @param dynamicReturnUrl indicates whether the registration ReturnURL parameter should
	 *        include the calling page (if true) or default myAnalog home (if false or null).
	 */
	function buildRegistrationLink(dynamicReturnUrl) {
		var locale = obtainLocaleFromPath(location.pathname);
		var returnUrl = dynamicReturnUrl ? location.href : (MYANALOG_URI+"?");
		
		var homePageUrl = location.protocol + "//" + location.host + "/";
		//START OF MODIFICATION FOR REMEDY ISSUE FIX INC0000000107757 
		if (returnUrl.indexOf(homePageUrl) != -1){        // returnUrl == homePageUrl
			returnUrl = homePageUrl + locale +"/index.html?";
		}
		//	END OF MODIFICATION FOR REMEDY ISSUE FIX INC0000000107757 
		return REGISTRATION_URI + '/Registration/login/myAnalogLogin/myAnalogLogin.aspx?ReturnURL=' + returnUrl + '&locale=' + locale;
	}
	
	/**
	 * Triggers a login/logout event depending on the value of the loginOrLogout parameter.
	 *
	 * @param loginOrLogout - indicator of login ('login') or logout ('logout').
	 */
	function triggerLoginLogout (loginOrLogout) {
		$(LOGIN_LOGOUT_ID).trigger('loginLogoutEvent', [loginOrLogout]);
	}

	/**
	 * Event handler for the login/logout event.  Sets up the Login/Logout link accordingly.
	 *
	 * @param event - the JavaScript event (e.g., 'click')
	 *
	 * @param loginOrLogout - data for the event ('login' or 'logout')
	 */
	function loginLogoutEventHandler (event, loginOrLogout) {
		var url = buildRegistrationLink();
        // Start: Site-redesign: changes to handle third display msg type 'Log in as different user'
        var name = getMyAnalogName();
        var text = "";
        // User is known, show the cookied state login form
        if (loginOrLogout == 'logout') {
	        var cookied = name != undefined
	        text = (!cookied) ? MSG_CAT['myanalog.login.label'] : MSG_CAT['myanalog.welcome.differentuser'];    
        }    
        // End: Site-redesign changes
		
		var loggedIn = loginOrLogout == 'login';
		if (loggedIn) {
			url = MYANALOG_URI + '/ajax-logout';
			text = MSG_CAT['myanalog.logout.label'];
		}
		// Get rid of any previous 'click' event handlers for this link to avoid
		// repeated invocations of handlers.
		$(LOGIN_LOGOUT_ID).unbind("click");

		// Now reestablish the handler for the login/logout link.
		$(LOGIN_LOGOUT_ID).attr("href", url).text(text).one("click", (function (event) {
			// Asserting complete control over the onclick event.
			event.preventDefault();

			// If clicked and we were in the 'logged in' state, we must be logging out.
			if (loggedIn) {
				logout(event);
				return false;
			}

			// Not in the 'logged in' state, so handle the two login cases:
			// See if the user is known by trying to get the user's name
            // Site-redesign: modified check from earlier CALLER == 'main'
            if (name !== undefined && CALLER != "main") { // 1. User is known, show the login form or popup
				showMessagePopup(event, MSG_CAT['myanalog.please.wait'], CALLER);
				fetchProfile();
			} else { // 2. User is not known, so transition to the registration/login page
				location.href = event.target.href;
			}
			return false;
		}));
	}

	/**
	 * Reads the myAnalog cookie and tries to determine the user's name and username.
	 */
	function updateNamesFromCookie() {
		var cookie = $.cookie(MYANALOG_COOKIE_NAME);
		if (cookie) {
			var values = cookie.split('|');
			//MODIFICATION FOR INC000000108959
			//MYANALOG_NAME = values[0];
			MYANALOG_FIRST_NAME = decodeURIComponent(decodeURIComponent(values[0]));
			MYANALOG_LAST_NAME = decodeURIComponent(decodeURIComponent(values[1]));
			MYANALOG_USERNAME = values[2];
		}
	}

	/**
	 * Property accessor for the user's name.
	 */
	function getMyAnalogName() {
		updateNamesFromCookie();
		// START OF IS WORK REQUEST 13279
		var locale = obtainLocaleFromPath(location.pathname);
		var name = MYANALOG_FIRST_NAME;
		if (locale == "jp"){
			
			name = MYANALOG_LAST_NAME;
		}
		// END OF IS WORK REQUEST 13279
		return name;
	}

	/**
	 * Property accessor for the user's username.
	 */
	function getMyAnalogUsername() {
		updateNamesFromCookie();
		return MYANALOG_USERNAME;
	}

	/**
	 * Determine the locale string from the url path.
	 */
	function obtainLocaleFromPath(path) {
		var locale = 'en';
		//START: WR13877 - LOCAL RESOLVER CHANGE FOR PROCESSOR PAGES (/embedded-processing-dsp/processors/jp/index.html)
		//var localeMatch = path.match(/^\/(en|ru|jp|zh|tw)\/?.*/);
		var localeMatch = path.match(/^\/([-_a-zA-Z0-9/]*?)(en|ru|jp|zh|tw)\/?.*/);
		
		if (localeMatch != null) {
			//locale = localeMatch[1];
			locale = localeMatch[2];
			//END: WR13877 - LOCAL RESOLVER CHANGE FOR PROCESSOR PAGES (/embedded-processing-dsp/processors/jp/index.html)
		}
		else{
			 
			 if(path.indexOf("=ja")> 0 ){
			  locale = "jp";
			 }
			 else if (path.indexOf("=jp")> 0) {
			  locale = "jp";
			 }
			 else if (path.indexOf("=zh")> 0) {
			  locale = "zh";
			 }
			 else if (path.indexOf("=ru")> 0) {
			  locale = "ru";
			 }
		}
		return locale;
	}

	/**
	 * Callback to 'handle' responses to requests where the response is assumed to be Ok,
	 * and no response data needs to be processed.  This is just a notification that the
	 * request was successfully received.
	 */
	function onResponse(event) { /* intentionally empty */ }

	/**
	 * Triggers a 'logoutEvent' when a logout response is received.
	 */
	// Start: Site-redesign: modified this method 
	function onLogout(event) {        
        // Resetting the CALLER back to 'main' upon logout.         
        initHook({caller:'main', disableProfileFetch:true});
        /** 
         * Upon logout, resetting the onUnauthorizedResponse handler to
         * call the response's "run()" method with the myAnalog header container
         * parameters - LOGIN_PARENT. This will ensure that the view in the header
         * area is correctly redrawn.
         */
        onUnauthorizedResponse.handler = function (event) {
            $("div#welcome_user").hide(1, function () {
                setWelcomeText();
                $(this).show();
            });
            event.run(LOGIN_PARENT, LOGIN_PARENT_CONTENT_AREA);
        }
		$(document).trigger('logoutEvent');
	}
	// End: Site-redesign 
    
	/**
	 * Initialize certain properties of this module.	This function should
	 * be called in the using page's onload or $(document).ready() function.
	 *
	 * @param opts currently processes the following attributes:
     *     caller         - the name of the page that is using this module (e.g., "main").
	 *     disableLogin - true if the initial fetch of myAnalog user profile
	 *				should have login disabled.
	 *     displayPopup = true if the module should popup a message dialog
	 *				for certain events.
	 *     loginLogoutId - the element ID of the login/Logout link
	 */
	function initHook(opts) {
		if (opts !== undefined) {
			if ("caller" in opts && opts.caller !== undefined) {
				CALLER = opts.caller;
			}
			
			if ("disableLogin" in opts && opts.disableLogin !== undefined) {
				DISABLE_LOGIN = opts.disableLogin;
			}
			
			if ("displayPopup" in opts && opts.displayPopup !== undefined) {
				DISPLAY_POPUP = opts.displayPopup;
			}
			
			if ("loginLogoutId" in opts && opts.loginLogoutId !== undefined) {
				LOGIN_LOGOUT_ID = opts.loginLogoutId;
			}
			// Start: Site-redesign added
			if ("disableProfileFetch" in opts && opts.disableProfileFetch !== undefined) {
                DISABLE_PROFILE_FETCH = opts.disableProfileFetch;
            }
            // End: Site-redesign added
		}
			
		registerMsgCatListener(initModule);
			
		// Try SSO login to set initial state of page
		// Site-redesign: added check
		if (!DISABLE_PROFILE_FETCH) {
            registerMsgCatListener(fetchProfile);
		}
	}

	/**
	 * Initialization routine to set up the default welcome text.  Requires that the
	 * message catalog object be initialized.  Accordingly, this function should
	 * be registered as a listener for the 'messageCatLoaded' event, and not
	 * called directly.
	 *
	 * @see registerMsgCatListener
	 * @see MSG_CAT
	 */
     // Site-redesign: modified this method for new welcome text
	function initDefaultWelcomeText () {
        DEFAULT_WELCOME = MSG_CAT['myanalog.default.welcome'];
		$(LOGIN_LOGOUT_ID).bind("loginLogoutEvent", loginLogoutEventHandler).trigger("loginLogoutEvent", ["logout"]);
	}

	/**
	 * Sets the welcome text according to whether the user is known or not.  In case not,
	 * the default text shall be used.  Relies on the message catalog having been loaded.<b> 
	 * Consequently, this routine should be called in the context of a listener for the
	 * 'messagCatLoaded' event particularly when used as part of this module's initialization.<b> 
	 *
	 * @see registerMsgCatListener
	 * @see initDefaultWelcomeText
	 * @see MSG_CAT
	 */
	function setWelcomeText() {
		var name = getMyAnalogName();
		if (name) {
			var regLoginUrl = buildRegistrationLink();
			var msgCat = MSG_CAT;
        // Start: Site-redesign modified
            var welcomeNote = msgFormat(msgCat['myanalog.welcome'], [name]);
            $("div#welcome_user").hide(1, function () {
                $("span#user").html(welcomeNote);
				$(this).show();
			});
		} else {
            $("span.user").html(DEFAULT_WELCOME);
		}
        // End: Site-redesign modified
	}

	/** Indicates if the initModule function has been run yet or not. */
	var MODULE_INITED = false;
	/**
	 * Initializes this module.  It will be scheduled to run after the message catalog
	 * has been loaded (see the event handler for the document.ready (page load) event.
	 *
	 * @see registerMsgCatListener
	 * @see MSG_CAT
	 */
	function initModule() {
		if (MODULE_INITED) return;
		MODULE_INITED = true;

		initDefaultWelcomeText();
		setWelcomeText();
	}

	/**
	 * Registers event listener(s) for the 'messageCatLoaded' event iff the MSG_CAT
	 * object has not yet been defined.  Otherwise, calls the listener immediately.
	 * 
	 * @see MSG_CAT
	 */
	function registerMsgCatListener(listener) {
		if (MSG_CAT === undefined) {
			$(document).bind('messageCatLoaded', listener);
		} else {
			listener();
		}
	}

	/**
	 * Binds a function to be called upon the occurrence of the specified event.
	 */
	function registerListenerForEvent(listener, event) {
		$(document).bind(event, listener);
	}

	// Page-load initializations here.  This code will execute after the calling
	// document's DOM has been initialized.
	$(document).ready(function () {
		var locale = obtainLocaleFromPath(location.pathname);
		//var locale = obtainLocaleFromPath(location.href);

		// Find the hidden value for myAnalogUri on the calling page.
		var myAnalogUri = $("#myAnalogUri").text();
		MYANALOG_URI = myAnalogUri ? myAnalogUri : MYANALOG_URI;
		MYANALOG_URI = MYANALOG_URI + '/' + locale;

		// Find the hidden value for registrationUri on the calling page.
		var registrationUri = $("#registrationUri").text();
		REGISTRATION_URI = registrationUri ? registrationUri : REGISTRATION_URI;

		// Find the hidden value for myAnalogCookieName on the calling page.
		var cookieName = $("#myAnalogCookieName").text();
		MYANALOG_COOKIE_NAME = cookieName ? cookieName : MYANALOG_COOKIE_NAME;

		// Get the message catalog object
		$.ajax({
			url: MYANALOG_URI + "/message-catalog.js?callback=" + m.name + ".onMessageCatResponse",
			processData: false,
			async: false,
			dataType: "script",
			cache: true
		});

		// Register the initModule() function to be called once the message catalog has been retrieved.
		registerMsgCatListener(initModule);

		// Provide a sensible default for the doSaveToMyAnalog function in case the calling page has not defined it.
		if (!window.doSaveToMyAnalog) {
			window.doSaveToMyAnalog = function (type, sectionName, scid, scname, displayPage) {
				m.saveToMyAnalog(type, sectionName, scid, scname, displayPage);
			};
		}

		// Provide a sensible default for the hidePopUp function in case the calling page has not defined it.
		if (!window.hidePopUp) {
			window.hidePopUp = function (notificationVal) {
				$('#savepopup').hide();
				if (notificationVal != 'Non-Notification') {
					var notifyElement = $('#chkNotify');
					if (!notifyElement.checked) {
						saveToMyAnalog('notifications',notificationVal,'0','','others');
					}
				}
			};
		}
	});

	// This section exports names in the namespace specified by the argument to the 'm' parameter.
	// So, if the argument to this function was 'Foo', then the calling page would know
	// m.logout as Foo.logout.
	//
	// The argument to this function should be an object with a 'name' property that is set
	// to the same value as the name of the variable holding a reference to the object.
	// E.g., var Foo = { name:"Foo" };
	//
	m.getDefaultWelcome              = function () { return DEFAULT_WELCOME; };
	m.onUnauthorizedResponse         = onUnauthorizedResponse;
	m.onUnauthorizedResponse.handler = onUnauthorizedResponse.handler;
	m.getUserProfile                 = getUserProfile;
	m.onProfileResponse              = onProfileResponse;
	m.onProfileResponse.handler      = onProfileResponse.handler;
	m.onRedirectResponse             = onRedirectResponse;
	m.onRedirectResponse.handler     = onRedirectResponse.handler;
	m.saveToMyAnalog                 = saveToMyAnalog;
	m.saveISCToMyAnalog              = saveISCToMyAnalog;
	m.onSaveResponse                 = onSaveResponse;
	m.onSaveResponse.handler         = onSaveResponse.handler;
	m.logout                         = logout;
	m.getMyAnalogUri                 = function () { return MYANALOG_URI; };
	m.getMyAnalogName                = getMyAnalogName;
	m.getMyAnalogUsername            = getMyAnalogUsername;
	m.obtainLocaleFromPath           = obtainLocaleFromPath;
	m.onResponse                     = onResponse;
	m.registrationPageLink           = buildRegistrationLink;
	m.initHook                       = initHook;
	m.usePopupDisplay                = function () { return DISPLAY_POPUP; };
	m.enableLogin                    = function () { DISABLE_LOGIN = false; };
	m.disableLogin                   = function () { DISABLE_LOGIN = true; };
	m.msgCat                         = function () { return MSG_CAT; };
	m.onMessageCatResponse           = onMessageCatResponse;
	m.registerMsgCatListener         = registerMsgCatListener;
	m.setWelcomeText                 = setWelcomeText;
	m.msgFormat                      = msgFormat;
	m.registerListenerForEvent       = registerListenerForEvent;
	m.onLogout                       = onLogout;

}) (MyAnalogRemote);
