var affiliate_index_URL="index.jsp";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 8;
var phoneNumberDelimiters = "()- ";
var validWorldPhoneChars = phoneNumberDelimiters + "+";

var debug=false;
var default_country='US';
var default_state='';
DWREngine.setTimeout(240000);
DWREngine.setErrorHandler(timeout);
dwr.util.setEscapeHtml(false);

function showMsg(msg,divid){
	var div = null;
	if(divid!=null)
		div = $(divid);
	if(layers.messager==null){
		if(div==null)
			$("message").innerHTML="<p><h4>"+msg+"</h4></p>";
		else
			div.innerHTML="<p><h4>"+msg+"</h4></p>";
	}else{
		$("msg").innerHTML=msg;
		layers.messager.show();
	}
}

function timeout(msg){
	if(layers.loader==null){
		var div = $('loader_layer');
		if (div != null) {
			div.style.display = 'none';
		}
	}else{
		layers.loader.hide();
	}
	if (msg=="Timeout") {
		msg="<font color='red'><b>The operate timeout !</b></font>";
	} else if (msg=="Session Timeout") {
		window.location.href = affiliate_index_URL;
		return;
	}
	showMsg(msg);
}

function delRow(tab, rowid){
	if (tab == null) return;
	for (var i = 0; i < tab.rows.length; i+=1) {
		if (rowid == tab.rows[i].id) {
			tab.deleteRow(i);
			break;
		}
	}
}
function getRow(tab, rowid){
	if (tab == null) return -2;
	for (var i = 0; i < tab.rows.length; i+=1) {
		var rid = tab.rows[i].id;
		if(rid==null||rid==="")rid=tab.rows[i].style.id;
		if (rowid == rid) return i;
	}
	return 0;
}

function clearOption(selectid){
	var sel = document.getElementById(selectid);
	for(var i=sel.length-1; i>=0; i--)sel.remove(i);
}
function appendOption(selectid, option){
	var select = document.getElementById(selectid);
	try {
		select.add(option, null);	// standards compliant; doesn't work in IE
	} catch(ex) {
		select.add(option); // IE only
	}
}
function overIt(){
	var the_obj = event.srcElement;
	if(the_obj!==null&&the_obj.tagName.toLowerCase()!="td"){
		if(the_obj.parentElement !== null){
			the_obj=the_obj.parentElement;
		}
	}
	if(the_obj!==null&&the_obj.tagName.toLowerCase()=="td"){
		the_obj = the_obj.parentElement;
		if(the_obj.id.indexOf("title")>-1)return;
		if(the_obj.className.indexOf("title")>-1)return;
        if (the_obj.hasChildNodes()) {
		for (i = 0; i < the_obj.childNodes.length; i+=1) {
			var currentNode = the_obj.childNodes[i];
			if (i!=0&&currentNode.nodeName.toLowerCase() == "td") {
				currentNode.oBgc = currentNode.currentStyle.backgroundColor;
				//currentNode.oFc  = currentNode.currentStyle.color;
		     	currentNode.style.backgroundColor='D6E0F5';//'E6E6E6';//'FEFE80';
		     	//currentNode.style.color='blue';
          	}
        }
		}
   }
}

function outIt(){
	var the_obj = event.srcElement;
	if(the_obj!==null&&the_obj.tagName.toLowerCase()!="td"){
		if(the_obj.parentElement !== null){
			the_obj=the_obj.parentElement;
		}
	}
	if(the_obj!==null&&the_obj.tagName.toLowerCase() == "td"){
        the_obj = the_obj.parentElement;
        if(the_obj.id.indexOf("title")>-1)return;
        if(the_obj.className.indexOf("title")>-1)return;
		if (the_obj.hasChildNodes()) {
		for (i = 0; i < the_obj.childNodes.length; i+=1) {
			var currentNode = the_obj.childNodes[i];
			if (i!=0&&currentNode.nodeName.toLowerCase() == "td") {
       			currentNode.style.backgroundColor = currentNode.oBgc;
			    //currentNode.style.color = currentNode.oFc;
			}
		}
		}
	}
}
function validDate(str){
	if(!str.match(/^\d\d?\/\d\d?\/\d{4}$/)){return false;}
	var ar=str.replace(/\/0/g,"/").split("/");
	ar=new Array(parseInt(ar[2]),parseInt(ar[0])-1,parseInt(ar[1]));
	var d=new Date(ar[0],ar[1],ar[2]);
	//alert(d.getFullYear()+"-"+d.getMonth()+"-"+d.getDate());
	return d.getFullYear()==ar[0]&&ar[0]>2004&&d.getMonth()==ar[1]&&d.getDate()==ar[2];
}
function getDate(str){
	return new Date(Date.parse(str.replace(/-/g, "/")));
}
function DateCompare(date1,date2){
	if(typeof(date1)!="object"&&date1.constructor!=Date){return -2;}
	if(typeof(date2)!="object"&&date2.constructor!=Date){return -3;}
	var d=date1.getTime()-date2.getTime();
	if(d>0){
		return 1;
	}else if(d==0){
		return 0;
	}else{
		return -1;
	}
}
function isEmpty (str) {
if ((str==null)||(str.length==0)) return true;
else return(false);
}

