var flagSpaceEnter = false;//3DTrack add start
var brandText = "";
var focusOnAWB = false;
var showRed = false;
var flpleaseSelectRed = false;
var awbs = null;
var awbsLength = 0;//3DTrack add End
var def_tracking="1.0";
var errorStrings=new Array();
var reasonForReject = "";
var reasonForSuccess = "";
var newAWB = null;


//3DTrack Start Changes
errorStrings['noNumbs']   =new Array( track3d_msg007,track3d_msg008 );
errorStrings['tooMany']   =new Array( track3d_msg009,comm_msg039 + track3d_msg003, track3d_msg004 );
//errorStrings['singInvalid'] =new Array( comm_msg016, comm_msg014, tracking_msg004 + "<br /><br />" + comm_msg019 + comm_msg021 );
errorStrings['singInvalid'] =new Array( comm_msg096, comm_msg099, tracking_msg032 + "<br /><br />" + comm_msg019 + comm_msg021 );
//errorStrings['multInvalid'] =new Array( comm_msg016, comm_msg018, tracking_msg005 + "<br /><br />" + comm_msg019 + comm_msg020 );
errorStrings['multInvalid'] =new Array( comm_msg096, comm_msg097, tracking_msg030 + "<br /><br />" + comm_msg019 + comm_msg020 );
errorStrings['cannotBeZero'] =new Array( track3d_msg011, track3d_msg012 + track3d_msg013);
errorStrings['duplicateawbs'] =new Array( track3d_msg005, track3d_msg006 + track3d_msg013);
errorStrings['tooManyDanzas']   =new Array( track3d_msg009,comm_msg039 + track3d_msg010 );
errorStrings['selectType']   =new Array( track3d_msg001, track3d_msg002 );
errorStrings['awbpiecemix']   =new Array( comm_msg098,tracking_msg031 +"<br /><br />" + tracking_msg037);
//3DTrack End Changes

function fnFocusOnAWB()
{
  focusOnAWB = true;
}
function fnBlurOnAWB()
{
  focusOnAWB = false;
}

function trackingAlert( stringId, insert )
{ 
 flagSpaceEnter = false;
 document.forms["trackingIndex"].AWB.focus();
 eName = errorStrings[stringId][0];
 eText1 = errorStrings[stringId][1];
 eText2 = errorStrings[stringId][2];
 eHeight = errorStrings[stringId][3];
 eWidth = errorStrings[stringId][4];
 if( typeof( def_dhlAlert ) != "undefined" )
 {
  dhlAlert( eName, eText1+((insert)?" "+insert+((eText2)?" "+eText2:""):""), eWidth, eHeight );
 }
 else
 {
  alert( eName+"\n"+eText1+" "+insert+" "+eText2 );
 }
}

function trackingMixAlert( stringId, stringval )
{ 
	
 flagSpaceEnter = false;
 document.forms["trackingIndex"].AWB.focus();
 eName = errorStrings[stringId][0];
 eText1 = errorStrings[stringId][1];
 eText2 = errorStrings[stringId][2];
 eHeight = errorStrings[stringId][3];
 eWidth = errorStrings[stringId][4];
 if( typeof( def_dhlAlert ) != "undefined" )
 {
  dhlAlert( eName, stringval, eWidth, eHeight );
 }
 
}

function strip( instring )
{
 var outstring="";
 var bit="";
 var founddigit=false;
 for( j=0;j<instring.length;j++ )
 {
  c=instring.charAt(j);
  if( c != "," && c != " " && c !="\t" && c !="\n"  && c !="\r" )
  {
   if( founddigit == true )
   {
    outstring+=bit;
   }
   bit="";
   outstring+=c;
   founddigit=true;
  }
  else if( founddigit == true )
  {
   bit+=c;
  }
 }
 return outstring;
}

function isZeroValue()
{
  for( i=0 ; i < awbsLength ; i++ )
  {
    if( parseInt( awbs[i] ) == 0 )
    {
      return true;
    }
  }
}

