( function(){
	function isBoolean(a){
		return a === true || a === false;
	}
	
	if (!Array.isArray){
		/**
		 * check whether a object is array
		 * */
		Array.isArray = function(a) {
			return typeof(a) === "array";
		};
	}
	
	if (!Function.bind){
		/**
		 * add Function.bind of ES5
		 * */
		Function.prototype.bind = function(scope) {
			if (arguments.length < 2 && scope === void 0){
				return this;
			}
			var fn = this,
				argv = arguments;
			return function() {
				var args = [], 
					i;
				for (i = 1; i < argv.length; i++){
					args.push(argv[i]);
				}
				for (i = 0; i < arguments.length; i++){
					args.push(arguments[i]);
				}
				return fn.apply(scope, args);
			};
		};
	}
	
	if (![].map) {
		/**
		 * add the array functions added in ES5
		 */
		$.extend(Array.prototype, {
		    indexOf: function(item, index) {
                var n = this.length,
                    i = ~~index;
                if (i < 0){
                    i += n;
                }
                for (; i < n; i++){
                    if (this[i] === item){
                        return i;
                    }
                }
                return -1;
            },
			lastIndexOf: function(item, index){
				var n = this.length,
					i = index == null ? n -1 : index;
				if (i < 0){
					i = Math.max(0, n + i);
				}
				for (; i >= 0; i--){
					if (this[i] === item){
						return i;
					}
				}
				return -1;
			},
			forEach: function(f, scope) {
				for (var i = 0, n = this.length; i < n; i++){
					(i in this) && f.call(scope, this[i], i, this);
				}
			},
			filter: function(f, scope) {
				for (var r = [], i = 0, j = 0, n = this.length; i < n; i++){
					if ((i in this) && f.call(scope, this[i], i, this)){
						r[j++] = this[i];
					}
				}
				return r;
			},
			map: function(f, scope) {
				for (var r = [], i = 0, n = this.length; i < n; i++){
					r[i] = ((i in this) && f.call(scope, this[i], i, this));
				}
				return r;
			},
			some: function(f, scope) {
				for (var i = 0, n = this.length; i < n; i++){
					if ((i in this) && f.call(scope, this[i], i, this)){
						return true;
					};
				}
				return false;
			},
			every: function(f, scope) {
				for (var i = 0, n = this.length; i < n; i++){
					if (!((i in this) && f.call(scope, this[i], i, this))){
						return false;
					};
				}
				return true;
			}
		});
	}
	
	//JQuery.fn.remove function may let IE7 crash
	var removeNodeIE = (function (){
		var d;
		return function(e){
			if (e){
				var d = d || document.createElement("div");
				d.appendChild(e);
				d.innerHTML = "";	
			}
		};
	})();
	
	if (window.attachEvent){
		$.fn.remove = function(selector, keepData){
			for (var i = 0, elem; (elem = this[i]) != null; i++){
				if (!selector || $.filter(selector, [elem]).length) {
					removeNodeIE(elem);
				}
			}
		};
	}

	/**
	 * get a simple json string by obj 
	 * */
	var getJson = function(obj, buffer){
		buffer = buffer || new StringBuffer();
		buffer.append("{");
		for (p in obj){
			if (!obj.hasOwnProperty(p) || typeof obj[p] === "function"){
				continue;
			}
			buffer.append(p).append(":").append(obj[p]).append(",");
		}
		buffer.append("},");
		return buffer;
	};
	
	window.getJson = getJson;
	
	/**
	 * generate a json string by arguments, cache function will use it as cache key 
	 * */
	var computerKey = function(){
		var buffer = new StringBuffer();
		buffer.append(arguments.length);
		Array.prototype.forEach.call(arguments, function(x) { return getJson(x, buffer); });
		
		return buffer.toString();
	};
	
	/** implements aop function like java aop framework 
	 * function will return a deferred object if async is true
	 * */
	function aop(f, before, after, async){
		return function(){
			async = async || false;
			//call before function, 
			//before function can set canContinue of returnValue to control original function 
			var b = before && before.apply(this, arguments);
			if (b && !(b.canContinue)) {
				if (async){
					var dtd = $.Deferred();
					dtd.resolve(b.value);
					return dtd;
				}
				else{
					return b.value;
				}
			}
			
			var returnValue = f.apply(this, arguments);
			
			if (after){
				if (async){
					var self = this;
					var args = Array.prototype.map.call(arguments, function(x) { return x; });
					
					returnValue.done( function() {
						after.call(self, { args: args, doneArgs: arguments} );
					});
				}
				else{
					after.call(this, { args: arguments, doneArgs: returnValue} );
				}
			}
			return returnValue;
		};
	}

	/**
	 * cache aop function 
	 * */
	function cache(f, async) {
		var cacheData = {};
		var cache = {
			before: function(key) {
				var key = computerKey.apply(null, arguments);
				if (key in cacheData){
					return { canContinue: false, value: cacheData[key] };
				}
			},
			after: function(){
				var returnValue = arguments[0].doneArgs[0] || arguments[0].doneArgs;
				var key = computerKey.apply(null, arguments[0].args);
				cacheData[key] = returnValue;
			}
		};
		return aop(f, cache.before, cache.after, async);
	}
	
	/**
	 * the function that wrap an async ajax request with cache 
	 * */
	var ajaxAsyncCache = cache( function(request) { 
		return $.ajax(request); 
	}, true);

	/**
	 * the function that wrap an sync ajax request with cache 
	 * */
	var ajaxSyncCache = cache( function(request) { 
		return $.ajax(request); 
	}, false);

	/**
	 * common ajax request function 
	 * */
	window.ajaxCall = function(request, cacheEnable){
		var ajax,
			dtd = $.Deferred(),
			cacheEnable = cacheEnable || false;
		
		if (cacheEnable){
			var async = request.async ||  true;
			ajax = async ? ajaxAsyncCache : ajaxSyncCache;
		}
		else{
			ajax = $.ajax;
		}
		
		var url = request.url,
			cnumber = getCookie("cnumber");
		//add random query string to avoid IE cache and add cnumber to prevent CRFS hacking
		url += (url.indexOf("?") > 0? "&" : "?") + "cnumber=" + cnumber;
		if (!cacheEnable) {
			url += "&rand=" + (new Date()).getTime();
		}

		request.url = url;
		//trackLinkUrl(request.url);
		var disable401 = request.disable401;
		
		ajax(request)
		.done( function(data) {
			if (data.meta && data.meta.code !== "200") {
				//about meta.code, 500: server side error, 600: server side validation failed, other code: other errors
				console.log("failed in " + url);
				var xhr = arguments[2];
				xhr.status = data.meta.code;
				xhr.errorId = data.meta.errorId; 
				dtd.reject(xhr, data.meta.errorType, data.meta.errorMessage);
			} else if (url.indexOf(app.EPRESTAPI_CONTEXT_ROOT) >= 0){
				if (typeof(data) == "object" && !data.meta){
					app.user.logout();
				} else if (typeof(data) == "string" && isLoginPage(data)){
					app.user.logout();
				} else{
					dtd.resolve.apply(null, arguments);
				}
			} else if (url.indexOf(".html") >= 0 && isLoginPage(data)){
				app.user.logout();
			} else {
				dtd.resolve.apply(null, arguments);
			}
		})
		.fail( function() {
			console.log("failed in " + url);
			if (isLoginPage( arguments[0].responseText)){
				app.user.logout();
			} else {
				dtd.reject.apply(null, arguments);
			}
		});
		return dtd.promise().fail( function(){
			//var args = ["ajaxError"].concat(arguments);
			var args = Array.prototype.map.call(arguments, function(x){return x;});
			args = ["ajaxError"].concat(args);
			app.trigger.apply(app, args);
		}).done( function() {
			
		});
	};
	
	window.cache = cache;
	
	var isLoginPage = function(){
		var responseText = arguments[0];
		if (responseText.indexOf("/IDM/js/NNLogin.js") >= 0 && responseText.indexOf("/IDM/UI/Login") >= 0){
			return true;
		} else {
			return false;
		}
	}
	
	/* use Nomura Now track function to track all restapi request*/
	var trackLinkUrl = function(url){
		if (url.indexOf(app.EPRESTAPI_CONTEXT_ROOT) >= 0){
			try{
				window.NN_trackLink && NN_trackLink(url.slice(app.EPRESTAPI_CONTEXT_ROOT.length));
			}
			catch(e){
				if (console && console.log) {
					console.log(e);
				}
			}
		}
		
	};
	
	var trackAction = function(actionName) {
		try{
			if (app.user.role.checkRole("hasRole('WMD_Clients')")){
				window.NN_trackLink && NN_trackLink(actionName);
			}
		}
		catch(e){
			if (console && console.log) {
				console.log(e);
			}
		}
	};
	
	window.trackAction = trackAction;
	
	window.showSaveResult = function(){
		try{
			if (arguments.length > 0){
				if ($.isArray(arguments[0])){
					var success = 0, fail = 0;
					for(var i = 0; i < arguments.length; i++){
						if (isBoolean(arguments[i][0].data.data)){
							if (arguments[i][0].data.data){
								success += 1;
							}
							else{
								fail += 1;
							}
						}
					}
					if (fail > 0){
						dialog
						.set({autoHideTime: 2000})
						.show(lang.messages["msgSaveFailed"] || "Save failed");
					}
					else{
						dialog
						.set({autoHideTime: 2000})
						.show(lang.messages["msgSaveSuccessed"] || "Save successful");
					}
				} else {
					var result = arguments[0].data.data;
					if (isBoolean(result)){
						dialog
						.set({autoHideTime: 2000})
						.show( result ? 
								(lang.messages["msgSaveSuccessed"] || "Save successful") :
								(lang.messages["msgSaveFailed"] || "Save failed"));
					}
				}
			}
		}
		catch(e){
			console.log(e);
		}
	};
	
	window.formatMessage = function(){
		var msg = arguments[0];
		for ( var i = 1; i < arguments.length; i++){
			msg = msg.replace("{" + (i - 1) + "}", arguments[i]);
		}
		return msg;
	};
	
})();

