/******************************** PAGE CONTENT *****************************************
 *				FUNCTIONS 									DESCRIPTION
 *		openCalendar(target, format)				Open a Whiz 3.1 calendar
 *		openCarrierCodeEncoder(target)				Open a Whiz 3.1 carrier code encoder
 *		openCityCodeEncoder(target)					Open a Whiz 3.1 city code encoder
 *		openEncoder(target, type)					Open a Whiz 3.1 encoder (requires type)
 *		createTag(tag, content)						Create an xml tag in string
 *		addAttribute(string, name, value)			Add an attribute to an xml tag in string
 *		createWebRequest()							Create a MSXML based web request
 *		sendSoap(url, ns, fn, soap, action)			Send an xml soap message to a given endpoint
 *		addSoapEnvelope(content, fn, ns)			Add body content to an xml soap envelope
 *		getMonthByShortName(name)					Get the month (0-11) for months in MMM format
 *		contains(strs, str)							Test if a string contains another string
 *		parseDate(date)								Parse a date in DDMMM/DDMMMYY/DDMMMYYYY/DD-MM-YYYY format
 *		toDDMMM(date)								Format a date to DDMMM format
 *		toDDMMMYY(date)								Format a date to DDMMMYY format		
 *		toDDMMMYYYY(date)							Format a date to DDMMMYYYY format
 *		closure(ary, evaluation)					For each item in the array, examine the evaluation
 *		trim(str)									Trim whitespaces from the string
 *		
 *		
 ***************************************************************************************/

var DDMMM = 0;
var DDMMYY = 1 ;
var MMYY = 2;
var DDMMMYY = 3;
var DDMMMYYYY = 4;
var DDMM = 5 ;
var DDMMYYYY = 6;

var CROSS = "\u00a5";
var CHNG = "\u00a4";
var END_ITEM = "\u00a7";

var mths = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var WEEKs =["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"];
var WEKs = [ "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" ];

function openCalendar(target, format) {
	if (window.external.showCalendar(format) == 0) {
		target.value = window.external.CalendarDate;
	}
}
function openCarrierCodeEncoder(target) {
	if (window.external.showEncoder("ENCODER_CARRIER") == 0) {
		target.value = window.external.EncoderCode;
	}
}

function openCityCodeEncoder(target) {
	if (window.external.showEncoder("ENCODER_CITY") == 0) {
		target.value = window.external.EncoderCode;
	}
}

function openEncoder(target, type) {
	if (window.external.showEncoder(type) == 0) {
		target.value = window.external.EncoderCode;
	}
}

function createTag(tag, content) {
	if (content == null || content == "") {
		return "<" + tag + " />";
	} else {
		return "<" + tag + ">" + content + "</" + tag + ">";
	}
}

function addAttribute(string, name, value) {
	if (string.indexOf("<") == -1 || string.indexOf(">") <= string.indexOf("<")) return string;
	var h = string.substring(0, string.indexOf(">"));
	var f = string.substring(string.indexOf(">"), string.length);
	return h + " " + name + "=\"" + value + "\"" + f;
}

function createWebRequest() {
	var x;
	try {
		return new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) { }
	
	if (x == null) {
		try {
			x = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) { }
	} // if
	
	// Gecko / Mozilla / Firefox
	if ((x == null) && (typeof(XMLHttpRequest) != "undefined")) {
		x = new XMLHttpRequest();
	}
	return x;
}

function sendSoap(url, ns, fn, soap, action) {
	var conn = createWebRequest();
	conn.open("POST", url, false);
	conn.setRequestHeader("SOAPAction", action);
	conn.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	
	var request = addSoapEnvelope(soap, fn, ns);
	conn.send(request);
	if (conn.readyState == 4 && conn.status == 200) {
//		alert(conn.responseText);
		return conn.responseXML;
	} else {
//		alert(conn.status);
//		alert(conn.responseText);
		throw conn.responseText;
	}
}



function addSoapEnvelope(content, fn, ns) {
	var soap = "<?xml version='1.0' encoding='utf-8'?>"
		+ "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
		+ "<soap:Body>"
		+ "<" + fn + " xmlns='" + ns + "'>";
	soap += content;
	soap += "</" + fn + ">" + "</soap:Body>" + "</soap:Envelope>";
	
	return soap;
}

function addSoapEnvelopeForJava(content, fn, ns) {
	var soap = '<?xml version="1.0" encoding="UTF-8"?>'
		+'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
  		+'<SOAP-ENV:Body>'
   		+ '<' + fn + '>';
		soap += content;
		soap += "</" + fn + ">" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";
	return soap;
}

function getMonthByShortName(name) {
	name = name.toUpperCase();
	for (var i = 0; i < mths.length; i++) {
		if (mths[i] == name) {
			return i;
		}
	}
	return -1;
}

