var debug = constants['com.hsi.client.debug'];
var ch_u00 =  '\\u00';			//used by prototype.js
/*
 * Submit form with action
 */
function submitForm(cmd, options) {	
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}
	
	if (cmd == "navigation"){
		//currentForm.method = "get";			//TODO: will be available in next release
	}

	currentForm.cmd.value = cmd;
	currentForm.submit();
}

/*
* Navigation Engine Client Script
*/
function navigate(pageId){
	//Tranlation check
	if (isTranslated() && !supportSimplified(pageId)){
		var locale = constants['com.hsi.client.locale'].toLowerCase();
		if (debug) alert("Untranlate back to "+locale+", pageId: "+pageId);
		unTranslate(locale, pageId);
		return;
	}
	
	//Normal Navigation
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}
	currentForm.pageId.value = pageId;
	submitForm('navigation');
}

/*
* Language Switching Script
* Simply switch pageId between en|zh_hk|zh_cn
* param pageId is optional, if null, will use current pageId
*/
function switchLang(lang, pageId){
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}
	var page = pageId || currentForm.pageId.value;
	currentForm.pageId.value = page;
	currentForm.lang.value = lang;	
	if (debug) alert('Switching '+page+' to language: '+lang);
	submitForm('lang');
}

/**
* Return true if the current page is translated.
*/
function isTranslated(){
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}
	var url = currentForm.action;
	var gbUrl = constants['com.hsi.client.translationUrl'];
	if (!gbUrl){
		alert("No gbUrl found.");	
		return;
	}
	return url.indexOf(gbUrl) != -1;	
}

/*
 * Disable use of translation server.
 * Remove translation address from url
 */
function unTranslate(lang, pageId){
	if (isTranslated()){
		var currentForm = document.forms[0];
		if (!currentForm) {
			alert("No currentForm is declared");
			return;
		}
		var url = currentForm.action;
		var gbUrl = constants['com.hsi.client.translationUrl'];
		if (!gbUrl){
			alert("No gbUrl found.");	
			return;
		}
		var iUrl = url.indexOf(gbUrl);
		if (iUrl != -1){
			var iStart = iUrl+gbUrl.length;
			currentForm.action = "http://"+url.substring(iStart);				
		}
	}
	switchLang(lang, pageId);	
}

/**
 * Using tranlation server.
 * Append translation address to url;
 * E.g. http://scmain.hangseng.com/gb/130.3.14.206:9080/HSI-Net/HSI-Net?cmd=navigate&pageId=
 */
function translate(pageId){	
	if (!isTranslated()){
		var currentForm = document.forms[0];
		if (!currentForm) {
			alert("No currentForm is declared");
			return;
		}
		var action = constants['com.hsi.client.esFormAction'];
		var contextPath = constants['com.hsi.client.contextPath'];
		var pageId = constants['com.hsi.client.pageId'];
		var gbUrl = constants['com.hsi.client.translationUrl'];
		if (!gbUrl){
			alert("No gbUrl found.");
			return;
		}
		try{
			var url = gbUrl+ window.location.host + contextPath + "/"+ action;
			url = switchToHTTP(url);						
			if (debug) alert("Translated Url: "+url);
			currentForm.action = url;
		}catch(e){
			alert("Error when assigning translated server url: "+url +"\nReason: "+ e);
			return;
		}
	}
	switchLang('zh_hk',pageId);
}

/**
* Force switch to HTTP
*/
function switchToHTTP(url){
	url = url.replace(/https/i,"http");
	var httpPort = constants['com.hsi.http.port'];
	var httpsPort = constants['com.hsi.https.port'];		
	if (httpsPort && httpPort) url = url.replace(new RegExp(httpsPort,'g'),httpPort);
	return url;
}