/**
 * the function that dynamic load javascript 
 * */
(function () {
	function loadScriptByAjax(urls, callback) {
		var createScriptElement = function(data) {
			var head = $("head")[0];
			var s = document.createElement("script");
			s.type = "text/javascript";
			s.text = data[0];
			head.appendChild(s);
		};
		var ajaxs = urls.map( function (x) { return ajaxCall({ url:x, dateType:"text" }, true); });
		return $.when.apply(null, ajaxs)
		.done( function() {
			for(var i = 0; i < arguments.length; i++){
				createScriptElement(arguments[i]);
			}
			if (callback){
				callback();
			}
		});
	}

	function loadScriptBySrc(urls, callback) {
        var dtd = $.Deferred();
		var addScript = function() {
			if (urls.length >= 1) {
				var s = document.createElement("script");
				s.type = "text/javascript";
				s.onload = s.onerror = s.onreadystatechange = function () {
					if (!s.readyState || s.readyState === "loaded" || s.readyState === "complete"){
						s.onload = s.onerror = s.onreadystatechange = null;
						$("head")[0].removeChild(s);
						urls.shift();
						addScript();
					}
				};
				s.src = urls[0] + (urls[0].indexOf("?") > 0? "&" : "?") + "version=|||xxx|||";
				$("head")[0].appendChild(s);
			}
			else{
				if (callback){
					callback();
				}
				dtd.resolve();
			}
            return dtd;
		};
		return addScript();
	}

	var debug = true;
	window.loadScript = debug? loadScriptBySrc : loadScriptByAjax;
})();

