//Javascript for tracking
//----------------------------------------
//Naming convention of javascript function
//----------------------------------------
//1. wf_[function name] - wf means windows function which includes all functions in a form
//2. gf_[ function name] - gf means global funciton which includes all functions in a seperate .js file 
//

//open a new window in middle of the screen

var	centerX = screen.width/2;
var centerY = screen.height/2;
var wHeight, wWidth, setLeft, setTop;

//To check whether a value is null and display the error message when null is true
function isNull(inValue, msg){
 if (inValue == ''){
    alert (msg);
    return true;
  }
  else {
    return false;
  }
}

//Check whether a value is a number
function isNumeric(objNum, msg){

  //objNum = document.form1.f_license_no;
  //msg = "License no.";
  
  var numStr = objNum.value;
  var numPat = /[A-Za-z]/;
  
  //alert("pat: " + numStr.match(numPat));
  
  if(numStr == ""){
    return true;
  }
  else if(numStr.match(numPat)!=null){
      alert(msg + " should be numbers only");
      objNum.focus();
      objNum.select();
      return false;
  }
  else {
    return true;
  }
}


function go(){

  history.back(-3);

}


//-- Date and Time --


//Open calendar
function openCal(objChange){
  window.open("/tracking/web/common/calendar.asp?objChange=" + objChange + "", "cal", "height=400,width=300,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=50,top=50");
}


function openCalx(objChange){
	wWidth = 300
	wHeight = 300
	setLeft = centerX - (wWidth / 2);
	setTop = centerY - (wHeight / 2);

	//alert("/tracking/web/common/calendar.asp?objChange=" + objChange + "");
	window.open("/tracking/web/common/calendar.aspx?objChange=" + objChange + "", "cal", "height=300,width=300,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left="  + setLeft + ",top=" + setTop );
   //window.open("/tracking/web/common/calendar.asp?objChange=" + objChange + "", "cal", "height=300,width=300,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left="  + setLeft + ",top=" + setTop);
}


//Fill in an object
function checkDate(dataField){

    if(dataField.value == "") { return true; }

    var datestr = dataField.value;
    var re = /-/g;
    datestr = datestr.replace(re, "\/");

    var myyear = datestr.substring( 0, 4 );
    var mymonth = datestr.substring( datestr.indexOf("/") + 1, datestr.lastIndexOf("/") );
    var mydate = datestr.substring( datestr.lastIndexOf("/") + 1, datestr.length );
    var tday = new Date(myyear + '/' + mymonth + '/' + mydate);

    datestr = myyear + '/'; 
    datestr += ( ( mymonth.length == 1 )?mymonth = "0"  + mymonth:mymonth ) + '/'; 
    datestr += ( mydate.length == 1 )?mydate = "0" + mydate:mydate;
    //alert("datestr: " + datestr);

    var datePat=/([0-9]{4,})\/([0-9]{2,})\/([0-9]{2,})/;

    var matchArr=datestr.match(datePat);

      if ( matchArr==null ) {
        alert("The date format should be yyyy-mm-dd");
        dataField.focus();
        return false;
      }
      else if( datestr.substring(0,4) < 1900 || datestr.substring(0,4) > 3000 ){
        alert("The year is out of range");
        dataField.focus();
        return false;
      }
      else if( datestr.substring(5,7)>12 ){
        alert("The month is out of range");
        dataField.focus();
        return false;
      }
      else if( datestr.substring(8,10)>31 ){
        alert("The date is out of range");
        dataField.focus();
        return false;
      }
      else{
        if ( myyear != tday.getFullYear() || 
        	 mymonth - 1 != tday.getMonth() || 
        	 mydate != tday.getDate() ){
            alert ('The date is invalid.');
            dataField.focus();
            return false;
        }
        return true;
      } 
}


function adddate(days, dateObj){
//Add an amount of days from the input date object

  var theSec, yr_num="", m_num, yy, mm;
  odate = new Date();
 
  //Calculate the milliseconds of new date
  theSec = Date.parse(dateObj) + (days * 24 * 60 * 60 * 1000);
  odate.setTime(theSec);
  
  yr_num = odate.getYear()+"";
  yr_num = yr_num.substring(yr_num.length-2, yr_num.length);
  
  yy = yr_num;

  if(yy < 60){
    yr_num = '20' + yr_num;
  }
  else {
    yr_num = '19' + yr_num;
  }
  
  return yr_num  + '-' + addZero(odate.getMonth()+1) + '-' + addZero(odate.getDate());
}