function contains(strs, str) {
	for(var i=0;i<strs.length;i++){
		if(strs[i] == str){
			return true; 
		}
	}
	return false;
}
//yearRangeType=0 the return date (now -1Y,now)
//yearRangeType=1 the return date (now,now +1Y,)
function parseDate(date,yearRangeType) {
	var dd;
	var mm;
	var yyyy;
	if (date.length == 5 || date.length == 7 || date.length == 9) {
		dd = parseInt(date.substring(0, 2), 10);
		mm = getMonthByShortName(date.substring(2, 5));
		if (date.length == 5) {
			yyyy = new Date().getFullYear();
		} else if (date.length == 7) {
			yyyy = parseInt("20" + date.substring(5, 7), 10);
		} else {
			yyyy = parseInt(date.substring(5, 9), 10);
		}
		var d = new Date(yyyy, mm, dd, 0, 0, 0, 0);
		if(yearRangeType!=self.undefined){
			switch(yearRangeType){
				case 0:
					if(date.length == 5 && d > new Date())
						d.setYear(d.getFullYear() - 1);
				    break;
				case 1:
					if(date.length == 5 && d < new Date())
						d.setYear(d.getFullYear() + 1);
				    break;	
			}
		}
		return d;
	} else return new Date();
}

function strToDate(dateStr , dateFormat){
	if(dateFormat=="YYYY-MM-DD"){
		var tmps = 	dateStr.split("-");
		return new Date(tmps[0] , tmps[1] -1 ,tmps[2]);
	}else if(dateFormat=="DD-MM-YYYY"){
		var tmps = 	dateStr.split("-");
		return new Date(tmps[2] , tmps[1] -1 ,tmps[0]);
	}else{
		alert("Unknow Date format!");
	}
}

Date.prototype.toDDMMM = function() {
	return toDDMMM(this);
}

Date.prototype.toDDMMMYY = function() {
	return toDDMMMYY(this);
}

Date.prototype.toDDMMMYYYY = function() {
	return toDDMMMYYYY(this);
}

function toDDMMM(date) {
	var d = toDDMMMYYYY(date);
	return d.substring(0, 5);
}

function toDDMMMYY(date) {
	var d = toDDMMMYYYY(date);
	return d.substring(0, 5) + d.substring(7, 9);
}

function toDDMMMYYYY(date) {
	var d = new Date(date.getTime());
	var dd = d.getDate() < 10 ? "0" + d.getDate() : d.getDate().toString();
	var mmm = mths[d.getMonth()];
	var yyyy = d.getFullYear().toString();
	return dd + mmm + yyyy;
}

Date.prototype.parseStr = function(format) {
	var YYYY = "000" +  this.getFullYear();
	YYYY = YYYY.substr(YYYY.length - 4);
	var YY = YYYY.substr(2);
		format = format.replaceAll("@YYYY@",YYYY);
		format = format.replaceAll("@YY@",YY);
	var M=this.getMonth()+1;
	var MM=(M<10)?"0"+M:M;
	var MMM=mths[M - 1];
		format=format.replaceAll("@MMM@",MMM);
		format=format.replaceAll("@MM@",MM);
		format=format.replaceAll("@M@",M);
	var D=this.getDate();
	var DD=(D<10)?"0"+D:D;
		format=format.replaceAll("@DD@",DD);
		format=format.replaceAll("@D@",D);
		
	var h=this.getHours();
	var hh=(h<10)?"0"+h:h;
		format=format.replaceAll("@hh@",hh);
		format=format.replaceAll("@h@",h);
	var m=this.getMinutes();
	var mm=(m<10)?"0"+m:m;
		format=format.replaceAll("@mm@",mm);
		format=format.replaceAll("@m@",m);
	var s=this.getSeconds();
	var ss=(s<10)?"0"+s:s;
		format=format.replaceAll("@ss@",ss);
		format=format.replaceAll("@s@",s);
	var dayOfWeek=this.getDay();
	    format=format.replaceAll("@WEEK@",WEEKs[dayOfWeek]);
		format=format.replaceAll("@WEK@",WEKs[dayOfWeek]);
	return format;
}


	String.prototype.strParseDate = function(format){
		if(format.length!=this.length) throw "Unknow format!";
		var _yyyy = new Date().getFullYear().toString();
		var YYYY_indexOf = format.indexOf("YYYY");
		if(YYYY_indexOf >-1){
			_yyyy = this.substring(YYYY_indexOf , YYYY_indexOf + 4);
		}else{
			var YY_indexOf = format.indexOf("YY");
			if(YY_indexOf > -1) {
				_yyyy = ("" + _yyyy).substring(0,2) + this.substring(YY_indexOf , YY_indexOf + 2);
			}else{
				var Y_indexOf = format.indexOf("Y");
				if(Y_indexOf > -1) throw "Unknow Year format!";
			}
		}
		
		var _mm=0;
		var MMM_indexOf = format.indexOf("MMM");
		if(MMM_indexOf >-1){
			_mm = getMonthByShortName(this.substring(MMM_indexOf , MMM_indexOf + 3)) + 1;
			if(_mm==0) throw "Unknow Month format!";
		}else{
			var MM_indexOf = format.indexOf("MM");
			if(MM_indexOf > -1) {
				_mm = this.substring(MM_indexOf , MM_indexOf + 2);
			}else{
				throw "Unknow Month format!";
			}
		}
		var _dd=0;
		var DD_indexOf = format.indexOf("DD");
		if(DD_indexOf > -1) {
			_dd = this.substring(DD_indexOf , DD_indexOf + 2);
		}else{
			throw "Unknow Date format!";
		}
		
		return new Date(_yyyy,_mm - 1,_dd);
	}
	