/**
 * The dialog class which can use to show message in a dialog box.
 */
(function() {
	window.dialog = {
		autoHideTime : 0,
		init: function (){
			var self = this;
			$("#closeBtn").live("click", function(){
				self.close("close");
			});				
		},
		/** show a dialog
		 * @arguments
		 * 		first argument: the message be show
		 * 		other arguments: customized buttons (max count is 3), can accept two type:
		 * 			1. string - this argument will be button text, default action is close the dialog
		 * 			2. object - should include two property:
		 * 					text - button text
		 * 					action - action function when button be clicked
		 * @returns
		 * 		return a deferred object, it will be resolved when call close() method
		 * @examples
		 * 		//show a dialog with a Ok button
		 * 		dialog.show("Please contact us", "Ok");  
		 * 
		 * 		//show a dialog with a Ok button, alert "Ok" after dialog be closed
		 * 		dialog.show("Please contact us", "Ok").done( function(btnBtn) {
		 * 			alert(btnBtn);
		 * 		});  
		 * 
		 * 		//show a dialog with Yes and Ok buttons, 
		 * 		//programmer can add customized logic after user click "Yes" button 
		 * 		dialog.show("Are you sure", "Yes", "No").done( function(btnBtn) {
		 * 			if (btnBtn === "Yes") {
		 * 				//....
		 * 			}
		 * 		}); 
		 *  
		 * 		//show a dialog with Yes, Other and Ok buttons, 
		 * 		//note that the action function of "Other" button is customized 
		 * 		//so that dialog be unable to auto close when click "Other" button, 
		 * 		//it need programmer to close the dialog 
		 * 		dialog.show("Are you sure", "Yes", {
		 * 				text: "Other",
		 * 				action: function() {alert("Other");}
		 * 			}, "No")
		 * 		.done( function(btnBtn) {
		 * 			if (btnBtn === "Yes") {
		 * 				//....
		 * 			}
		 * 		});  
		 */
		show: function (){
			var self = this,
				dtd = $.Deferred(),
				div = $("#popupDiv"),
				btn,
				btnCSSs = {};
			for (var i = 1; i <= 3; i++){
				btnCSSs["#button" + i] = {
						style: $("#button" + i).attr("style"),
						css: $("#button" + i).attr("class")
				};
				//btnCSSs["#button" + i].style = $("#button" + i).attr("style");
				//btnCSSs["#button" + i].css = $("#button" + i).attr("class");
			}
			
			if(!this.arg || !this.arg.top) {
				//when the arg.top(the setting value) is null, popup set in center
				var popupHeight = (this.arg && this.arg.height && this.arg.height.substring(0, this.arg.height.length - 2)) || div.height();
				var top = ($(window).height() - popupHeight) / 2 + "px";
				console.log("top" + top);
				div.css({"top" : top});
			}
			if(!this.arg || !this.arg.left) {
				//when the arg.left(the setting value) is null, popup set in middle
				var popupWidth = (this.arg && this.arg.width && this.arg.width.substring(0, this.arg.width.length - 2)) || div.width();
				var left = ($(window).width() - popupWidth) / 2 + "px";
				console.log("left" + left);
				div.css({"left" : left});
			}

			var msg = arguments[0] || "<p style='padding:15px;'></p>";
			$("#alertMsgContainer").html(msg);
			if (!this.disableLanguage){
				lang.updateUIMessages("alertMsgContainer");
			}
			
			$("#popupDiv").show();
			$("#popupDivBackground").show();
			function getCloseFunction(btnAttr){
				return function(){
					self.close(btnAttr.text || btnAttr);
				};
			};
			var btnCount = arguments.length - 1;
			for (var i = 1; i <= 3; i++){
				btn = $("#button" + i);
				if (i <= 3 - btnCount) {
					btn.hide();
				}
				else{
					var index = i - (3 - btnCount),
						btnAttr = arguments[index],
						btnText = btnAttr.text || btnAttr,
						langText = (window.lang && lang.messages && lang.messages["btn" + btnText]) || btnText;
					btnAttr.style && btn.attr("style", btnAttr.style);
					btnAttr.css && btn.addClass(btnAttr.css);
					//btn.text(btnText);
					var textHtml = "<span>" + btnText + "</span>";
					btn.html("").append(textHtml);
					btn.die().live("click", btnAttr.action || getCloseFunction(btnAttr)).show();
				}
			}
			
			this.close = function(btnName){
				$("#popupDiv").hide();
				$("#popupDivBackground").hide();
				//reagain init css
				$("#testHeader h1").html("Nomura Now");
				$("#popupContentArea").removeAttr("style");
				$("#popupDiv").css({"top" : "262px", "left" : "270.5px", "width" : "500px"});
				this.autoHideTime = 0;
				for (btnId in btnCSSs){
					btnCSSs[btnId].css && $(btnId).attr("class", btnCSSs[btnId].css);
					btnCSSs[btnId].style && $(btnId).attr("style", btnCSSs[btnId].style);
				}
				dtd && dtd.resolve && dtd.resolve(btnName);
			};
			var self = this;
			if (this.autoHideTime > 0){
				setTimeout( function () {self.close(self.autoHideAction);}, self.autoHideTime);
			}
			return dtd.promise();
		},
		/* set the popup css and title */
		set : function(arg) {
			this.arg = arg;
			if (arg.header && arg.header.length > 0) $("#testHeader h1").html(arg.header);
			if (arg.width && arg.width.length > 0) {
				var width = arg.width.substring(0, arg.width.length - 2) - 20 + "px";
				console.log("width = " + width);
				$("#popupDiv").css({"width" : arg.width});
				$("#popupContentArea").css({"width" : width});
			}
			//if (arg.height && arg.height.length > 0) $("#popupContentArea").css({"height" : arg.height});
			if (arg.top && arg.top.length > 0) {
				$("#popupDiv").css({"top" : arg.top});
			}
			if (arg.left && arg.left.length > 0) {
				$("#popupDiv").css({"left" : arg.left});
			}
			if (arg.autoHideTime && arg.autoHideTime > 0) this.autoHideTime = arg.autoHideTime;
			if (arg.autoHideAction) this.autoHideAction = arg.autoHideAction;
			if (arg.disableLanguage) this.disableLanguage = arg.disableLanguage;
			return this;
		},
		/**
		 * this function is used to generate a argument object when call show method
		 * @param text
		 * @param action
		 * @returns argument object be used in show method
		 */
		getButton: function(text, action) {
			var self = this;
			return {
				text: (window.lang && lang.messages && lang.messages["btn" + text]) || text,
				action: function(){
					if (action) {
						action();
					}
					else{
						self.close(text);
					}
				}
			}
		}
	};
	dialog.init();
})();