/*
Return true if the given pageId can be translated other languages
*/
function canTranslate(pageId){
	if (!pageId) return false;
	if (pageId.match(/(en|zh_hk)\.contact\.(thankyou)$/)!=null) return false;
	if (pageId.match(/(en|zh_hk)\.products\.form_input$/)!=null) return true;	
	if (pageId.match(/(en|zh_hk)\.products\.form.+$/)!=null) return false;
	return true;
}

/*
Return true if the given pageId can be translated to simplified languages
*/
function supportSimplified(pageId){
	if (pageId.match(/(en|zh_hk)\.contact\.(form|thankyou)$/)!=null) return false;
	if (pageId.match(/(en|zh_hk)\.products\.form.*$/)!=null) return false;
	return true;
}

/*
* Download a web resource by given url.
*/
function download(url){

window.open( url, "downloadWindow", 
"status = 1, height = 800, width = 600, resizable =1" );

}

/**
Switch tab helper method
*/
function switchTab(targetTab,pageId){
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}
	var page = pageId || currentForm.pageId.value;
	currentForm.pageId.value = page;
	$('tabs.current').value = targetTab;
	submitForm('tab');
}

function showWaitingScreen(){
	try{
		
	//disable Scrolling
	document.body.scroll = "no";

	//screen environments
	var screenTop = document.body.scrollTop;
	var screenLeft = document.body.scrollLeft;
	//screen mask
		var oDiv = document.createElement("div");
		oDiv.className = "screenMask";
		oDiv.style.marginTop = screenTop;
		oDiv.style.marginLeft = screenLeft;
		oDiv.style.width = window.screen.availWidth;
		oDiv.style.height = window.screen.availHeight;	
	
	//panel
	var oPanel = document.createElement("div");
	oPanel.className = "screenPanel";	
	//image icon, add to panel
	document.body.appendChild(oPanel);
	//add to document
	document.body.appendChild(oDiv);
	
	//Fancy Effect!	
	new Effect.Opacity(oDiv, {duration:0.5, from:0.0, to:0.5});
	Effect.Grow(oPanel);	
	
	}catch (e){alert(e); throw e;}
	
}


function renderLink(link,linkName,target,image){
	var l = "<a href=\"javascript:openUrl('"+link+"','"+linkName.replace(new RegExp("[\\W]",'g'),"_")+"',800,600,false);\"" 
	+">";
	document.write(l);
	if (image){
		renderImage(image,linkName);
	}else document.write(linkName);
	document.write("</a>");
}

/*
 * Render Image Tag by a given image file name
 */
function renderImage(image,alt){
	var img = "<img src=\""+constants['imagePath']+'/'+image+"\" border=\"0\" " +
			(alt?"alt=\""+alt+"\" ":"") +
			"/>";
	document.write(img);
}

/*
 * Go to the specified URL in the window
 */
function goUrl(url) {
	location.href = url;
}

/*
 * Popup function to show stand alone formula page
*/
function popupPage(page_id_suffix, height, width) { 
var pageId = constants['com.hsi.client.pageId'];
var contentPagePath = constants['com.hsi.client.contentPagePath'];
var iFolderId = pageId.lastIndexOf('.');
if (iFolderId < 0){
	alert("Cannot found folder Id: "+pageId);
	return;
}
pageId = pageId.substring(0,iFolderId)+"."+page_id_suffix;
var url = "/HSI-Net/HSI-Net?cmd=popup&pageId="+pageId;
window.open( url, "myWindow", 
"status = 1, height = " + height + ", width = " + width +", resizable=0" );
}

function popupFormula(page_id_suffix) {
  popupPage(page_id_suffix, 130, 940);
}

function myPopup() { 
var pageId = constants['com.hsi.client.pageId'];
var contentPagePath = constants['com.hsi.client.contentPagePath'];
var iFolderId = pageId.lastIndexOf('.');
if (iFolderId < 0){
	alert("Cannot found folder Id: "+pageId);
	return;
}
pageId = pageId.substring(0,iFolderId)+".popup_formula";
var url = "/HSI-Net/HSI-Net?cmd=popup&pageId="+pageId;
window.open( url, "myWindow", "status = 1, height = 130, width = 940, resizable =0" );
} 