function isNaI(str){
	var integer = parseInt(str);
	return isNaN(integer);
}
function isInt (theStr) {
var flag = true;

if (isEmpty(theStr)) { flag=false; }
else
{ for (var i=0; i<theStr.length; i++) {
if (isDigit(theStr.substring(i,i+1)) == false) {
flag = false; break;
}
}
}
return(flag);
}

function isReal (theStr, decLen) {
var dot1st = theStr.indexOf('.');
var dot2nd = theStr.lastIndexOf('.');
var OK = true;

if (isEmpty(theStr)) return false;

if (dot1st == -1) {
if (isNaI(theStr)) return false;
else return(true);
}

else if (dot1st != dot2nd) return (false);
else if (dot1st==0) return (false);
else {
var intPart = theStr.substring(0, dot1st);
var decPart = theStr.substring(dot2nd+1);

if (decPart.length > decLen) return(false);
else if (isNaI(intPart) || isNaI(decPart)) return (false);
else if (isEmpty(decPart)) return (false);
else return(true);
}
}

function today(days) {
	var day = new Date();
    return getDay(day,days);
}

function tomorrow() {
	return today(1);
}
function getDayFromYYYYMMDD(yyyymmddhhmmss){
	var time=yyyymmddhhmmss;
	if(time.length>19)time=time.substring(0,19);
	var year  = time.substring(0,4);
	var month = time.substring(5,7);
	var day   = time.substring(8,10);
	var date  = month+"/"+day+"/"+year;
	if(time.length==19)date+=" "+time.substring(11,19);
	return date;
}
function fillzero(i,s){
	if (s<i){
		var count=i.toString().length-s.toString().length;
		for(var c=0;c<count;c+=1)
			s="0"+s;
	}
	return s;
}
function getDay(day,days){
	if(days==null)days=0;
	if(days!=0)day=new Date(day.getTime()+(days*24*60*60*1000));

	var year  = day.getFullYear();
 	var month = fillzero(10,day.getMonth()+1);
    var day   = fillzero(10,day.getDate());
    return month + "/" + day + "/" + year;
}
function getTime(date){
	return getDay(date)+" "+
	fillzero(10,date.getHours())+":"+fillzero(10,date.getMinutes());
}
function getMMMMddyyyy(){
	var months=new Array("January","February","March","April","May","June",
			"July","August","September","October","November","December");
	var time=new Date();
	var year=time.getYear();
	if (year < 2000)
		year = year + 1900;
	return months[time.getMonth()] + " " + time.getDate() + ", " + year + " ";
}
function useLoadingMessage(divname, message) {
if (divname){
	var loadingMessage;
	if (message) {
		loadingMessage = message;
	} else {
  		loadingMessage = "Loading...";
	}
	
	DWREngine.setPreHook(function() {
		if(layers.loader==null){
    		var div = $(divname);
	    	if (div==null)return;
	    	div.innerHTML = "<div id='loader_layer' class=loader>"+loadingMessage+"<br/><object width='180' height='20' type='application/x-shockwave-flash'><param name='movie' value='/flash/progressbar.swf' /></object></div>";
		}else{
			layers.loader.show();
		}
	});

	DWREngine.setPostHook(function() {
		if(layers.loader==null){
			var div = document.getElementsByName("loader_layer");
			if (div != null) {
				//if (DWRUtil._isArray(div)) {
					for(i=0;i<div.length;i+=1){
						var d=div[i];
						d.style.visibility="hidden";
						d.style.display="none";
					}
				//}else{
				//	div.style.visibility="hidden";
				//	div.style.display="none";
				//}
			}
		}else{
			layers.loader.hide();
		}
	});
}else{
	DWREngine.setPreHook(void(null));
	DWREngine.setPostHook(void(null));
}
}

function getPageNum (totalrow, pagerow) {
	var pages = totalrow / pagerow;
	var pagesround = Math.round(pages);
	if (pagesround < pages) {
		return pagesround + 1;
	}
	return pagesround;
}

var curr_page = 0;
var row_num = 10;
var total_page = 0;
var total_row_num = 0;

function getTotalPage (num) {
	total_row_num=num;
	total_page = getPageNum(num, row_num);
	//alert("total page num:"+
	//total_page+
	//",total row num:"+
	//num);
	displayPages("pages");
}