/**
 * the StringBuffer class 
 * */
function StringBuffer(){
	var buffer = [];
	var len = 0;
	this.append = function(){
		for (var i = 0; i < arguments.length; i++){
			buffer[len++] = arguments[i];
		}
		return this;
	};
	this.toString = function(){
		return buffer.join("");
	};
}

function getCookie(cookieName){
	var value = document.cookie;
	var start = value.indexOf(" " + cookieName + "=");
	if(start == -1){
    	start = value.indexOf(cookieName + "=");
    }

    if(start == -1){
    	value = null;          
    } else {
    	start = value.indexOf("=", start) + 1;
    	var end = value.indexOf(";", start);
    	if(end == -1){
        	end = value.length;
        }
        value = unescape(value.substring(start, end));
    }
    return value;
}

function setCookie(cookieName, value, exdays, domain){
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var value = escape(value) + (exdays == null? "": "; expires=" + exdate.toUTCString());
	var cookieDomain = "" ;
	if (cookieName != app.LANGUAGE_COOKIE_NAME){
	    cookieDomain = domain ? "domain=" + domain :"";	
	}
	document.cookie = cookieName + "=" + value + ";" + cookieDomain +"; path=/";
	
}

/**
 * generate html that show page no list and prev, next link  
 * */
function genPaginationFooter(pagination, callback){
    if(pagination == null){
        return "";
    }
    var totalCount = parseInt(pagination.totalCount);
    var currentPage = parseInt(pagination.page);
    var recordsPerPage = parseInt(pagination.recordsPerPage);
    var pageCount = parseInt((totalCount - 1)/recordsPerPage + 1);
    var begin = 1,end = 5;
    if(totalCount == 0 || pageCount <= 1 ){
        return "";
    }
    if(currentPage <= 3){
        begin = 1;
    }else if(pageCount - currentPage <= 2 ){
        begin = pageCount - 4;
    }else{
        begin = currentPage - 2;
    }
    if(begin < 1){
        begin = 1;
    }
    if(pageCount > begin + 4){
        end = begin + 4;
    }else{
        end = pageCount;
    }
    /*
    var htmlBuffer = new StringBuffer();
    if(currentPage == 1){
    	htmlBuffer.append("<a page>prev</a>");
    }else{
    	htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", currentPage - 1, ");'>prev</a>");
    }
    for (var i = begin; i <= end; i++){
        if(i == currentPage){
        	htmlBuffer.append("<a page href='javascript:void(0);' class='current'>");
        }else{
        	htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", i, ");'>");
        }
        htmlBuffer.append(i);
        htmlBuffer.append("</a>");
    }
    if(currentPage == pageCount){
    	htmlBuffer.append("<a page>next</a>");
    }else{
    	htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", currentPage + 1, ");'>next</a>");
    }
    return htmlBuffer.toString();
    */
    
    /*=======new test==========================*/
    var htmlBuffer = new StringBuffer();
    htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", 1, ");'>");
    htmlBuffer.append("<<");
    htmlBuffer.append("</a>");
    
    if(currentPage == 1){
        htmlBuffer.append("<a page> < </a>");
    }else{
        htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", currentPage - 1, ");'> < </a>");
    }    
      
    for (var i = begin; i <= end; i++){
        if(i == currentPage){
            htmlBuffer.append("<a page href='javascript:void(0);' class='current'>");
        }else{
            htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", i, ");'>");
        }
        htmlBuffer.append(i);
        htmlBuffer.append("</a>");
    }
    
    if(currentPage == pageCount){
        htmlBuffer.append("<a page> > </a>");
    }else{
        htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", currentPage + 1, ");'> > </a>");
    }
    
    htmlBuffer.append("<a page href='javascript:void(0);' onclick='", callback, "(", pageCount, ");'>");
    htmlBuffer.append(">>");
    htmlBuffer.append("</a>");
    
    return htmlBuffer.toString();
    /*=======new test end======================*/
}