function Popup(pageId) { 
var url = "/HSI-Net/HSI-Net?cmd=popup&pageId="+pageId;
window.open( url, "myWindow", "status = 1, height = 600, width = 900, resizable =0" );
} 

/**
due to page exprie issue, the page doesn't exipred for the 1st time, so it need to retry the 2nd time.
*/
function reTrySubmit(pageId){
	var currentForm = document.forms[0];
	if (!currentForm) {
		alert("No currentForm is declared");
		return;
	}

	if (false){//IE7: Operation About Error, so you must place <input /> on JSP
		var inputElm = document.createElement('input');
		inputElm.setAttribute("type", "hidden");
		inputElm.setAttribute("name", "retry");
		inputElm.setAttribute("value", "false");
		currentForm.appendChild(inputElm);
	}
		
	var oRetry = $('retry');
	if (!oRetry) {alert("No retry parameter to disable next retry screen.");return;}
	if (pageId && oRetry.value == "true"){
	    if (debug) alert('Revisit page: '+pageId);
	    oRetry.value = "false";    
	    currentForm.expire.value= "true";
		navigate(pageId);    	
	}
}

/****************( Common Methods)*****************/

//safe function to hide an element with a specified id
Object.prototype.hide = function () {
	// DOM3 = IE5, NS6
	this.style.display = 'none';	
}

//safe function to show an element with a specified id
Object.prototype.show = function() {
	this.style.display = 'block';	
}

//safe function to show an element with a specified id
function show(obj) {
	obj.style.display = 'block';	
}
function hide(obj) {
	obj.style.display = 'none';	
}

function toogle(obj){
	if (obj.style.display == 'none')
		show(obj);
	else hide(obj);
}


/**
* Navigate page from one to another
*/
function page(no){
	var pages = 20;	//Page no bigger than 20
	var targetPage = $('page-'+no);
	if (!targetPage) return false;
	for (var i = 1; i <=pages ; i++){
		var oPage = $('page-'+i);		
		if (!oPage) continue;
		 hide(oPage);
		var oPager = $('pager-'+i);	
		if (!oPager) continue;
		oPager.className = "pageNum";		
	}	
	show(targetPage);	
	var cPage = $('page-current');		
	if (cPage) cPage.value = no;
	var oPager = $('pager-'+no);		
	if (oPager) oPager.className = "curPageNum";			
	return true;
}

function goPage(no){
	page(no);
}

function nextPage(){
	var oPage = $('page-current');		
	if (!oPage) return;
	var p = oPage.value;
	p++;
	if (page(p))
		oPage.value = p;
}

function prevPage(){
	var oPage = $('page-current');		
	if (!oPage) return;
	var p = oPage.value;
	p--;
	if (page(p))
		oPage.value = p;
}



/*
 * Open a pop-up window and go to the specified URL
 */
function openUrl(url, name, width, height, fullscreen) {
	if (fullscreen != false) {
		width  = screen.availWidth;
		height = screen.availHeight;
	}

	var top  = (screen.availHeight - height) / 2;
	var left = (screen.availWidth - width) / 2;

	var win  = window.open(url, name, 'top=' + top + ', left=' + left + ', width=1, height=1, resizable=yes, scrollbars=yes, status=yes');
	win.resizeTo(width, height);
	win.focus();

	return win;
}