function displayPages(divname) {
	var pages = $(divname);
	if (pages !== null) {
		if(curr_page<0)curr_page=0;
		if(curr_page>=total_page)curr_page=total_page-1;
		var begin = curr_page - 5;
		if (begin < 0) {
			begin = 0;
		}
		var h = "";
		for (var i = 0; i < 10; i += 1) {
			var list = begin + i;
			if (list == total_page) {
				break;
			}
			var title = list + 1;
			if (curr_page == list) {
				title = "<font color='red'>" + title + "</font>";
			}//else{title = "<font color='blue'>" + title + "</font>";}
			title += " ";
			h += "<a href='javascript:void(null)' onclick='changePage(" +
					list +
					");' class='style10'>" +
					title +
					"</a> ";
		}
		//if (curr_page > Number(0)) {
			h = "<a href='javascript:void(null)' onclick='changePage(" +
					(curr_page - 1) +
					");' class='style10'><</a> " +
					h;
		//}
		//if (total_page>1&&curr_page > Number(0)) {
			h = "<a href='javascript:void(null)' onclick='changePage(0);' class='style10'><<</a> " + h;
		//}
		//if (curr_page < Number(total_page - 1)) {
			h += "<a href='javascript:void(null)' onclick='changePage(" +
					(curr_page + 1) +
					");' class='style10'>></a> ";
		//}
		//if (total_page>1&&curr_page < Number(total_page - 1)) {
			h += "<a href='javascript:void(null)' onclick='changePage(" +
					(total_page - 1) +
					");' class='style10'>>></a>";
		//}
		//var begin_row = curr_page*row_num+1;
		//var end_row   = (curr_page+1)*row_num;
		//if(end_row>total_row_num)end_row=total_row_num;
		//begin_row+"-"+end_row+"/"+total_row_num+" "+(curr_page+1)+"/"+total_page+" "+
		pages.innerHTML="<font class='style10'>Total:"+total_row_num+"&nbsp;&nbsp;&nbsp;&nbsp;</font>"+h;
	}
}

var layerTimer = new Object;

function getRect(id, win)
{
    if(!document.getElementById){ return null;}
    if(!win){ win = window;}

    var o = win.document.getElementById(id);
    if(!o){ return null;}

    var rect = { top:    0, left:   0, width:  0, height: 0 };
    rect.height = o.offsetHeight;
    rect.width = o.offsetWidth;

    while (o)
    {
         rect.top += parseInt(o.offsetTop);
         rect.left += parseInt(o.offsetLeft);
         o = o.offsetParent;
    }
    return rect;
}

function checkRange(test, value, feather){
    return ((test >= (value - feather)) && (test <= (value + feather))) ? true : false;
}

function transform(div, startPosX, startPosY, startWidth, startHeight, targetPosX, targetPosY, targetWidth, targetHeight, steps, JSCode, posX, posY, width, height, terminate){
    if (document.getElementById) {
        var o = document.getElementById(div);
        if (!posX) var posX = startPosX;
        if (!posY) var posY = startPosY;
        if (!width) var width = startWidth;
        if (!height) var height = startHeight;
        if (!steps) var steps = 15;
        
        if (terminate) {
            o.style.left    = targetPosX + 'px';
            o.style.top     = targetPosY + 'px';
            o.style.width   = targetWidth + 'px';
            o.style.height  = targetHeight + 'px';

            eval (JSCode);
            return;
        }
        else {
            o.style.left    = posX + 'px';
            o.style.top     = posY + 'px';
            o.style.width   = width + 'px';
            o.style.height  = height + 'px';
        }
        
        posX += (targetPosX - startPosX) / steps;
        posY += (targetPosY - startPosY) / steps;
        width += (targetWidth - startWidth) / steps;
        height += (targetHeight - startHeight) / steps;

        terminate = checkRange(posX, targetPosX, 1)
                    && checkRange(posY, targetPosY, 1)
                    && checkRange(width, targetWidth, 1)
                    && checkRange(height, targetHeight, 1);

        layerTimer[div] = setTimeout("transform('" + div + "', " + startPosX + ", " + startPosY + ", " + startWidth + ", " + startHeight + ", " + targetPosX + ", " + targetPosY + ", " + targetWidth + ", " + targetHeight + ", " + steps + ", \"" + JSCode + "\", " + posX + ", " + posY + ", " + width + ", " + height + ", " + terminate + ")", 20);
    }
}