/**
 * get a array includes all property names in obj  
 * */
var getKeyArray = function(obj){
	var array = [];
	for(var o in obj){
		if (obj.hasOwnProperty(o)){
			array.push(o);
		}
	}
	return array;
};

/**
 * input 200000 or "200000"
 * after format
 * result 200,000.00
 * if isRemove = true
 * result 200,000
 * */
var formatMoney = function(money,isRemove){
	if(money == null) {
		return "";
	}
	return money;// added by Ho( server side will do the formatting) 
	if(money == null) {
		return "";
	}
	money = money.toString();
	var moneyPettern = /^\-{0,1}\d+(\.*\d+){0,1}$/;
	if(!moneyPettern.test(money)){
		return "error";
	}
	var isNegative = false;
	if(money.charAt(0) == "-"){
		isNegative = true;
		money = money.replace(/^\-(.*)$/,"$1");
	}
	//if money = 1000   moneyStr = 100.
	var moneyStr = money.toString().replace(/^(\d*)$/,"$1."); 
	moneyStr = (moneyStr+"00").replace(/(\d*\.\d\d)\d*/,"$1");
	moneyStr = moneyStr.replace(".",",");
	var re = /(\d)(\d{3},)/;
	while(re.test(moneyStr)){
		moneyStr = moneyStr.replace(re,"$1,$2");
	}
	moneyStr = moneyStr.replace(/,(\d\d)$/,".$1");
	if(isNegative){
		moneyStr = "-"+moneyStr;
	}
	if(isRemove){
		moneyStr = moneyStr.substring(0,moneyStr.indexOf("."));
	}
	return moneyStr;
	
};