/*
	Force all form property value to "false/N" while:
	1. The checkbox is Unchecked AND
	2a. The checkbox doesn't has value. (No "value" attribute) OR
	2b. The checkbox value = [true|false|Y|N]
*/
function formPreProcess(form){
	var inputs = document.getElementsByTagName("input");
	for (i = 0 ; i < inputs.length;i++){
		var oInput = inputs[i];
		if (oInput.type != "checkbox" || oInput.checked) continue;
		if (oInput.value == "Y"){
			oInput.value = "N";
			oInput.checked = true;
			if (debug) alert("forced  "+oInput.name+" to N.");		
		}else if (oInput.value == "true"){
			oInput.value = "false";
			oInput.checked = true;
			if (debug) alert("forced  "+oInput.name+" to false.");					
		}else if (debug) alert("Unknown property value: "+oInput.value+"with name: "+oInput.name);
			
	}
	//Dump form value	
	if (debug){
		pp = "<<Form values>>\n";
		for (p in form){
			pp += p+eval("form."+p+".value")+"\n";
		}
		alert(pp);
	}
	reEnableFields(form);
	
	return true;
}

/*
 *	Enable Disabled elements in form
 */
 function reEnableFields(oForm){
 	var FIELD_TYPES = ["text","textarea","checkbox","radio"];
 	var oList = oForm.getElementsByTagName("input");
 	for (var i = 0 ; i < oList.length; i++){
 		if (contains( FIELD_TYPES,oList[i].type) && oList[i].disabled == true){
 			oList[i].disabled = null;
 		}
 	}
 }

/*
 * Removes leading whitespaces
 */
String.prototype.LTrim = function(){
	var re = /\s*((\S+\s*)*)/;
	return this.replace(re, "$1");
}

String.prototype.LTrimZeros = function(){
	var re = /[0]*(([^0]+[0]*)*)/;
	return this.replace(re, "$1");
}

String.prototype.ltrim = function(space) {
  var self = this;
  while (1) {
    if (self.substring(0, 1) != space)
      break;
    self = self.substring(1, self.length);
  }
  return self;
}

String.prototype.rtrimP = function(pattern) {
	var str = this;
   pattern = pattern || "[\\s]+$";
   return str.replace(new RegExp( pattern , "g"), "");
}

/*
 * Removes ending whitespaces
 */
String.prototype.RTrim = function(){
	var re = /((\s*\S+)*)\s*/;
	return this.replace(re, "$1");
}

/*
 * Removes leading and ending whitespaces
 */
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g, "");
}

/*
 * Pop up a calendar for selecting a date
 */
function doSelectDate(dataName, anchorName, pattern) {
	var call = new CalendarPopup();
	call.select(document.getElementById(dataName), anchorName, pattern);
}

/*
 * Alert Messages upon the following constants has its key:
 * - starts with "errMsg."
 */
function displayMsg() {
	var msg = "";

	for (i in constants) {
		if (i.substring(0, 7) == "errMsg.") {
			msg += (msg.length > 0 ? "\n" : "") + constants[i];
		}
	}

	if (msg.length > 0) {
		alert(msg);
	}

	return;
}

//With toggle check option
function selectAll(checkBoxId){
	var allCheckedBefore = true;
	var cBoxes = document.getElementsByName(checkBoxId);	
	for (i = 0 ; i < cBoxes.length;i++){
		if (!cBoxes[i].checked) {
			cBoxes[i].checked = true;
			allCheckedBefore = false;
		}
	}
	if (cBoxes.length >0 && allCheckedBefore) clearAll(checkBoxId);
}


function clearAll(checkBoxId){
	var cBoxes = document.getElementsByName(checkBoxId);
	for (i = 0 ; i < cBoxes.length;i++){
		cBoxes[i].checked = false;
	}
}


function getInputValue(sInput){
 	var INPUT_TYPES = ["textarea","select"];
	var oElement = document.getElementById(sInput);	
	if (oElement){
		var tag = oElement.tagName.toLowerCase();
		if (contains(INPUT_TYPES,tag)){
			return oElement.value;
		}else if (tag == "input"){
			if (oElement.type == "text"){
				return oElement.value;
			}
		}
	}
	return null;
}