function hideFormElements(hide){
    // buggy IE places the form fields always on top, so we have no other
    // chance: we have to hide the center field
    var o = document.getElementById('hide_select');
    //alert(o);
    if (o){
    	o.style.visibility = (hide == 1) ? "hidden" : "visible" ;
    }
    	//alert(o + '5');
    	/*
    if (rForm.length){
        for (i = 0; i < rForm.length; i++){
            for (j = 0; j < rForm[i].elements.length; j++){
                rForm[i].elements[j].style.visibility = hide ? "hidden" : "visible" ;
            }
        }
    }
    */
}
var visibleLayerCounter = 0;
function Layer(divId, width, height, create, content){
    if (!divId)
        return false;
    if (create){
        document.getElementById(create).innerHTML += "<div id = '" + divID + "' style = 'overflow:hidden; display: none; position:absolute; width: " + width + "px; height: " + height + "px'>" + content + "</div>";
    }
        
    var id = divId;             // ID of the layer
    this.attached = false;      // false or ID name of parent object
    this.whereAttached = false; // when attached, contains corner where layer should be attached to
    this.attachedX = false;     // attach layer to a absolute Pos
    this.attachedY = false;
    this.animate = true;        // animate layer or not
    this.aniDirY = 'DOWN';
    this.aniDirX = 'LEFT';
    this.width = width;
    this.height = height;
    this.visible = false;
    this.steps = 15;
    this.beforeShowJSCode = "o.style.display = 'block'; if (visibleLayerCounter == 0) hideFormElements(1); ";
    this.afterShowJSCode  = '';//"o.style.overflow = 'hidden'; ";
    this.beforeHideJSCode = '';//"o.style.overflow = 'hidden'; ";
    this.afterHideJSCode  = "o.style.display = 'none'; if (visibleLayerCounter == 0) hideFormElements(0); ";
    var timer = null;
    var curWidth = 0;
    var curHeight = 0;


    function getObject(){
        return document.getElementById ? document.getElementById(id) : false;
    }

    function substituteArgs(str, arg1){
        if (str.substring(0, str.indexOf('??'))){
            return str.substring(0, str.indexOf('??')) + arg1 + str.substring(str.indexOf('??') + 2);
        }
        return str;
    }

    this.attachTo = function(id, where){
        this.attached = id;
        if (where)
            this.whereAttached = where;
        else
            this.whereAttached = 'TOPLEFT';
    }

    this.attachToPos = function(x, y){
        this.whereAttached = 'POS';
        this.attachedX = x;
        this.attachedY = y;
    }

    this.getWidth = function(){
        o = getObject();
	return o ? o.offsetWidth : false;
    }

    this.getHeight = function(){
        o = getObject();
	return o ? o.offsetHeight : false;
    }

    this.getLeft = function(){
        o = getObject();
	return o ? parseInt(o.style.left) : false;
    }

    this.getTop = function(){
        o = getObject();
	return o ? parseInt(o.style.top) : false;
    }

    this.setWidth = function(width){
        this.width = width;
        if (this.visible){
            this.show();
        }
    }

    this.setHeight = function(height){
        this.height = height;
        if (this.visible){
            this.show();
        }
    }
    
    this.setDimensions = function(width, height){
        this.width = width;
        this.height = height;
        curWidth = this.getWidth();
        curHeight = this.getHeight();
        if (this.visible){
            this.show();
        }
    }
    
    this.setTop = function(top){
        o = getObject();
        o.style.top = top + 'px';
    }

    this.setLeft = function(left){
        o = getObject();
        o.style.left = left + 'px';
    }

    this.show = function(arg1){
	    o = getObject();
        if (this.visible && (this.width == this.getWidth()) && (this.height == this.getHeight())){ //nothing to do
            return;
        }

        //clearTimeout(layerTimer[id]);
        var pos = getRect(this.attached);
	    o.style.zIndex = (visibleLayerCounter + 2) * 1000;
        eval(substituteArgs(this.beforeShowJSCode, arg1));
        visibleLayerCounter++;

        var start = new Object();
        var target = new Object();

        start.width = curWidth;
        start.height = curHeight;
        target.width = this.width;
        target.height = this.height;

        switch (this.whereAttached){
            case 'TOPLEFT':
                start.x = pos.left - curWidth;
                start.y = pos.top;
            break;
            case 'TOPRIGHT':
                start.x = pos.left + pos.width;
                start.y = pos.top;
            break;
            case 'BOTTOMLEFT':
                start.x = pos.left - curWidth;
                start.y = pos.top + pos.height - curHeight;
            break;
            case 'BOTTOMRIGHT':
                start.x = pos.left + pos.width;
                start.y = pos.top + pos.height - curHeight;
            break;
            case 'POS':
                start.x = this.attachedX;
                start.y = this.attachedY;
            break;
        }

        switch (this.aniDirX){
            case 'RIGHT':
                target.x = start.x
            break;
            case 'LEFT':
            default:
                target.x = start.x - this.width;
            break;
        }

        switch (this.aniDirY){
            case 'UP':
                target.y = start.y - this.height;
            break;
            case 'DOWN':
            default:
                target.y = start.y;
            break;
        }

        if (this.animate){
            layerTimer[id] = transform(id, start.x, start.y, start.width, start.height, target.x, target.y, target.width, target.height, this.steps, substituteArgs(this.afterShowJSCode, arg1));
        }
        else{
            o.style.left = target.x + 'px';
            o.style.top = target.y + 'px';
            o.style.width = target.width + 'px';
            o.style.height = target.height + 'px';
            eval(substituteArgs(this.afterShowJSCode, arg1));
        }
        this.visible = true;
    }

    this.hide = function(arg1){
        if (!this.visible) //nothing to do
            return;
    	clearTimeout(layerTimer[id]);
        var pos = getRect(this.attached);
	    o = getObject();
  	    o.style.zIndex = (visibleLayerCounter) * 1000;
        curWidth = o.offsetWidth; // this.width;
        curHeight = o.offsetHeight;
        eval(substituteArgs(this.beforeHideJSCode, arg1));
        visibleLayerCounter--;
        var start = new Object();
        var target = new Object();

        start.width = curWidth;
        start.height = curHeight;
        target.width = 0;
        target.height = 0;

        switch (this.whereAttached){
            case 'TOPLEFT':
                target.x = pos.left;
                target.y = pos.top;
            break;
            case 'TOPRIGHT':
                target.x = pos.left + pos.width;
                target.y = pos.top;
            break;
            case 'BOTTOMLEFT':
                target.x = pos.left;
                target.y = pos.top + pos.height;
            break;
            case 'BOTTOMRIGHT':
                target.x = pos.left + pos.width;
                target.y = pos.top + pos.height;
            break;
            case 'POS':
                target.x = this.attachedX;
                target.y = this.attachedY;
            break;
        }

        switch (this.aniDirX){
            case 'RIGHT':
                start.x = target.x;
            break;
            case 'LEFT':
            default:
                start.x = target.x - curWidth;
            break;
        }

        switch (this.aniDirY){
            case 'UP':
                start.y = target.y - curHeight;
            break;
            case 'DOWN':
            default:
                start.y = target.y;
            break;
        }
        
        if (this.animate){
            layerTimer[id] = transform(id, start.x, start.y, start.width, start.height, target.x, target.y, target.width, target.height, this.steps, substituteArgs(this.afterHideJSCode, arg1));
        }
        else{
            o.style.left = target.x + 'px';
            o.style.top = target.y + 'px';
            o.style.width = target.width + 'px';
            o.style.height = target.height + 'px';
            eval(substituteArgs(this.afterHideJSCode, arg1));
        }
        
        this.visible = false;
        curWidth = 0; // this.width;
        curHeight = 0;
    }

    this.toggle = function(arg1){
        if (this.visible)
            this.hide(arg1);
        else
            this.show(arg1);
    }

}