function closure(ary, evaluation) {
	for (var i = 0; i < ary.length; i++) {
		if (ary[i].length != undefined) {
			for (var j = 0; j < ary[i].length; j++) {
				eval(evaluation.replace(/\{0\}/g, "ary[i][j]"));
			}
		} else {
			eval(evaluation.replace(/\{0\}/g, "ary[i]"));
		}
	}
}

function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");
}

function isEmpty(str) {
	return str == null || str.length == 0;
}

String.prototype.replaceAll = function(str, replaceText) {
	var tmp = this;
	while(tmp.indexOf(str) >- 1) {
	  tmp = tmp.replace(str, replaceText);
	}
	return tmp;
}

String.prototype.padLeft = function(len, string) {
	if (this.length >= len) return this.toString();
	else {
		var s = this.toString();
		for (var i = 0; i < len - this.length; i++) {
			s = string + s;
		}
		return s;
	}
}

String.prototype.padRight = function(len, string) {
	if (this.length >= len) return this.toString();
	else {
		var s = this.toString();
		for (var i = 0; i < len; i++) {
			s += string;
		}
		return s;
	}
}

String.prototype.trim = function() {
	var whitespace = new String(" \t\n\r"); 
    var s = this; 
    if (whitespace.indexOf(s.charAt(0)) != -1) 
    { 
        var j = 0, i = s.length; 
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1) 
        { 
            j++; 
        } 
        s = s.substring(j, i); 
    } 
   
    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) 
    { 
        j = s.length - 1; 
        while (j >= 0 && whitespace.indexOf(s.charAt(j)) != -1) 
        { 
            j--;
        } 
        s = s.substring(0, j+1); 
    } 
    return s; 
}
    //add by ho  StringUtil.java 
    // not test
function substringAfterLast(str,lastStr){
    return str.substr(str.lastIndexOf(lastStr) + lastStr.length);
}

function substringBefore(str,st){
    return str.substring(0,str.indexOf(st));
}

function substringAfter(str,st){
	return str.substr(str.indexOf(st) + st.length);
}

function substringBetween(str,str1,str2){
	var i1=str.indexOf(str1);
	var i2=str.indexOf(str2);
	if(i1==-1 || i2==-1) return null;
	if(i1<i2)
    	return str.substring(i1 + str1.length,i2);
	else
		return str.substring(i2 + str2.length,i1);	
}

//just for Whizscripts
function showTimeoutAlert(){
	if(hideProcessing) hideProcessing();
	try{
		var mess="Host timeout.";
		throw mess;
	}catch(e){
		alert(e);
	}
}

var beforeCommandCommandCommand;
var finishCommandCommandCommand;
var catchExceptionCommandCommandCommand;
var XMLHttpXMLHttpXMLHttp;
var XMLHttptimerIdidididid;
var XMLHttpAbortAbortAbort=false;
var alertMessagealertMessagealertMessage;
var waitTimewaitTimewaitTime;
var timeoutExptimeoutExptimeoutExp;