function isDuplicate()
{
  for( i=0 ; i< awbsLength - 1 ; i++ )
  { 
    awbs[i] = awbs[i].replace(/\s+/g,'');
    awbs[i] = fnTrim(awbs[i], 2);
    for( j=(i+1) ; j< awbsLength ; j++ )
    {
	  awbs[j] = fnTrim(awbs[j], 2);
	  if(awbs[i].length !=0 && awbs[j].length !=0 )
   	  {
	      if (awbs[i] == awbs[j])
	      {
	        return true;
	      }
	  }
    }
  }
  return false;
}

function isValidDHLAWB(awbNum)
{
  awbNum = fnTrim(awbNum, 2);
  //awbNum = awbNum.replace(/\s+/g,'');
  //awbNum = awbNum.replace(/[^a-zA-Z0-9]+/g,'');
  if(isNaN( awbNum ))
  {
    //alert(" this is string !!! Invalid AWB..go for piece id validation");
    return false;
  }
  if (awbNum.length != 10 )
  {
    return false;
  }
  check1=awbNum.substring(9,10);
  tocheck=awbNum.substring(0,9);
  check2=tocheck % 7;
  if( check1 != check2  && awbNum != "" )
  {
    return false;
  }
  return true;
}

function fnDHL(form)
{
  var finalPieceStr  = "";
  var trimmedPid     = "";
  var upperCasePid   = "";
  errors="";
  var isAwbFound = false;
  var isPieceFound = false;
  var invalidEntryFound = false;
  var errorMessage = "";
  var newline = "<br>";
  var space   = " ";

  if ( (awbsLength > 10) || ((flagSpaceEnter) && (awbsLength==10)) )
  {
    trackingAlert( "tooMany", brandText+"s." );
    return false;
  }
  for (i=0;i<awbsLength;i++)
  {
    
  awbs[i] = awbs[i].replace(/\s+/g,'');
  if( awbs[i].length !=0)
  {

	    if (!isValidDHLAWB(awbs[i]))
	    {
	      if(!validatePieceid(awbs[i]))
	        {
			  var pieceIdLen = awbs[i];
			  if(pieceIdLen.length != 0)
			  {
			  		invalidEntryFound = true;
			  		errorMessage = errorMessage + 
							comm_msg099 + space + (i+1) + tracking_msg033 + 
								tracking_msg034 +newline;
      
			  		if( errors == "" ) errors=""+(i+1);
		      		else errors+=(  ", " + (i+1) );
			  }
	        }
			else
		    {
				errorMessage = errorMessage + 
					comm_msg099 + space +(i+1) + tracking_msg035 +newline;

				isPieceFound = true;
			}
     
	    }
	    else
	    {
			errorMessage = errorMessage + 
					comm_msg099 + space+ (i+1) + tracking_msg036 +newline;

			isAwbFound = true;
		}
   }

    trimmedPid = awbs[i].replace(/[^a-zA-Z0-9]+/g,'');

    upperCasePid =  trimmedPid.toUpperCase();
   
	finalPieceStr = finalPieceStr + upperCasePid + " ";
	

	if( i == awbsLength - 1 )
	{   //alert("before form.awb_hidden.value :"+form.awb_hidden.value);
		form.awb_hidden.value = finalPieceStr;
        //alert("after form.awb_hidden.value :"+form.awb_hidden.value);
	} 
  }
	if( errorMessage != "" )
  {     
		if( isAwbFound && isPieceFound )
	    {
			trackingMixAlert("awbpiecemix", errorMessage + "<br><br>" + tracking_msg037 );
		    return false;
	    }
  }
  if( errors != "" )
  {
	

    showRed = true;
    numbad=errors.split( ", " );
    if( numbad.length == 1 )
      trackingAlert( "singInvalid", numbad[0] );
    else
      trackingAlert( "multInvalid", errors );
    return false;
  }
  if (isZeroValue())
  {
    trackingAlert("cannotBeZero");
    return false;
  }
  if (isDuplicate())
  {
    trackingAlert("duplicateawbs");
    return false;
  }

  return true;
}

function fnDPEE()
{
  if ( (awbsLength > 10) || ((flagSpaceEnter) && (awbsLength==10)) )
  {
    trackingAlert( "tooMany", brandText+"s." );
    return false;
  }
  if (isZeroValue())
  {
    trackingAlert( "cannotBeZero");
    return false;
  }
  if (isDuplicate())
  {
    trackingAlert("duplicateawbs");
    return false;
  }
  return true;
}