var layers = new Object(); // used as layerarray
layers.loader = new Layer('load_layer', 300, 100);
layers.loader.aniDirY = "DOWN";
layers.loader.aniDirX = "RIGHT";

layers.messager = new Layer('msg_layer', 300, 100);
layers.messager.aniDirY = "DOWN";
layers.messager.aniDirX = "RIGHT";

///////////////////////////////////////////////////////////////////////////////
function substring(STRING,len){
var tail="";
if(len==null)len=16;
if(STRING.length<=len)len=STRING.length;
else tail="...";
return STRING.substring(0,len)+tail;
}

function firstUpper(instr){
	thestr=instr.toLowerCase();
    retStr="";
    nextupper=false;
    for(i=0;i<thestr.length;i++){
    	if(i==0){
        	retStr=thestr.substring(0,1).toUpperCase();
        }else{
            if(nextupper){
            	retStr+=thestr.substring(i,i+1).toUpperCase();
                nextupper=false;
            }else{
                retStr+=thestr.substring(i,i+1);
            }
        }
        if(thestr.substring(i,i+1)==" "){
            nextupper=true;
        }
    }
    return retStr;
}

function Trim(STRING){
if(STRING==null)return "";
STRING=STRING.replace(/&nbsp;/g," ");
STRING=STRING.replace(/\n/g,"");
STRING=STRING.replace(/\r/g,"");
if(STRING=="null")return "";
STRING = LTrim(STRING);
return RTrim(STRING);
}

function RTrim(STRING){
while(STRING.charAt((STRING.length -1))==" "){
STRING = STRING.substring(0,STRING.length-1);
}
return STRING;
}

function LTrim(STRING){
while(STRING.charAt(0)==" "){
STRING = STRING.replace(STRING.charAt(0),"");
}
return STRING;
}
function arry2string(strs) {
	var str = "";
	if (strs.length == null) {
		str = strs.value;
	} else {
		for (var i = 0; i < strs.length; i+=1) {
		if (i != strs.length - 1) {
			str += strs[i].value + ",";
		} else {
			str += strs[i].value;
		}
		}
	}
	return str;
}
function checkboxarry2string(strs) {
	var str = "";
	if (strs.length == null) {
		if (strs.checked) {
			str = strs.value;
		}
	} else {
		for (var i = 0; i < strs.length; i+=1) {
			if (strs[i].checked) {
				str += strs[i].value;
				if (i != strs.length - 1) {
					str += ",";
				}
			}
		}
	}
	return str;
}
function newWindow(winname,width,height){
	if(width==null)
		width=800;
	if(height==null)
		height=640;
    window.open(winname, 'newWinpop', 'width='+
    	width+',height='+
    	height+',scrollbars=1,menubar=0,toolbar=0,location=0,status=0,resizable=1');
}