function sendSoap(url,ns,fn,soap,action,before,finish,catchException,waitTime,timeoutExp){
        window.parent.beforeCommandCommandCommand=before;
        window.parent.finishCommandCommandCommand=finish+"(XMLHttp)";
        window.parent.catchExceptionCommandCommandCommand=catchException;
        window.parent.XMLHttpXMLHttpXMLHttp = createWebRequest();
        window.parent.XMLHttpXMLHttpXMLHttp.onreadystatechange=xmlHttpChange;
        window.parent.XMLHttpXMLHttpXMLHttp.open("POST",url,true);
        window.parent.XMLHttpXMLHttpXMLHttp.setRequestHeader("SOAPAction", action);
	    window.parent.XMLHttpXMLHttpXMLHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        window.parent.XMLHttpXMLHttpXMLHttp.send(addSoapEnvelope(soap, fn, ns));
   /* if(waitTime!=undefined){
        if(timeoutExp!=undefined)
            timerIdidididid = setTimeout(timeoutExp, waitTime);
        else
            timerIdidididid = setTimeout("alert(\"Host timeout!\");", waitTime);      
    } */
}
//use in SAPJVMASK ,java web services
function sendSoapForJava(url,ns,fn,soap,action,before,finish,catchException,alertMessage,waitTime,timeoutExp){
	window.parent.beforeCommandCommandCommand=before;
	window.parent.finishCommandCommandCommand=finish+"(XMLHttp)";
	window.parent.catchExceptionCommandCommandCommand=catchException;
	window.parent.alertMessagealertMessagealertMessage=alertMessage;
	window.parent.waitTimewaitTimewaitTime=waitTime;
	window.parent.timeoutExptimeoutExptimeoutExp=timeoutExp;
	window.parent.XMLHttpXMLHttpXMLHttp = createWebRequest();
	window.parent.XMLHttpXMLHttpXMLHttp.onreadystatechange=xmlHttpChangeForJava;
	window.parent.XMLHttpXMLHttpXMLHttp.open("POST",url,true);
	window.parent.XMLHttpXMLHttpXMLHttp.setRequestHeader("SOAPAction", action);
	window.parent.XMLHttpXMLHttpXMLHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	window.parent.XMLHttpXMLHttpXMLHttp.send(addSoapEnvelopeForJava(soap, fn, ns));
	if(alertMessage==self.undefined) alertMessage="";
	if(waitTime!=self.undefined){
		if(timeoutExp!=self.undefined){
			window.parent.XMLHttptimerIdidididid = setTimeout(timeoutExp, waitTime);
		}else{
			window.parent.XMLHttptimerIdidididid = setTimeout('abortXMLHttp();alert("'+alertMessage+'");', waitTime);      
		}
    }
}

function xmlHttpChange()
{
    if (window.parent.beforeCommandCommandCommand != undefined) eval(window.parent.beforeCommandCommandCommand);
    if (window.parent.XMLHttpXMLHttpXMLHttp.readyState!=undefined && window.parent.XMLHttpXMLHttpXMLHttp.readyState == 4) {
        if (window.parent.XMLHttpXMLHttpXMLHttp.status == 200) {
            if (window.parent.finishCommandCommandCommand != undefined) eval(window.parent.finishCommandCommandCommand.replace("(XMLHttp)", "(window.parent.XMLHttpXMLHttpXMLHttp)"));
        } else {
            if (window.parent.catchExceptionCommandCommandCommand != undefined) eval(window.parent.catchExceptionCommandCommandCommand);
            if (!window.parent.XMLHttpAbortAbortAbort) alert("Error in sending request. Please restart application. If problem persists, please contact administrator.");
            window.parent.XMLHttpAbortAbortAbort = false;
        }
    }
}

function xmlHttpChangeForJava()
{
    if (window.parent.beforeCommandCommandCommand != undefined) eval(window.parent.beforeCommandCommandCommand);
    if (window.parent.XMLHttpXMLHttpXMLHttp.readyState!=undefined && window.parent.XMLHttpXMLHttpXMLHttp.readyState == 4) {
        if(window.parent.XMLHttptimerIdidididid != undefined) clearTimeout(window.parent.XMLHttptimerIdidididid);
        if (window.parent.XMLHttpXMLHttpXMLHttp.status == 200) {
            if (window.parent.finishCommandCommandCommand != undefined) eval(window.parent.finishCommandCommandCommand.replace("(XMLHttp)", "(window.parent.XMLHttpXMLHttpXMLHttp)"));
        } else {
            if (window.parent.catchExceptionCommandCommandCommand != undefined) eval(window.parent.catchExceptionCommandCommandCommand);
            if (!window.parent.XMLHttpAbortAbortAbort) alert(window.parent.alertMessagealertMessagealertMessage);
            window.parent.XMLHttpAbortAbortAbort = false;
        }
    }
}

function abortXMLHttp(){
   if(window.parent.XMLHttptimerIdidididid != undefined) clearTimeout(window.parent.XMLHttptimerIdidididid);
   if(window.parent.XMLHttpXMLHttpXMLHttp!=undefined && window.parent.XMLHttpXMLHttpXMLHttp!=null && window.parent.XMLHttpXMLHttpXMLHttp.readyState==1){
     window.parent.XMLHttpAbortAbortAbort=true;
     window.parent.XMLHttpXMLHttpXMLHttp.abort();
     window.parent.XMLHttpXMLHttpXMLHttp=null;
   }
}