function fnDanzas()
{
  if ( (flagSpaceEnter) || (awbsLength>1) )
  {
    trackingAlert( "tooManyDanzas", brandText+"." );
    return false;
  }
  if (isZeroValue())
  {
    trackingAlert( "cannotBeZero");
    return false;
  }
  return true;
}

/*
Function to check for Exel numbers 
Though Exel numbers have only one space, the function will consider only
line breaks and tab as different numbers and not space. So a number like 
'020-5040 100 234' is still considered as one number.
*/
function fnExel()
{
  if ( (awbsLength>1) || ((flagSpaceEnter) && (awbsLength==2)) )
  {
    trackingAlert( "tooManyDanzas", brandText+"." );
    return false;
  }
  if (isZeroValue())
  {
    trackingAlert( "cannotBeZero");
    return false;
  }
  return true;
}

function checkForm(form)
{
 if( typeof( form ) == "undefined" ) form = document.forms[0];
 if( typeof( form.elements["AWBV"] ) != "undefined" && form.elements["AWBV"].value != awbText )
 {
  form.AWB.value = form.AWBV.value;
 }
 awb=strip( form.AWB.value );
 //3DTrack Start Add
 if (awb=="")
 {
  trackingAlert( "noNumbs");
  return false;
 }

  var brand=form.brand.options[form.brand.selectedIndex].value;
  brandText = form.brand.options[form.brand.selectedIndex].text;

  awbs=new Array();
  tmp=""; iterator=0; i=0;
  while(iterator<awb.length)
  {
    c=awb.charAt(iterator);
    if( brand=="HBN" || brand=="CRN" ) 
    {
        if ( c !="\t" && c !="\n"  && c !="\r"  )
        {
          tmp=tmp+c;
        }
        else if (tmp!="")
        {
          awbs[i]=tmp;
          tmp="";
          i++;
        }
    }
    else
    {
        if ( c != "," && c !="\t" && c !="\n"  && c !="\r"  )
        {
          tmp=tmp+c;
        }
        else if (tmp!="")
        {
          awbs[i]=tmp;
          tmp="";
          i++;
        }
    }
    iterator++;
  }
  if (tmp!="")
  {
    awbs[i]=tmp;
  }

  awbsLength = awbs.length;
  
  if (brand=="")
  {
    trackingAlert( "selectType");
    return false;
  }
  else if ( (brand=="DHL") && !fnDHL(form) )
  {
    return false;
  }
  else if ( (brand=="I" || brand=="R") && !fnDPEE() )
  {
    return false;
  }
  else if ( (brand=="HBN" || brand=="CRN") && !fnExel() )
  {
    return false;
  }
  else if ( (brand=="CN" || brand=="BOLN" || brand=="DOC") && !fnDanzas() )
  {
    return false;
  }

 flagSpaceEnter = false;
 //3DTrack End Add
 dd=new Date();
 ms=dd.getTime()+600*86400000;
 dd.setTime(ms);
 days=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
 mons=new Array("Jan","Tue","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
 if( typeof( dd.getFullYear ) != "undefined" ) year=dd.getFullYear();
 else { year=dd.getYear(); if( year < 1900 ) year+=1900; }
 year+="";
 expire=days[dd.getDay()]+", "+zpad(dd.getDate())+"-"+mons[dd.getMonth()]+"-"+year.substring(2,year.length)+" 00:00:00 GMT";
 setCookie( "AWBS", awb, expire );
 setCookie( "BRAND", form.brand.options[form.brand.selectedIndex].text );
 return true;
}
function zpad(num)
{
 return ((num<10)?"0"+num:num);
}
function getCookie(Name)
{
 var search = Name + "="
 if (0 < document.cookie.length)
 {
  offset = document.cookie.indexOf(search) 
  if (offset != -1)
  {
   offset += search.length 
   end = document.cookie.indexOf(";", offset) 
   if (end == -1) 
    end = document.cookie.length
    return unescape(document.cookie.substring(offset, end))
  } 
 }
 return "";
}
function setCookie(name, value, expire) {
 document.cookie = name + "=" + escape(value)
 + ((expire == null) ? "" : ("; expires=" + expire))
}

function initForm(form)
{
  form.AWB.value=getCookie("AWBS");
  if ( form.brand.options[0].text != "Please Select" )
  {
    BRAND = getCookie("BRAND");//form.brand.options[form.brand.selectedIndex].value ;
    brandlength = form.brand.length;
    for ( j=0 ; j < brandlength ; j++ )
    {
      if ( form.brand.options[j].text == BRAND )
      {
        form.brand.options[j].selected = true;
        break;
      }
    }
    if ((BRAND == "HBN" || BRAND == "CN" || BRAND == "BOLN" || BRAND == "DOC" ||BRAND == "CRN" ))
    {
      reDanzasTrackIndex = true;
    }
  }
}
/* End Add:SM0018:manmohan:21.07.2002:for NGW3.0 Look n feel*/

function clearForm( theform )
{
 theform.awb.value="";
 theform.email.value="";
 theform.mobile.value="";
 theform.pager.value="";
 len = theform.elements.length;
 for( i=0 ; i<len ; i++) 
 {
    if ((theform.elements[i].name=="awb") && (theform.elements[i].checked==true))
    {
        theform.elements[i].checked=false;
    }
 }
}

function checkAWBSelection(val)
{
  var checked = false;
  var form = document.forms["f1"];

  if(typeof(form.awb)!="undefined")
  {
     
    if(typeof(form.elements["awb"].length)!="undefined")
    {
        for(i=0;i<form.elements["awb"].length;i++)
        {
          if(form.elements["awb"][i].checked)
            checked = true;
        }
    } 
    else
    {
      if(form.elements["awb"].checked)
        checked = true;
    }

    if (!checked)
    {
      strErrMess = tracking_msg007;
      return false;
    }
    
  }
  else
  {
    strErrMess = tracking_msg007;
    return false;
  }
  return true;
}


function validateTracking( form )
{
  if (  validateForm( form ) )
  {
    if ( typeof( form ) == 'undefined' )
    {
      theForm = document.forms[0];
    }
    else
    {
      theForm = document.forms[form];
    }

    if (  theForm.mobile.value != "" )
    {
      validateFollowMe( theForm, "mobile")
    }
    if ( theForm.pager.value != "" )
    {
      validateFollowMe ( theForm, "pager")
    }
  }
  else
  {
    return false
  }

}

function validateFollowMe( theForm, type )
{
  zeroFlag  = true
  returnNo  = ""
  number    = theForm.elements[type].value 

  for ( j=0 ; j < number.length ; j++ )
  {
    if ( ! charIsDigit( number.charAt(j) ) )
    {
      if (  number.charAt(j).charCodeAt( 0 ) != 32 )
      {
        return false;
      }
    }
    else
    {
      if ( ( number.charAt(j).charCodeAt( 0 ) != 48 )  || ( number.charAt(j).charCodeAt( 0 ) == 48 && !zeroFlag  ) )
      {
        zeroFlag = false
        returnNo = returnNo + number.charAt(j)
      }
    }
  }

  theForm.elements[type].value = returnNo
}
//3DTrack Start Adding
function trackSubmit(form)
{
  form=document.forms['trackingIndex'];
  if (!checkForm(form) )
  {
    if (showRed)
    {
        setErrorLayerStyle( "trackError" );
        showRed=false;
    }
    return false;
  }
  return true;
}

function fnSpaceEnterPressed()
{
  if (focusOnAWB)
  {
  flagSpaceEnter=true;
  return trackSubmit();
  }
  focusOnAWB = false;
}

function fnShowDefault(form)
{
  setNormalLayerStyle( "trackError" );
}

function fnClearClick(form)
{
  setNormalLayerStyle( "trackError" );
}

// Fallowing function uses for piece id validation

function validatePieceid(pieceid)
{	
	var pid = " ";
    pid = pieceid.toUpperCase();

	if(!testPiece(pid))
   	{
	    //alert("Sorry!! Piece Id - "+pid +" would NOT be sent to ITS\nReason: " + reasonForReject);
		return false;
   	}
   	else
   	{
		pid =  pid.replace(/[^a-zA-Z0-9]+/g,'');
	   //alert("Bingo!! Piece Id - "+pid + " WOULD BE sent to ITS\nReason: " + reasonForSuccess);
        return true ;
   	}

}

function testPiece( pieceId)
{
	//check the max length of teh piece-id along with the special characters and ().
	var pieceIdTmp = pieceId.replace(/[^a-zA-Z0-9]+/g,'');

	//check the min max rule
	if( pieceIdTmp.length < 7 || pieceIdTmp.length > 37 )
	{
		reasonForReject = "Piece id length < 7 or > 37";

		return false;
	}

	//Replace special characters apart from ()
	//var pieceId = "this is a (te)!!!!st st>r23ing**%";
	pieceId =  pieceId.replace(/[^a-zA-Z0-9()]+/g,'');
	
	pieceId = fnTrim(pieceId, 2);

	//Check if piece id starts with "("
	if( pieceId.indexOf("(") == 0 )
	{

		var closingBracketIndex = pieceId.indexOf(")");
		
		//If there is no char between starting and closing bracket
		if( closingBracketIndex != 1 )
		{

			//get the value between brackets
			var valueBetweenBrackets = pieceId.substring(1, closingBracketIndex);
			
			//Check if the DI is present in the valid DI list
			if( isDIValid( valueBetweenBrackets ) )
			{

				//If the DI is 00
				if( valueBetweenBrackets == "00" )
				{

					var tmpPid = pieceId.substring(closingBracketIndex + 1);
					
					var pidAsNumber = new Number(tmpPid);
					
					//if this is a valid number
					if( pidAsNumber.toString() != "NaN" )
					{
						var pidlength = pieceId.length;

						//length must be 22 including ( AI/DI )
						if( pidlength == 22 )
						{
							reasonForSuccess = "Piece id meets all criteria";

							//Piece Id is valid
							return true;
						}
						else
						{
							reasonForReject = "Piece Id length is not 18";
						}
					}
					else
					{
						reasonForReject = "Piece Id is not numeric";
					}

				}
				else
				{
					//Check if IAC is valid
					if( isIACValid( pieceId, closingBracketIndex + 1 ) )
					{
						//Now check length
						//get the length of the piece Id
						var pidlength = pieceId.length;

						if( valueBetweenBrackets == "5J" || 
						valueBetweenBrackets == "6J" )
						{		
							//length must be less than or equal to 24 including ( AI/DI )
							if( pidlength <= 24 )
							{
								reasonForSuccess = "Piece id meets all criteria";

								//Piece Id is valid
								return true;
							}
							else
							{
								reasonForReject = "Piece Id length is  > 20";
							}
						}
						else
						{

							if( valueBetweenBrackets == "J" )
							{
								//length must be less than or equal to 38 including ( AI/DI )	
								if( pidlength <= 38 )
								{
									reasonForSuccess = "Piece id meets all criteria";

									//Piece Id is valid
									return true;
								}
								else
								{
									reasonForReject = "Piece Id length is > 35";
								}
							}
							else
							{
								//length must be less than or equal to 39 including ( AI/DI )	
								if( pidlength <= 39 )
								{
									reasonForSuccess = "Piece id meets all criteria";

									//Piece Id is valid
									return true;
								}
								else
								{
									reasonForReject = "Piece Id length is > 35";
								}
							}

							
						}
					}
				}
			}
		}
		
	}//End of ( check
	else 
	{

		var diValue = pieceId.substring(0,1);

		if( diValue == "J" )
		{
			reasonForSuccess = "Since it starts with J. No Validation at NGW end.";

			return true;
		}
		else
		{
			diValue = pieceId.substring(0,2);
		}
		
		//Check if the DI is present in the valid DI list
		if( isDIValid( diValue ) )
		{
			//If the DI is 00
			if( diValue == "00" )
			{
				
				var pidAsNumber = new Number(pieceId);
				
				//if this is a valid number
				if( pidAsNumber.toString() != "NaN" )
				{
					var pidlength = pieceId.length;

					//length must be 20 including AI/DI
					if( pidlength == 20 )
					{
						reasonForSuccess = "Piece id meets all criteria";

						//Piece Id is valid
						return true;
					}
					else
					{
						reasonForReject = "Piece Id length is not 18";
					}
				}
				else
				{
					reasonForReject = "Piece Id is not numeric";
				}
				

			}
			else
			{
				//Check if IAC is valid
				if( isIACValid( pieceId, 2 ) )
				{
					//Now check length
					//get the length of the piece Id
					var pidlength = pieceId.length;

					if( diValue == "5J" || 
					diValue == "6J" )
					{			
						//length must be less than or equal to 22 including AI/DI
						if( pidlength <= 22 )
						{
							reasonForSuccess = "Piece id meets all criteria";

							//Piece Id is valid
							return true;
						}
						else
						{
							reasonForReject = "Piece Id length is not > 20";
						}
					}
					else if( diValue != "J" )
					{
						//length must be less than or equal to 37 including AI/DI
						if( pidlength <= 37 )
						{
							reasonForSuccess = "Piece id meets all criteria";

							//Piece Id is valid
							return true;
						}
						else
						{
							reasonForReject = "Piece Id length is > 35";
						}
					}
				}
			}
		}
		else
		{
		    //alert(" pidlength  :"+pieceIdTmp.length );
			
			if(pieceIdTmp.length  <= 35)
			{
                reasonForSuccess = "Invalid AI/DI. No Validation at NGW end.";
				return true;
			}
			else
			{
                reasonForReject = " Even AI/DI not present,yet length is greter than 35 characters.";
				return false;
			}
		}
	}
}

function isIACValid( pieceId, startingIndex )
{

	//Check if the IAC starts with a character

	var iacAsNumber = new Number(pieceId.charAt(startingIndex));

	if( iacAsNumber.toString() != "NaN" )
	{
		reasonForReject = "First IAC char is a number";
		return false;
	}

	var validIACList = document.getElementById("iac").value;

	//Check if the IAC is valid
	if( validIACList.indexOf( "|" + pieceId.substring( startingIndex, startingIndex+3) + "|" ) != -1 )
	{
		//3 digit IAC handled here
		return true;
	}
	else if( validIACList.indexOf( "|" + pieceId.substring( startingIndex, startingIndex + 2) + "|" ) != -1 )
	{
		//2 digit IAC handled here
		return true;
	}
	else if( validIACList.indexOf( "|" + pieceId.substring( startingIndex, startingIndex + 1) + "|" ) != -1 )
	{
		//1 digit IAC handled here
		return true;
																
	}
	else
	{
		reasonForReject = "Invalid IAC";
		return false;
	}
}

function isDIValid(diValue)
{
	
	var validDIList = document.getElementById("di").value;

	if( validDIList.indexOf( "|" + diValue + "|" ) != -1
				|| validDIList.indexOf( diValue + "|" ) != -1
				||validDIList.indexOf( "|" + diValue) != -1 )
	{
		return true;
	}
	else
	{
		reasonForReject = "Invalid AI/DI";
		return false;
	}

}

//3DTrack End Adding
//Start Bhargav.K : 30.10.08 : Trim function added to trim spaces for AWB number check
function fnTrim(inputString, side)
{
    var tempString = "";
    var tempChar = "";
	var count = "";
    var SINGLE_BLANK = " ";
    var inputWidth = 0;
    if (null == inputString)
    {
        tempString = EMPTY_STRING;
    }
    else
    {
        inputWidth = inputString.length;
        switch (side)
        {
        case 0:
            //left trim
            for (count = 0; count < inputWidth; count++)
            {
                tempChar = inputString.charAt (count);
                if (SINGLE_BLANK != tempChar )
                {
                    tempString = inputString.substring (count, inputWidth);
                    break;
                }
            }
            break;
        case 1:
            //right trim
            for (count = inputWidth - 1; count >= 0 ; count--)
            {
                tempChar = inputString.charAt (count);
                if (SINGLE_BLANK != tempChar )
                {
                    tempString = inputString.substring (0, count+1);
                    break;
                }
            }
            break;
        case 2:
            //both trim
            for (count = 0; count < inputWidth; count++)
            {
                tempChar = inputString.charAt (count);
                if (SINGLE_BLANK != tempChar )
                {
                    tempString = inputString.substring (count, inputWidth);
                    break;
                }
            }
            inputWidth = tempString.length;
            for (count = inputWidth - 1; count >= 0 ; count--)
            {
                tempChar = tempString.charAt (count);
                if (SINGLE_BLANK != tempChar )
                {
                    tempString = tempString.substring (0, count+1);
                    break;
                }
            }
            break;
        }
    }
    return tempString;
} // end of fnTrim
//End change Bhargav.K : 30.10.08