function money(number,round){
if (round==null)round=true;
if (round)
	number = forDight(number,2);
var doc=-1;
var STRING=number+"";
for(var i=0;i<(STRING.length-1);i+=1){
	if(STRING.charAt(i)=="."){
		doc=i;
		break;
	}
}
if(doc==-1){
	STRING+=".00";
}else if(doc==(STRING.length-2)){
	STRING+="0";
}
return STRING;
}
function forDight(Dight,How){
	var Dight = Math.round(Dight*Math.pow(10,How))/Math.pow(10,How);
	return Dight;
}
function parseXML(xml) {
	var dom;
	try{
		if (window.ActiveXObject){
			dom = new ActiveXObject("Microsoft.XMLDOM");
			dom.async = false;
			dom.loadXML(xml);
		} else if (document.implementation&&document.implementation.createDocument){
			dom = document.implementation.createDocument("","",null);
			dom.async = false;
			dom.load(xml);
		}
	} catch (error) {
		try{
			var parser = new DOMParser();
			dom = parser.parseFromString(xml, "text/xml");
			delete parser;
		} catch (error2) {
			if(debug){alert("XML parsing is not supported.");}
		}
	}
	return dom;
}
function filtrate(txt){
//if (txt.indexOf('www')>=0){return "";}
txt = txt.replace(/\n/g, "<br/>");
txt = txt.replace(/ /g, "&nbsp;");
return txt;
}
function show(node, c){
	if (node.hasChildNodes()) {
	for (var i=0; i<node.childNodes.length; i++) {
		var childNode = node.childNodes[i];
		alert(c+":"+childNode.nodeName+"="+childNode.nodeValue);
		show(childNode, c+1);
    }
    }
}
function showObj(obj){
	var str = "";
	for (var prop in obj) {
		str += prop + ":" + obj[prop] + "<br/>";
	}
	return str;
}
function error(doc){
	var err = "";
	msg = doc.getElementsByTagName("LIST_MSG");
	for (var i=0;i<msg.length;i++){
		err += msg[i].getElementsByTagName("TEXT")[0].text+"<br/>";
	}
	return err;
}
function sleep(y){if(y<=0)y=12;for(var z=0;z<y*999;z++){;}}
function showimgs(div, doc){
	var m = doc.getElementsByTagName("MULTIMEDIA_DETAILS")[0];
	var c = m.getElementsByTagName("LIST_CATEGORIES");
	var count=0;
	for (var i=0;i<c.length;i+=1){
		var imgs = c[i].getElementsByTagName("LIST_IMAGES");
		for (var j=0;j<imgs.length;j+=1){
			var url = getimage(imgs[j]);
			var bigurl = getbigimage(imgs[j]);
			var newImage = document.createElement("<img src=\""+url+"\" width=150 height=105 alt=\"<img border='0' src='"+bigurl+"'>\"/>");
			div.appendChild(newImage);
			div.appendChild(document.createTextNode(" "));
			sleep(60-count*20);
			count+=1;
		}
	}
	showMULTIMEDIA_MARKETING(div,doc);
	return count;
}
function showHotelEXTIMG(div, doc){
	var m = doc.getElementsByTagName("MULTIMEDIA_DETAILS")[0];
	var c = m.getElementsByTagName("LIST_CATEGORIES");
	var count=0;
	for (var i=0;i<c.length;i+=1)
		if(c[i].getElementsByTagName("CODE")[0].text==='EXT'){
			var imgs = c[i].getElementsByTagName("LIST_IMAGES");
			for (var j=0;j<imgs.length;j+=1){
				var url = getimage(imgs[j]);
				var newImage = document.createElement("<img src=\""+url+"\" width=\"90\" height=\"67\"/>");
				div.innerHTML="";
				div.appendChild(newImage);
				div.appendChild(document.createTextNode(" "));
				sleep(60-count*20);
				count+=1;
				break;
			}
		}
	return count;
}
function getbigimage(node){
	var imgsize = node.getElementsByTagName("LIST_IMAGES_SIZES");
	var i=0;
	for (var j=0;j<imgsize.length;j+=1){
		var width = imgsize[j].getElementsByTagName("WIDTH")[0].text;
		//height = imgsize[j].getElementsByTagName("HEIGHT")[0].text;
		if(Number(width)>=Number(imgsize[i].getElementsByTagName("WIDTH")[0].text))
			i=j;
	}
	return imgsize[i].getElementsByTagName("URL")[0].text;
}
function getimage(node){
	var imgsize = node.getElementsByTagName("LIST_IMAGES_SIZES");
	for (var j=0;j<imgsize.length;j+=1){
		var width = imgsize[j].getElementsByTagName("WIDTH")[0].text;
		//height = imgsize[j].getElementsByTagName("HEIGHT")[0].text;
		if(Number(width)>=150)return imgsize[j].getElementsByTagName("URL")[0].text;
	}
}
function getMULTIMEDIA_DETAILS(doc){
	return doc.getElementsByTagName("MULTIMEDIA_DETAILS")[0];
}
function showMULTIMEDIA_MARKETING(div, doc){
	var m=getMULTIMEDIA_DETAILS(doc).getElementsByTagName("MULTIMEDIA")[0];
	if(m==null)return;
	var t=m.getElementsByTagName("MARKETING_TEXT")[0];
	if(t==null)return;
	//t.getElementsByTagName("LONG_TEXT");
	var s=t.getElementsByTagName("SHORT_TEXT")[0];
	if(s==null)return;
	div.innerHTML+="<br/>"+s.text;
}
function getLeft(e){
  var ret=e.offsetLeft
  while(e=e.offsetParent)ret+=e.offsetLeft
  return ret;
}