/**
* set the given object target with the given value
*/
function setTargetValue(oTarget, value){
	if (!value) value = "";
	if (oTarget){
		var tag = oTarget.tagName.toLowerCase();
		if (tag == "input" || tag == "select"){
			oTarget.value = value.trim();
			return;
		}else if (tag == "div" || tag == "textarea"){
			oTarget.innerText = value.trim();
			return;
		}else alert("Cannot resolve target element type ("+oTarget.name+")");		
	}
}


/**
 * Invoke lookup screen with dynamic parameters assignment.
 * params: 2d array containing list of name/value pairs of parameters
 * example: lookup('/lookup?action=searchTemplate',[[1,11],[2,22]],'source1,source2')
 * output: &param1=value1&param2=value2&...
 * caution: "&" will be generated at beginning of string.
 */
function lookup(url, params, width, height, fullScreen){
	for (i = 0 ; i < params.length; i++){
		var pName = params[i][0];		
		var sValue = getInputValue(pName);	
		var genName = pName;
		if (sValue != null && sValue.length > 0){		//non-client-side params
			url += "&"+genName+"="+sValue;
	//		alert("dynamic param: "+genName+"="+sValue);			
		}else{
			var pValue = params[i][1];
			url += "&"+genName+"="+pValue;
	//		alert("default param: "+genName+"="+pValue);					
		}
	}
	openUrl(url,'Lookup_pop',450,400,fullScreen?fullScreen:false);
}

/**
	Realign all criterias in page of this search template to either:
	All AND / All OR options depending on given value
*/
function alignCriterias(value){
	var currentForm = eval('document.'+constants['currentForm']);
	var hAndOrs = document.getElementsByTagName("input");		
	for (i =0 ; i< hAndOrs.length;i++){
		if (/template\.criterias\[[0-9]+\]\.andOr/.test(hAndOrs[i].name)){
			hAndOrs[i].value = value;
		}
	}
}

function dump(object){
	//Dump form value	
	pp = "<<Object values>>\n";
	var i = 0;
	for (p in object){
		pp += p+"="+eval("object."+p);
		if (i % 3 ==0)pp+="\n";
		i++;
	}
	alert(pp);
}


/************************
* Array Extensions
*************************/
Array.prototype.item=function(i)
{
	return this[i];	
};

/*
* Return string representation of this Array.
* e.g. ["10.00","02.13","abc"...]
* Replaced by prototype.js - Object.toJSON();
Array.prototype.joinAsString = function(sep){
	var result = "";
     for(var i=0;i<this.length;i++)
     {
     	result += "\""+this[i]+"\"";
     	if (i < this.length-1) result += sep;
     }	
     result+= "";
     return result;
};
*/
Array.prototype.sort=function()
  {
      var tmp;
      for(var i=0;i<this.length;i++)
      {
          for(var j=0;j<this.length;j++)
          {
              if(this[i]<this[j])
              {
                  tmp = this[i];
                  this[i] = this[j];
                  this[j] = tmp;
              }
          }
      }
  };
  
Array.prototype.clear=function()
  {
      this.length = 0;
  };  
  
Array.prototype.contains = function (element) 
  {
          for (var i = 0; i < this.length; i++) 
       {
              if (this[i] == element) 
          {
                      return true;
              }
          }
          return false;
  };
  
/* Shuffles the Array elements randomly */
 Array.prototype.shuffle=function()
 {
     var i=this.length,j,t;
     while(i--)
     {
         j=Math.floor((i+1)*Math.random());
         t=arr[i];
         arr[i]=arr[j];
         arr[j]=t;
     }
 }
 
 /* Removes redundant elements from the array */
 Array.prototype.unique=function()
 {
     var a=[],i;
     this.sort();
     for(i=0;i<this.length;i++)
     {
         if(this[i]!==this[i+1])
         {
             a[a.length]=this[i];
         }
     }
     return a;
 }
 
 /* Returns the index of the element matched from the behind */
 Array.prototype.lastIndexOf=function(n)
 {
     var i=this.length;
     while(i--)
     {
         if(this[i]===n)
         {
             return i;
         }
     }
     return -1;
 }    
 
 