//Check time format of time
function isTimeFormat(objTime, msg){

  //objTime = document.form1.f_cargo_avali_time;
  //var msg = "Cargo avaliable time";

  if(objTime.value == ""){
	return true;
  }

  //var timePat=/([0-9]{2,}):([0-9]{2,}):([0-9]{2,})/;
  var timePat=/([0-9]{2,}):([0-9]{2,})/;
  var timeStr=objTime.value;
  
  //alert("pattern: " + timeStr.match(timePat) );
  //alert("hours: " + timeStr.substring(0,2));

  if(timeStr.match(timePat)==null){
    alert("The format of " + msg + " should be hh:mm");
    objTime.focus();
    return false;
  }
  
  //Check no. of hours
  else if(timeStr.substring(0,2) > 24){
     alert("Hours of " + msg + " cannot be greater than 24");
     objTime.focus();
  }
  
  //Check no. of minutes
  else if(timeStr.substring(3,5) > 60){
     alert("Minutes of " + msg + " cannot be greater than 60");
     objTime.focus();    
  }
  
  /*else if(timeStr.substring(6,8) > 60){
     alert("Seconds of " + msg + " cannot be greater than 60");
     objTime.focus();    
  }*/
  
  else{
    return true;
  }
  
  //Check time number
 
}



//Add a zero dight in datetime
function addZero(num){
  num = "" + num;
  if (num.length<=1){ num = "0" + num;}
  return num;
}


// -- Handle Pop-up Windows --
// This will direct the page to the port selection page
function selectport(type, port){
  wWidth = 500
  wHeight = 405
  setLeft = centerX - (wWidth / 2);
  setTop = centerY - (wHeight / 2);
  
  window.open("/tracking/web/common/select_port.asp?from_port=" + escape(type) + "&port_name=" + escape(port), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}
function selectVslname(objChange, strVslvoy){
  wWidth = 500
  wHeight = 405
  setLeft = centerX - (wWidth / 2);
  setTop = centerY - (wHeight / 2);

	window.open("/tracking/web/common/select_vesselname.asp?objChange=" + objChange + "&f_vslvoy_uid=" + escape(strVslvoy), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}

function selectVslvoy(objChange, strVslvoy){
  wWidth = 500
  wHeight = 405
  setLeft = centerX - (wWidth / 2);
  setTop = centerY - (wHeight / 2);

	window.open("/tracking/web/common/select_vslvoy.asp?objChange=" + objChange + "&f_vslvoy_uid=" + escape(strVslvoy), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}

function selectStatus(objChange, strStatus){
  wWidth = 500
  wHeight = 405
  setLeft = centerX - (wWidth / 2);
  setTop = centerY - (wHeight / 2);
	window.open("/tracking/web/common/select_status.asp?objChange=" + objChange + "&f_status=" + escape(strStatus), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}

function selectStatus1(objChange, strStatus){
  wWidth = 500
  wHeight = 405
  setLeft = centerX - (wWidth / 2);
  setTop = centerY - (wHeight / 2);
	window.open("/tracking/web/common/select_status1.asp?objChange=" + objChange + "&f_status=" + escape(strStatus), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}

//Select Shipper Consignee
function selectShprCnee(sch_type, usr_code, value, nature){
   wWidth = 500
   wHeight = 405
   setLeft = centerX - (wWidth / 2);
   setTop = centerY - (wHeight / 2);
   var url = "/tracking/web/common/select_shprcnee.asp?sch_type=" + escape(sch_type);
	   	url+= "&usr_code=" + escape(usr_code);
   		url+= "&value=" + escape(value);
        if ( nature != null )
			   	url+= "&nature=" + nature;
	window.open(url, "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left=" + setLeft + ",top=" + setTop);
}

//Select Export Job
function selectExJob(usr_code, value){
	wWidth = 500
   wHeight = 405
   setLeft = centerX - (wWidth / 2);
   setTop = centerY - (wHeight / 2);
	window.open("/tracking/web/common/select_exjob.asp?usr_code=" + escape(usr_code) + "&value=" + escape(value), "code_win","height=405,width=500,alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0,left="  + setLeft +  ",top=" + setTop);
}


// For data checking, this will pop up an error message window. When user close the window, the cursor will go back to the error field
function errorMsg(strMsg, objForm){

  var top_pos = screen.height/2 - 50;
  var left_pos = screen.width/2 - 50;

  property = 'top='+ top_pos +',left='+ left_pos +',width=200,height=200,scrollbars=no,status=no,toolbar=no,resizable=1,location=no,menu=no';
  url = '/booking/htdoc/help/check_popup.asp?msg=' + escape(strMsg) + '&value=' + escape(objForm)

  window.open(url,'error',property);
  history.back(1);
  
}



//Check if the value of textfield is not 0, then do not allow the checkbox to be false
function isValueZero(objCheckbox, objTextfield){
//alert("test" + document.form1.f_req_license_no.checked);
  //objCheckbox=document.form1.f_req_license_no;
  //objTextfield=document.form1.f_license_no;

  if(objCheckbox.checked==false && (objTextfield.value != "0") ){
      alert("The value of the right field should be 0");
      objCheckbox.checked=true;
  }
  else{
    objTextfield.focus();
  }

}


//Automatically change the value of checkbox according to the text field
function autoChecked(objCheckbox, objTextfield){
//alert("test" + document.form1.f_req_license_no.checked);

  //objCheckbox=document.form1.f_req_license_no;
  //objTextfield=document.form1.f_license_no;
  if(objTextfield.value == "" || objTextfield.value == "0"){
      objCheckbox.checked=false;
  }
  else{
    objCheckbox.checked=true;
  }

}


//Input an object to check it's email
function emailCheck (ind) {
	var emailStr 
	emailStr = ind.value;
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var	quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		alert("Invalid email address")
		ind.focus();
		ind.select();	
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	if (user.match(userPat)==null) {
		alert("Invalid username.")
		ind.focus();
		ind.select();	
	    return false
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!")
				ind.focus();
				ind.select();	
				return false
			}
	    }
		return true
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Invalid email address.")
		ind.focus();
		ind.select();	
		return false
	}

	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
		alert("The address must end in a three-letter domain, or two letter country.")
			ind.focus();
			ind.select();	
		   return false
	}
	if (len<2) {
		var errStr="This address is missing a hostname!"
		alert(errStr)
		ind.focus();
		ind.select();	
		return false
	}
	return true;
}



//Check string length
function isVaildLen(objIn, msgField, numFrom, numTo){
	//objIn = document.form1.f_login
	//numFrom = 6;
	//numTo = 10;
	//msgField = "login name";

	strIn = objIn.value;
	if (strIn.length < numFrom || strIn.length > numTo) {
	  alert("The length of " + msgField + " should be within " + numFrom + " to " + numTo);
	  objIn.focus();
	  return false;
	}
	else{
	  return true;
	}
	
}	


//Redirect page after a period of time
function redirect(url){
//alert("Your registration has been sent");
document.location.href = url;
}

function setRedirect(url){
setTimeout('redirect(' + url + ')',3000)
}
	


function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
          offset += search.length
          // set index of beginning of value
          end = document.cookie.indexOf(";", offset)
          // set index of end of cookie value
         if (end == -1)
             end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      }
    }
}