function getTop(e){
  var ret=e.offsetTop
  while(e=e.offsetParent)ret+=e.offsetTop
  return ret;
}

function showBookingReason(){
	bookingsearchhelper.getReasonCodeList(showBookingReason1);
}
function showBookingReason1(data){
	var str = $('reasoncode').innerHTML.replace(/&nbsp;/g,"");
	if (str=="") {
		var select="";
		for(var i=0;i<data.length;i+=1){
			select+="<option value='"
				+data[i].reason_code
				+"'>"
				+data[i].reason_id_code
				+"</option>";
		}
		$('reasoncode').innerHTML="<select name='reasoncode'>"
			+select+"</select>";
	} else {
		for (var i=0;i<data.length;i+=1) {
			AddItem($("reasoncodeid"),data[i].reason_id_code,data[i].reason_code);
		}
	}
}

function showCurrency(){
	useLoadingMessage();
	bookingsearchhelper.getCurrencyCodeList(showCurrency1);
}
function showCurrency1(data){
	var select='<option value="USD">USD</option><option value="EUR">EUR</option><option value="CAD" selected>CAD</option><option value="-">---</option>';
	for(var i=0;i<data.length;i+=1){
		select+="<option value='"
			+data[i].currency_code
			+"'>"
			+data[i].currency_code
			+"</option>";
	}
	$('currencycode').innerHTML="<select name='currencycode'>"
			+select+"</select>";
}

function showAffiliate(affiliateid,userid){
	if (affiliateid==null)
		affiliateid=getAffiliateID();
	if (userid==null)
		userid=getUserID();
	affiliate.listByUser(affiliateid,userid,showAffiliate1);
}

function showAffiliate1(data){
	var str = $('affiliate').innerHTML.replace(/&nbsp;/g,"");
	if (str==""){
		var select='';
		for(var i=0;i<data.length;i+=1){
			select+="<option value='"
				+data[i].affiliate_id
				+"'>"
				+data[i].affiliate_username
				+"</option>";
		}
		$('affiliate').innerHTML="<select name='affiliate'>"
				+select
				+"</select>";
	}else{
		for(var i=0;i<data.length;i+=1){
			AddItem($("affiliateid"),data[i].affiliate_username,data[i].affiliate_id);
		}
	}
}

function showAffiliate2(data){
	$('affiliate').innerHTML="<input type='hidden' name='affiliate' value='"+
		data.affiliate_id+"'>"+data.affiliate_username;
}
function showSupplier1(data){
	var select='';
	for(var i=0;i<data.length;i+=1){
		select+="<option value='"
				+data[i].supplier_id
				+"'>"
				+data[i].supplier_name
				+"</option>";
	}
	$('tdsupplier').innerHTML="<select name='supplier'>"
			+select
			+"</select>";
}
var curr_selected_country = null;
var curr_selected_state   = null;