/**
 * add console.log function for IE
 * */
var alertFallback = false;
if (typeof console === "undefined" || typeof console.log === "undefined") {
	console = {};
	if (alertFallback) {
		console.log = function(msg) {
           alert(msg);
		};
	} else {
		console.log = function() {};
	}
}
/**
 * input num:0.555555555 precision:4 return: 0.5556
 * */
formatRound = function(num, precision){
    var param = 1;
    for(var i = 0; i < precision; i++){
        param = param * 10;
    }
    return Math.round(num * param)/param;
};

getNetAssetValue = function(bpkey, portfolioNo, count){
    var pbpkey = bpkey,
    	url;
    if(!pbpkey){
        pbpkey = app.selectBpKey;
    }
    if(!portfolioNo) {
    	url = "portfolio/highLevelSummary/" + pbpkey + "?asOfDate=" + app.selectDateValue;
    } else {
    	url = "portfolio/netAssetValue/" 
    		+ pbpkey + "?asOfDate=" + app.selectDateValue + "&portfolioNo=" + portfolioNo;
    }
    return ajaxCall({ 
    	url: app.EPRESTAPI_CONTEXT_ROOT + url, 
    	dataType: "json"
    }, false).done( function(data){
    	if (count!==null && count!== undefined){
			var ccy = data.data.result.ccy,
	        	value = data.data.result.netAssetValue,
	        	netAssetValue = formatNetAssetValue(ccy, value);
			$("#netAsset" + count).html(netAssetValue);
    	}
    });
};