//Check whether pages are saved in add new mode
function checkSavedPage(mode){
	
	if(mode == '1') { // When user click general
		msg = "\nAre you sure you want to quit?";

	}else {
		msg = "\nAre you sure you want to finish?";

	}
	
	

	if (getCookie("special") == "false") {
		if(!confirm("You have not saved the information in special. " + msg)){
			return false;
		}
	}

	if (getCookie("marksndesc") == "false") {
		if(!confirm("You have not saved the information in marks and description. " + msg)){
			return false;
		}
	}

	if (getCookie("container") == "false") {

		if(!confirm("You have not saved the information in container. " + msg)){
			return false;
		}
	
	}
	
	if (getCookie("podetail") == "false") {
	
		if(!confirm("You have not saved the information in PO detail. " + msg)){
			return false;
		}
		
	}
	
	return true;

}


function checkIsFinished() {

	if(!confirm("Are you sure you want to leave the adding mode?")){
			return false;
	}
	return true;
}


//open a new window in middle of the screen
function gf_openNewWin(theURL,winName,features, height, width)
{
//Arguements:
//features 	- if you pass one word instead of a long string, the program can handle it case by case
//				and place the window in the center of the screen
//
//height	- Pass	'0' for width and height when screen is not fixed by programmer
//width		- Pass	'0' for width and height when screen is not fixed by programmer
//			- if height and width is provided, the screen will be displayed in the center of the screen
//Example:
//gf_openNewWin("http://myurl/myfile","mywin","height=100,width=100")				 //Normal use, all setting set by user
//gf_openNewWin("http://myurl/myfile","mywin","screenX=0,screeny=0", "100", "100") //Automatically set position and manually set attributes
//gf_openNewWin("http://myurl/myfile","mywin","print", "", "")					 //Use the printing window setting in this function
 
 	var setLeft, setTop;
	var setting = features;
	var setsize;

	//Not a nomral call, use pre set setting
	if(height!=null && width!=null)
	{
		switch(setting)
		{
			//case "browse":
			//	setting = "alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=1,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0";
			//break;
			case "print":
				wWidth=screen.width*0.98;
				wHeight=screen.height*0.8;
				setting = "alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=1,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0";
				//alert("wWidth=" + wWidth + " " +  "wHeight=" + wHeight);
			break;
			default:
				wWidth = parseInt(width);
				wHeight = parseInt(height);
				//setting = "alwaysLowered=0,alwaysRaised=0,channelmode=0,dependent=1,directories=0,fullscreen=0,hotkeys=1,location=0,menubar=0,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0,z-lock=0,screenX=0,screeny=0";
		}

		//Set the window position
		setLeft = centerX - (wWidth / 2);
		setTop = centerY - (wHeight / 2);
		setTop = parseInt(setTop) - 10;
		if(parseInt(setTop) < 0) setTop = 0;

		//Concat all strings as the setting string
		setsize = "height=" + wHeight + ",width=" + wWidth;
		setsize += ",left=" + setLeft + ",top=" + setTop;

		setting = (setting!="")?setsize + "," + setting:setsize;
	}
	//Open new window
	window.open(theURL,winName,setting);
}