function showCountry1(data){
	var select='';
	for(var i=0;i<data.length;i+=1){
		select+="<option value='"+data[i].shortname+"'>"+
			substring(firstUpper(data[i].name.toLowerCase()),20)+"</option>";
	}
	$('country').innerHTML="<select id='selcountry' name='country' onchange='useLoadingMessage();province.getStateList(this.value,showState1)'><option value=''>Select Country</option>"+
		select+"</select>";
	if (curr_selected_country!=null){
    	for(var i=0;i<$("selcountry").options.length;i++){
        	if ($("selcountry").options[i].value==curr_selected_country){
        		useLoadingMessage();
        		province.getStateList(curr_selected_country,showState1);
				$("selcountry").selectedIndex=i;
				break;
    		}
    	}
    }
}
function showState1(data){
	var input="<input type='text' name='state' value='' size='20' maxlength='24'/>";
	if(data!=null&&data.length>0){
		input='';
		for(var i=0;i<data.length;i+=1){
			input+="<option value='"+data[i].shortname+"'";
			if (curr_selected_state!=null && data[i].shortname==curr_selected_state)
				input+=" selected";
			input += ">"+substring(firstUpper(data[i].name.toLowerCase()),20)+"</option>";
		}
		input="<select name='state'><option value=''></option>"+input+"</select>";
	}
	$('state').innerHTML=input;
}
function showContractType(data){
	var str="";
	for(var i=0;i<data.length;i++){
		str+="<option value='"+
		 data[i].typeid+"'>"+
		 data[i].typename+"</option>";
	}
	$('contracttype').innerHTML="<select name='contract_type'><option value='-1'>All</option>"+
	str+"</select>";
}
function getUserID(){
	var user_id=getCookie('user_id');
	if (user_id==null||user_id==""){
		return null;
	}
	return user_id;
}
function getAffiliateID(){
   	var affiliate_id=getCookie('affiliate_id');
	if (affiliate_id==null||affiliate_id===""){
		alert("Can't get user's affiliate id!");
		return null;
   	}
   	return affiliate_id;
}
function setCheckboxValue(setvalue) {
	if($('searchHotel')==null)return;
	if($('searchHotel').fromsearchform==null)return;
	$('searchHotel').fromsearchform.value=setvalue;
}
function getCityCodeInput(affiliateid,divname,view){
	if(3==affiliateid){
	$(divname).innerHTML="<div class='layer'><input type=radio name='icaoIataType' value='0' checked>ICAO<input type=radio name='icaoIataType' value='1'>IATA</div>Airport Code: <input type=text name='icaoIataCode' value='' size=5 maxlength=16 onclick=\"setCheckboxValue('1');\"/>";
	}else{
	$(divname).innerHTML="<div class='layer'><input type=radio name='icaoIataType' value='0'>ICAO<input type=radio name='icaoIataType' value='1' checked>IATA</div>Airport/City Code: <input type=text name='icaoIataCode' value='' size=5 maxlength=16 onclick=\"setCheckboxValue('1');\"/>";
	}
	if (view)
	$(divname).innerHTML+=" <a href='javascript:searchLocation()'>view</a>";
}
function getCityCode(affiliateid,divname){
	if(3==affiliateid){
	$(divname).innerHTML="<div class='layer'><input type=radio name='icaoIataType' value='0' checked>ICAO<input type=radio name='icaoIataType' value='1'>IATA</div>Airport Code:";
	}else{
	$(divname).innerHTML="<div class='layer'><input type=radio name='icaoIataType' value='0'>ICAO<input type=radio name='icaoIataType' value='1' checked>IATA</div>Airport/City Code:";
	}
}
function showCityCode(affiliateid){
	if(3==affiliateid){
		return "Airport Code";
	}else{
		return "Airport/City Code";
	}
}
function getCompanyID(){
   	var company_id=getCookie('company_id');
   	company_id=1;
	if (company_id==null||company_id===""){
		alert("Cann't get user's company id!");
		return null;
   	}
   	return company_id;
}
function getSupplierID(){
   	var supplier_id=getCookie('supplier_id');
   	supplier_id=1;
	if (supplier_id==null||supplier_id===""){
		alert("Cann't get user's supplier id!");
		return null;
   	}
   	return supplier_id;
}
function getBookingFrom(){return 9;}
function getSourceFrom(){return "bookdirect";}
function getCrewfrom(){return 1;}

var Transportation = new HashMap();
Transportation.put("B", "Boat");
Transportation.put("C", "Coach");
Transportation.put("E", "Express train");
Transportation.put("F", "Free transport");
Transportation.put("H", "Helicopter");
Transportation.put("L", "Limousine");
Transportation.put("P", "Plane");
Transportation.put("R", "Rental car");
Transportation.put("T", "Taxi");
Transportation.put("U", "Underground");
Transportation.put("W", "Walking distance");

	// utility function to retrieve an expiration data in proper format;
    function getExpDate(days, hours, minutes)
    {
        var expDate = new Date();
        if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) == "number")
        {
            expDate.setDate(expDate.getDate() + parseInt(days));
            expDate.setHours(expDate.getHours() + parseInt(hours));
            expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
            return expDate.toGMTString();
        }
    }

    //utility function called by getCookie()
    function getCookieVal(offset)
    {
        var endstr = document.cookie.indexOf(";", offset);
        if(endstr == -1)
        {
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    }

    // primary function to retrieve cookie by name
    function getCookie(name)
    {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while(i < clen)
        {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg)
            {
                return getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if(i === 0) {break;}
        }
        return;
    }

    // store cookie value with optional details as needed
    function setCookie(name, value, expires, path, domain, secure)
    {
        document.cookie = name + "=" + escape(value) +
            ((expires) ? "; expires=" + expires : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
    }

    // remove the cookie by setting ancient expiration date
    function deleteCookie(name,path,domain) 
    {
        if(getCookie(name))
        {
            document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    }
//
function HashMap()
{
    var size = 0;
    var entry = new Object();

    this.put = function (key , value)
    {
        if(!this.containsKey(key))
        {
            size ++ ;
        }
        entry[key] = value;
    }

    this.get = function (key)
    {
        return this.containsKey(key) ? entry[key] : null;
    }

    this.remove = function ( key )
    {
        if( this.containsKey(key) && ( delete entry[key] ) )
        {
            size --;
        }
    }

    this.containsKey = function ( key )
    {
        return (key in entry);
    }

    this.containsValue = function ( value )
    {
        for(var prop in entry)
        {
            if(entry[prop] == value)
            {
                return true;
            }
        }
        return false;
    }

    this.values = function ()
    {
        var values = new Array();
        for(var prop in entry)
        {
            values.push(entry[prop]);
        }
        return values;
    }

    this.keys = function ()
    {
        var keys = new Array();
        for(var prop in entry)
        {
            keys.push(prop);
        }
        return keys;
    }

    this.size = function ()
    {
        return size;
    }

    this.clear = function ()
    {
        size = 0;
        entry = new Object();
    }
}