setPositionDetailPageScrollHeight = function() {
	//set the height of tableScrollDiv adjust the window's height
	if($("#positionDTable").length > 0) {
		var height = ($(window).height() - 200) + "px";
		$("#tableScrollDiv").css({"height" : height, "overflow" : "scroll"});
	}
};

formatNetAssetValue = function(ccy, netAssetValue) {
	return " "+ccy + " " + netAssetValue;
};

String.prototype.replaceAll = stringReplaceAll;

function stringReplaceAll(oldString, newString) {
	raRegExp = new RegExp(oldString, "gm");
	return this.replace(raRegExp, newString);
}

(function(){
/**
	 * Because some text want to display muti-lined.
	 * so I will override the encode function of jQuery and add replace(/\n/g, "<br/>") 
	 */
//	jQuery.extend({
//		encode : function(text){
//			var encodeStr = ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
//			return encodeStr.replace(/\n/g, "<br/>");
//		}
//	});
//	
//	var encodeInputTextarea = function(){
//		$("input:visible").each(function(i,item){
//			var value = $(item).val();
//			$(item).val( value.replace(/\<br\/\>/g, "\n") );
//		});
//		
//		$("textarea:visible").each(function(i,item){
//			var value = $(item).val();
//			$(item).val( value.replace(/\<br\/\>/g, "\n") );
//		});
//		
//	};
	
//	window.encodeInputTextarea = encodeInputTextarea;
})();

function createXHR (){
	var xhr;
	if(typeof window.XMLHttpRequest != "undefined"){
		xhr = new XMLHttpRequest();
	}else if(typeof window.ActiveXObject != "undefined") {
		if(typeof arguements.callee.activeXString != "string"){
			var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0",
							"MSXML2.XMLHttp"],
				  i,len;
			for (i=0, len=versions.length; i < len; i++){
				try{
					new ActiveXObject(version[i]);
					arguments.callee.activeXString = version[i];
					break;
				}catch(ex){
					app.trigger("ajaxError", "createXHR ERROR");
				}
			}
			
		}
		xhr = new ActiveXObject(arguments.callee.activeXString);
	} else {
		throw new Error("No XHR object available");
	}
	
	return xhr;
}


var addAccessLogout = function(){
    var requestUrl = app.EPRESTAPI_CONTEXT_ROOT + "access/logout?" + "rand=" + (new Date()).getTime();
	var xhr = createXHR();
	xhr.open("GET", requestUrl, false);
	xhr.send(null);
};

var addLogoutRecord = function(addTrackRecord){
	if(addTrackRecord===true){
		trackAction("Logout - Exit");
	}    
    var cnumber = getCookie("cnumber");
    var requestUrl = app.EPRESTAPI_CONTEXT_ROOT + "audit/visit?cnumber="+cnumber + "&rand=" + (new Date()).getTime();
	var xhr = createXHR();
	//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.open("POST", requestUrl, false);
	xhr.send(null);
};

