var d = new Date();
var theStart = d.getTime();

  function chkpicture()
   {
   var picture = document.ThisForm.filefield1;
    
   if (picture.value.length == 0) {
      alert("The picture field cannot be empty!");
      return false;
      }
   return true;
   }



   function advertvalidate()
   {
   var advertbody = document.ThisForm.txtAdvertBody;
   var itemcost = document.ThisForm.txtItemCost;
   var costValue = document.ThisForm.txtItemCost.value;
   var a = document.ThisForm.txtStartDate.value; // start date
   var today = new Date();
   
   decallowed = 2;  // how many decimals are allowed?

   if (advertbody.value.length == 0) {
      alert("Advert body text required");
      return false;
      }
		
   if (a.length>7&&!(a.split("/")[0]*1>31)&&!(a.split("/")[1]*1>12)&&!(a.split("/")[2]*1<1900))
   { 
 //  return true;
   }
   else {
   //Must be longer than 7 characters, first (two) digit(s) NOT greater than 12, second (two) digit(s) NOT greater than 31 and last 4 greater than 1900
   alert ("Start date invalid"); 
   return false;  
   }  
   if (isNaN(costValue) || costValue == "" || costValue == 0) {
   alert("Item Cost invalid");
   return false;
   }
   else {
   if (costValue.indexOf('.') == -1) costValue += ".";
   dectext = costValue.substring(costValue.indexOf('.')+1, costValue.length);

   if (dectext.length > decallowed)
   {
   alert ("Please enter a number with up to " + decallowed + " decimal places.");
   return false;
   }
   }
   
   return true;
   }


function regrequired() {

var okflag = 1
var errormessage = ""

if(document.RegForm.requiredusername.value == ""){okflag = 0; errormessage += "Please choose a username.\n"}
if(document.RegForm.requiredpassword.value == ""){okflag = 0; errormessage += "Please choose a password.\n"}
if(document.RegForm.requiredconfirm.value == ""){okflag = 0; errormessage += "Please confirm your password.\n"}
if(document.RegForm.requiredpassword.value != document.RegForm.requiredconfirm.value){okflag = 0; errormessage += "The confirmed password you have entered doesn't match. Please make sure you have entered the same password twice.\n"}

if(okflag){return true} else {alert(errormessage); return false;}
}


function reg2required(which){
var pass=true
if (document.images){
   for (i=0;i<which.length;i++){
      var tempobj=which.elements[i]
      if (tempobj.name.substring(0,8)=="required"){
         if (((tempobj.type=="text"||tempobj.type=="textarea")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&tempobj.selectedIndex==-1)){
            pass=false
            break
         }
      }
   }
}
if (!pass){
   alert("One or more of the required elements are not completed. Please complete them, then submit again!")
   return false
   }
else {

         if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(RegForm2.requiredemail.value)){
         return true
		 }
	     else {
	        alert("Invalid E-mail Address! Please re-enter.")
            return false
         }


return true
}
}





function chkrequired() {

var okflag = 1
var errormessage = ""

if(document.apply.username.value == ""){okflag = 0; errormessage += "Please choose a username.\n"}
if(document.apply.passa.value == ""){okflag = 0; errormessage += "Please choose a password.\n"}
if(document.apply.passb.value == ""){okflag = 0; errormessage += "Please repeat your password.\n"}
if(document.apply.passa.value != document.apply.passb.value){okflag = 0; errormessage += "The repeated password you have entered doesn't match. Please make sure you have entered the same password twice.\n"}

if(okflag){return true} else {alert(errormessage); return false;}
}


  function regvalidate()
   {
   var username = document.RegForm.requiredusername;
   var password = document.RegForm.requiredpassword;
   var confirm = document.RegForm.requiredconfirm;
    
   if (username.value.length == 0) {
      alert("Please enter username");
      return false;
      }
   if (password.value.length == 0) {
      alert("Please enter password");
      return false;
      }
  
   if (password.value != confirm.value) {
      alert("password mismatch");
      return false;
      }

   return true;
   }




//function to perform screen level validation on fields
function ftn_checkSearch() 
{
	ftn_stripSpaces()
	var search_data
	var search_code
	search_data = document.frmSearch.search_data.value
	search_code = document.frmSearch.search_code.value
	if (search_data == "") 
	{
        alert("Please enter a value to search the PLOF by")
        document.frmSearch.search_data.focus()
        return false 
   	}
   	else
   	{
   		return ftn_isValid()
   		if (ftn_isValid())
   			return true
   		else
   			return false
   	}
	return true
}


//function to prevent users from entering numeric/non-numeric
//or incorrect field lenghts into search data.
function ftn_isValid()
{
	ftn_stripSpaces()
	var search_code
	search_code = document.frmSearch.search_code.value
	var search_data
	search_data = document.frmSearch.search_data.value
	if (search_code == "3")
	{
		if((isNaN(search_data)) == false)
		{
			alert("Please enter a valid label and/or description")
			document.frmSearch.search_data.focus()
			return false
		}
		
		if ((search_data.length) <= 1)
	    {
	        alert("Please enter a valid label and/or description")
			document.frmSearch.search_data.focus()
			return false
	    }	 
		spaceloc = search_data.indexOf(" ") // the location of the blank space
		if (spaceloc == -1)
		{
			//this is an escape out of function if only one word is entered
			document.frmSearch.search_data.value = search_data
			return true
		}
		else
		{
			//substring out the first word to use in search plof
			search_data = search_data.substring(0, spaceloc)
			//now that you have the first word to search on
			//check that it is alpha - numeric again.
			if((isNaN(search_data)) == false)
			{
				alert("Please enter a valid label and/or description")
				document.frmSearch.search_data.focus()
				return false
			}
			document.frmSearch.search_data.value = search_data
			return true
		}
	 }
		
	 else if (search_code == "1")
	 {
		if ((search_data.length) > 13)
	    {
	        alert("Please enter a valid EAN code")
			document.frmSearch.search_data.focus()
			return false
	    }
	    if (ftn_isInteger())
   			return true
   		else
   			alert("Please enter a valid EAN code")
   			document.frmSearch.search_data.focus()
   			return false   		
	 }
	 
	 else if (search_code == "2")
	 {	 
		if ((search_data.length) != 6)
	    {
	        alert("Please enter a valid product code")
			document.frmSearch.search_data.focus()
			return false
	    }
	    if (ftn_isInteger())
   			return true
   		else
   			alert("Please enter a valid product code")
   			document.frmSearch.search_data.focus()
   			return false
	 }
	 return true 	
}


function ftn_stripSpaces() 
{
	var x
    x = document.frmSearch.search_data.value;
    //remove blank space if it is the first character
    while (x.substring(0,1) == ' ') x = x.substring(1);
    //remove blank space if it is the last character
    while (x.substring(x.length-1,x.length) == ' ') x = x.substring(0,x.length-1);
    //alert("the value after space strip is: " + x)
    document.frmSearch.search_data.value = x
    return true
}
//--&gt;&lt;/SCRIPT&gt;

//empty out contents of search data.
function ftn_clearData()
{
	var search_c
	var search_l
	search_c = document.frmSearch.search_code.value
	search_l = document.frmSearch.search_data.maxlength
	document.frmSearch.search_data.value = ""
	document.frmSearch.search_data.focus()
	if (search_c == "1")
	{
		document.frmSearch.search_data.maxLength = 13
		
	}
	else if (search_c == "2")
	{
		document.frmSearch.search_data.maxLength = 6
	}
	else if (search_c == "3")
	{
		document.frmSearch.search_data.maxLength = 25
	}
	
}

//function to check if number and has no decimal places
function ftn_isInteger()
{
	var search_code
	search_code = document.frmSearch.search_code.value
	var search_data
	search_data = document.frmSearch.search_data.value
	
	if ( (isNaN(search_data)) == false)
	{	
		//goes in to this method if value is numeric
		//need to send error if it's a decimal
		decloc = search_data.indexOf(".") // the location of the blank space
		if (decloc == -1)
		{
			//if no occurence of full stop go ahead
			return true
		}
		else
		{
			//if a number but a decimal then error
			return false
		}
		return true
	}
	else
	{
		return false
	}
}





function closewindow() {parent.window.close()}

function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); }

function OpenPage(name) {window.open = name}


function openwindow(URL)
{
   window.open (URL,"Help","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,copyhistory=no,width=600,height=400");
   window.focus;
}

function pdfwindow(URL)
{
   window.open (URL,"Help","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=600,height=400");
   window.focus;
}

function myalert(URL)
{
   window.open (URL,"Help","toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width=500,height=200");
   window.focus;
}


 function newswindow(URL)
{
   window.open (URL,"Help","toolbar=yes,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=600,height=400");
   window.focus;
}

   function HilightBkgnd(elem) 
   { elem.bgColor="#044C84" }

   function Hilite(elem) 
   { 
   var x 
   x = "#044C84" 
   elem.bgColor=x
   elem.border="1px solid";
   }

   function RestoreBkgnd(elem) 
   { 
   var y
   y = "#336699"
   elem.bgColor=y
   
   }
   
//Navigation rollover
function NavIn(menItem) {
	//menItem.style.borderColor='#999999'; 
	//menItem.style.backgroundColor='#e8e8e8';
menItem.style.backgroundColor='#C3D5FD';
}

function NavOut(menItem) {
	//menItem.style.borderColor='#6699cc'; 
	menItem.style.backgroundColor='#ffffff';
}

function NavCat(menItem) {
	menItem.style.borderColor='#FFFFFF'; 
	menItem.style.backgroundColor='#FFFFFF';
}



function GreyNavIn(menItem) {
	menItem.style.borderColor='#999999'; 
	menItem.style.backgroundColor='#CCCCCC';
}

function GreyNavOut(menItem) {
	menItem.style.borderColor='#E7E7E7'; 
	menItem.style.backgroundColor='#E7E7E7';
}



function modiBody(scode){

  var collapseableDiv = document.getElementById("body" + scode);
//  var collapseIMG = document.getElementById("img" + scode);
   
   if ( collapseableDiv.style.display != 'none' ) {
   collapseableDiv.style.display = 'none';
  // collapseIMG.src="images/plusbutton.gif";
    
    }
    else {
       collapseableDiv.style.display = 'block';
      // collapseIMG.src="images/minusbutton.gif";
    }




}

function changeWebBasket(){

  var collapseableDiv = document.getElementById("webbasketfunctions");
  var collapseIMG = document.getElementById("webbasketimg");
   
   if ( collapseableDiv.style.display != 'none' ) {
   collapseableDiv.style.display = 'none';
   collapseIMG.src="images/tree/round_plus.gif";
    
    }
    else {
       collapseableDiv.style.display = 'block';
       collapseIMG.src="images/tree/round_minus.gif";
    }


}

/* change the default order */
function changeDefaultOrder(defaultOrder){
  
  
  if (defaultOrder == "inactive"){
      window.location.reload();
      return;
    }

  var url = location.href;   
  var array1 = url.split("&");
  var array2 = new Array();  
  var i;  
  var labels = "";
  var data   = "";  
  var formObj = document.getElementById("searchform");
  
   
  //skip first array entry
  for(i=1; i < array1.length; i++){
   
       labels = labels + ",";
       data   = data   + ",";
      
       array2 = array1[i].split("=");
     
       labels = labels + array2[0];
       data   = data   + array2[1];
   }

 
 
formObj.action = "horis.asp?Action=Call&Page=ord_changedef&deford=" + defaultOrder + "&labels=" + labels + "&data=" + data;
//alert("horis.asp?Action=Call&Page=ord_changedef&deford=" + defaultOrder + "&labels=" + labels + "&data=" + data);

formObj.submit();
  
  

}

/***********************************************************/
/*******CREDIT FUNCTIONS************************************/
/***********************************************************/


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/*
   opens summary div for a credit
   credits an html tree and then adds it to the document body
    
    <div>
    <table>
    <tbody>
     <tr>
     <td>Credit No</td>
     <td>...</td>
     </tr>
     <tr>
     <td>No Of Items</td>
     <td>...</td>
     </tr>
     <tr>
     <td> Credit Total</td>
     <td>...</td>
     </tr>
     <tr>
     <td>Create Date</td>
     <td>....</td>
     </tr>
     <tr>
     <td>Status</td>
     <td>....</td>
     </tr>
     <tr>
     <td colspan='2'>'Status'</td>
    
     </tr>

    </tbody>
     </table>
    </div>
    


*/
function open_cd_sum(obj, cd_no, cd_items, cd_total, cr_dt, sts_desc)
{

var descArray = new Array();
var i;

descArray = sts_desc.split(",");





var div_node   = document.createElement('div');
var table_node = document.createElement('table');
var tbody_node = document.createElement('tbody');
var tr_node    = document.createElement('tr');
var td_node1   = document.createElement('td');
var td_node2   = document.createElement('td');
var text_node1 = document.createTextNode("Credit No.");
var text_node2 = document.createTextNode(cd_no);
td_node1.className="cred_summary_td";
td_node2.className="cred_summary_td";
td_node1.setAttribute('bold',true);

td_node1.appendChild(text_node1);
td_node2.appendChild(text_node2);
tr_node.appendChild(td_node1);
tr_node.appendChild(td_node2);
tbody_node.appendChild(tr_node);


tr_node = document.createElement('tr');
td_node1 = document.createElement('td');
td_node2 = document.createElement('td');
text_node1 = document.createTextNode("No Of Items");
text_node2 = document.createTextNode(cd_items);
td_node1.appendChild(text_node1);
td_node2.appendChild(text_node2);
tr_node.appendChild(td_node1);
tr_node.appendChild(td_node2);
tbody_node.appendChild(tr_node);

tr_node = document.createElement('tr');
td_node1 = document.createElement('td');
td_node2 = document.createElement('td');
text_node1 = document.createTextNode("Credit Total");
text_node2 = document.createTextNode("£" + cd_total);
td_node1.appendChild(text_node1);
td_node2.appendChild(text_node2);
tr_node.appendChild(td_node1);
tr_node.appendChild(td_node2);
tbody_node.appendChild(tr_node);

tr_node = document.createElement('tr');
td_node1 = document.createElement('td');
td_node2 = document.createElement('td');
text_node1 = document.createTextNode("Create Date");
text_node2 = document.createTextNode(cr_dt);
td_node1.appendChild(text_node1);
td_node2.appendChild(text_node2);
tr_node.appendChild(td_node1);
tr_node.appendChild(td_node2);
tbody_node.appendChild(tr_node);


tr_node = document.createElement('tr');
td_node1 = document.createElement('td');
td_node1.className = "purple";
text_node1 = document.createTextNode("");
td_node1.colSpan = "2";
td_node1.appendChild(text_node1);
tr_node.appendChild(td_node1);
tbody_node.appendChild(tr_node);


/* add all the cs code desc */
for(i in descArray){

tr_node = document.createElement('tr');
td_node1 = document.createElement('td');

text_node1 = document.createTextNode(descArray[i]);
td_node1.colSpan = "2";
td_node1.appendChild(text_node1);
tr_node.appendChild(td_node1);
tbody_node.appendChild(tr_node);

}


//get Pos of [X,Y]
var objPos = findPos(obj);


div_node.setAttribute('id','cred_summary');
div_node.className="cred_summary_parent";
div_node.style.position="absolute";
div_node.style.top =  objPos[1] - (150 + (20 * (descArray.length - 1)));
div_node.style.left = objPos[0] - 170;


table_node.appendChild(tbody_node);
text_node1 = document.createTextNode("Credit Summary");

var div_node_child1 = document.createElement('div');
var div_node_child2 = document.createElement('div');

div_node_child1.appendChild(text_node1);
div_node_child1.className="cred_summary";

div_node_child2.appendChild(table_node);

div_node.appendChild(div_node_child1);
div_node.appendChild(div_node_child2)

document.body.appendChild(div_node);


}



//closes a summary div for a credit
function close_cd_sum()
{
var div_node = document.getElementById('cred_summary');

document.body.removeChild(div_node);

}





/* stores the case/unit quanity on focus */
var storedCreditValue;
var modifiedCommodity = new Array();


/*
   Validates the credit amount entered against the available amount
   INPUT:-
   obj          - input obj in focus
   flag         - 'c'(case), 'u'(unit), 'w'(weight) 
   packsize     - no of units in  a case
   start_cases  - no of cases already credited
   start_units  - no of units already credited
   start_weight -  weight already credited
   cm_code      - used to identify line
   ord_qty      - orginal orders qty
*/

function val_credit(obj, flag, packsize, start_cases, start_units, start_weight, cm_code, ord_qty)
{
   

   var arraylength = modifiedCommodity.length;
   var addFlag     = true;

       
   
   var totalCreditedUnits = 0;   //stores the total credited units
   var totalUnits         = 0;   //stores the total units bought
   var totalCreditedWeight = 0;  //stores the total weight credited     

   // get elements that contain the av. credit amount
   var avCasesObj  = document.getElementById('avcase' + cm_code);
   var avUnitsObj  = document.getElementById('avunit' + cm_code);
   var avWeightObj = document.getElementById('avweight' + cm_code);
   var crCasesObj  = document.getElementById('case' + cm_code);
   var crUnitsObj  = document.getElementById('unit' + cm_code);
   var crWeightObj = document.getElementById('weig' + cm_code);

   
   // check that input is a positive number 
   if (!isNumber(crCasesObj.value) || !isNumber(crUnitsObj.value)){

      
      alert("Credited amount must be a positive number!");
      crCasesObj.value = 0;
      crUnitsObj.value = 0;
      obj.focus();
      return;      

   }


    /* add commodity to modified commodity */
    if (crCasesObj.value > 0 || crUnitsObj.value > 0 || crWeightObj.value > 0){

        if (arraylength > 0){

           for(var i=0;i<arraylength;i++){

              if (modifiedCommodity[i] == cm_code){
                  
                 addFlag = false;
                 break;
               }


            }

            if (addFlag)
              modifiedCommodity.push(cm_code);
        }
        else
           modifiedCommodity.push(cm_code);


     }


    // check that input is a positive number 
   if (!isDecimal(crWeightObj.value)){

      
      alert("Credited Weight must be a positive Decimal Number!");
      crWeightObj.value = 0.0;
      obj.focus();
      return;      

   }

    
   /* if obj is empty then set back to orginal value */   
   if (obj.value == ""){

     obj.value = storedCreditValue;
     obj.style.backgroundColor = '#FFFFFF';
     return;
    }

   totalCreditedWeight = parseFloat(crWeightObj.value) + parseFloat(start_weight);
   totalCreditedUnits = ((parseInt(crCasesObj.value) + parseInt(start_cases)) * parseInt(packsize)) + parseInt(crUnitsObj.value) + parseInt(start_units);
   totalUnits = ord_qty * packsize;
      


   //av_weight > 0 then can not enter cases and units	
   if ((flag == 'c' || flag  == 'u') && (avWeightObj.value > 0 || start_weight > 0)){

       alert("Cases or Units can not be used. Commodity was bought in weight!");
       obj.style.backgroundColor = '#FF0000';
       crCasesObj.value = 0;
       crUnitsObj.value = 0;
       return;
     }
    
    
   //av_weight > 0 then can not enter cases and units	
   if ((flag == 'w') && avWeightObj.value == 0 
    && (avUnitsObj.value > 0 || avCasesObj.value > 0 || start_units > 0 || start_cases > 0)){

       alert("Weight can not be used. Commodity was bought in Cases and units!");
       obj.style.backgroundColor = '#FFFFFF'; 
       crCasesObj.focus();                            //focus on cases field
       crWeightObj.value = 0.00;
       return;
     }
    
if (flag == 'c'){
      
   if (totalCreditedUnits > totalUnits) {

      crCasesObj.value = parseInt((totalUnits - ((parseInt(start_cases) * parseInt(packsize)) + parseInt(crUnitsObj.value) + parseInt(start_units))) / packsize);      //change value to max amount available     
      crCasesObj.style.backgroundColor = '#FF0000';  //alert color to red
      avCasesObj.value = 0;                          //set av. cases to zero
      alert("You have tried to Credit more than you have ordered\n" +
             "Cases limited to Available Case Quantity of " + crCasesObj.value);
      return;
   } //(creditVal > av_cases) 
   else{

      avCasesObj.value = parseInt((totalUnits  - totalCreditedUnits) / packsize); // reset available cases
      obj.style.backgroundColor = '#FFFFFF';  //alert color to white
       
    } //else(creditVal > av_cases) 

 } //(flag == 'c')



 if (flag == 'u'){
    

    if (totalCreditedUnits > totalUnits){
       crUnitsObj.value = parseInt(crUnitsObj.value) - (totalCreditedUnits - totalUnits);    //change value to max amount available
       obj.style.backgroundColor = '#FF0000';                                                //alert color to red
       avCasesObj.value = 0;                                                                 //set available to 0 for cases
       avUnitsObj.value = 0;                                                                 //set available to 0 for units
       alert("You have tried to Credit more than you have ordered\n" +
             "Units limited to Available Unit Quantity of " + crUnitsObj.value);
      return;
     }
    else{

      avCasesObj.value = parseInt((totalUnits - totalCreditedUnits) / packsize); // reset available cases
      avUnitsObj.value = (totalUnits - totalCreditedUnits) % packsize;
      obj.style.backgroundColor = '#FFFFFF';  //alert color to white

    } //else(creditVal > avCasesObj.value) 
}

if (flag == 'w'){
  if (totalCreditedWeight > ord_qty){
       crWeightObj.value = ord_qty; 
       obj.style.backgroundColor = '#FF0000';   
       avWeightObj.value = 0; 
       alert("You have tried to Credit more than you have ordered\n" +
             "Weight limited to Available Weight Quantity of " + crWeightObj.value);
      return;
    } // (totalCreditedWeight > ord_qty)
    else{
       avWeightObj.value = ord_qty - totalCreditedWeight;
       obj.style.backgroundColor = '#FFFFFF';  //alert color to white

    }
}

} //end function val_credit



/*
   INPUT:- 
   obj - element tat is currently in focus

   highlights text box when in focus

*/
function focus_credit(obj){
   
   //change background color to purple
   obj.style.backgroundColor = '#C3D5FD';
   storedCreditValue = obj.value;
   obj.value = "";

   
}



/*
 general purpose function to see if a suspected numeric input
 is a positive or negative number
*/
function isNumber(inputVal) {
  
  
  var inputStr = inputVal.toString();
   
  for (var i = 0; i < inputStr.length; i++) {
       var oneChar = inputStr.charAt(i);
      

      if (oneChar < '0' || oneChar > '9') {
         return false;
       }
      }
return true;
}

/*
 general purpose function to see if a suspected numeric input
 is a positive or negative number
*/
function isDecimal(inputVal) {

var oneDecimal = false;
var inputStr = inputVal.toString();

for (var i = 0; i < inputStr.length; i++) {

	var oneChar = inputStr.charAt(i);

	if (oneChar == '.' && !oneDecimal) {
		oneDecimal = true;
		continue;
	}

	if (oneChar < '0' || oneChar > '9') {
		return false;
	}

}
return true;
}



function beforeSubmit(){
  
    window.scrollTo(0,0);
/* tidy up the error display */
   var errorDiv = document.getElementById("errordiv");
   var text_node1 = document.createTextNode("Pease Wait. Currently Validating the Credit Lines.");
  



   while(errorDiv.childNodes.length > 0){
      childObj = errorDiv.lastChild;
      errorDiv.removeChild(childObj);     
 
   }  /* end for (i in errorDiv.ChildNodes) */
   
   errorDiv.className="validating";
   
   errorDiv.appendChild(text_node1);

   
   setTimeout("testSubmit()", 1000);
   
   return;

}


function testSubmit(){
   
   var frmCredit = document.getElementById("frmCredit"); 


   if (frmCredit.onsubmit()){


       frmCredit.submit();

      }


}

/*
   Valids the credits to be submitted
   INPUT:-
   formObj - the form element obj
   invtype - type of inv

*/
function validateCreditOnSubmit(formObj, invType){
   
   var startTime=new Date().getTime();

   
   /* flag to check that a credit is actually submitted */ 
   var creditsToSubmit = false;

   var submitButtonObj;  //Submit button object
   var reasonObj;        //stores reason element
   var caseObj;
   var unitObj;
   var weigObj;   
   var commodity;         //stores commodity number
   var childObj;
   
   /* stores errors */
   var noOfErrors = 0;
   var errorsArray = new Array();
  
   /* validation flag */
   var validated = true;
   

   /* tidy up the error display */
   var errorDiv = document.getElementById("errordiv");
   var text_node1;


    /* loop through form objs */
   for (var i=0, n=modifiedCommodity.length; i<n; i++){
                                    
              commodity = modifiedCommodity[i];
              
              
              reasonObj = document.getElementById("reas" + parseInt(commodity));
              caseObj = document.getElementById("case" + parseInt(commodity));
              unitObj = document.getElementById("unit" + parseInt(commodity));
              weigObj = document.getElementById("weig" + parseInt(commodity));
              
                         
              reasonObj.style.backgroundColor = "#ffffff"; 
              
              
              if (caseObj.value > 0 || unitObj.value > 0 || weigObj.value > 0){
                     
                     creditsToSubmit = true;

                     switch (parseInt(reasonObj.value)){
                          case 0:     
                          
                                reasonObj.style.backgroundColor = "#ff0000";
                          	validated = false; 
                           	errorsArray[noOfErrors] = "You Must Have A Reason Selected to Credit Commodity " + parseInt(commodity);
                                noOfErrors = noOfErrors + 1;
                                break;

                          case 2:    
                                      
                                break;
                          case 5:     

                                break;
                          case 6:     
                                
                                
                                 if (invType == "ffoods"){
                                    
                                    if (unitObj.value > 0 || weigObj.value > 0){
                                       
                                       reasonObj.style.backgroundColor = "#ff0000";
                          	       validated = false; 
                           	       errorsArray[noOfErrors] = "Reason 'Assembly Error' Must Be Credited In Cases For Commodity " + parseInt(commodity);
                                       noOfErrors = noOfErrors + 1;
                                       
                                      }  

                                    } 
 
                                break;
                          case 7:     

                               
                                 if (invType == "ffoods"){
                                    
                                    if (unitObj.value > 0 || weigObj.value > 0){
                                       
                                       reasonObj.style.backgroundColor = "#ff0000";
                          	       validated = false; 
                           	       errorsArray[noOfErrors] = "Reason 'Ordered In Error' Credits Must Be Credited In Cases For Commodity " + parseInt(commodity);
                                       noOfErrors = noOfErrors + 1;
                                       
                                      }  

                                    } 

                                   if (invType == "orders"){
                                    
                                    if (unitObj.value > 0 || weigObj.value > 0){
                                       
                                       reasonObj.style.backgroundColor = "#ff0000";
                          	       validated = false; 
                           	       errorsArray[noOfErrors] = "Reason 'Ordered In Error' Credits Must Be Credited In Cases For Commodity " + parseInt(commodity);
                                       noOfErrors = noOfErrors + 1;
                                       
                                      }  

                                    } 
                                break;
                          case 12:    

                                break;
                          case 13:    

                                 
                                 if (invType == "orders"){
                                    
                                    if (unitObj.value > 0 || weigObj.value > 0){
                                       
                                       reasonObj.style.backgroundColor = "#ff0000";
                          	       validated = false; 
                           	       errorsArray[noOfErrors] = "Reason 'Out Of Condition' Credits Must Be Credited In Cases For Commodity " + parseInt(commodity);
                                       noOfErrors = noOfErrors + 1;
                                       
                                      }  
                                    } 

                                break;

                          case 18:     

                                break;
                          case 19:   

                                break;

                     }   
                    
                                   
 
            } 
                    
      
  }  

 /* no credits available to submit */
 if (!creditsToSubmit){

     validated = false; 
     errorsArray[noOfErrors] = "You Have Not entered Any Credit Lines To Submit";
     noOfErrors = noOfErrors + 1;
  }



 if (!validated) {

         /* tidy up error div */
 while(errorDiv.childNodes.length > 0){
      childObj = errorDiv.lastChild;
      errorDiv.removeChild(childObj);     
   }  /* end for (i in errorDiv.ChildNodes) */
     
       var errorNo = 0;
       
       var tr_node1 = document.createElement("tr");
       var td_node1 = document.createElement("td");
       td_node1.className = "erroralert";
       var tbody_node = document.createElement("tbody");
       var table_node = document.createElement("table");

       errorDiv.className = "erroralert";

       for(i in errorsArray){
           errorNo = parseInt(i) + 1;           
           
           text_node1 = document.createTextNode(errorNo + ": " + errorsArray[i]);
            td_node1 = td_node1.cloneNode(false);  
            tr_node1 = tr_node1.cloneNode(false);
           td_node1.appendChild(text_node1); 
           tr_node1.appendChild(td_node1);    
           tbody_node.appendChild(tr_node1);      
          } // end for
         
           table_node.appendChild(tbody_node);

           text_node1 = document.createTextNode("The Credit Has Not Been Submitted For The Following Reasons:-");
           errorDiv.appendChild(text_node1);
           errorDiv.appendChild(table_node);
         
         /* scroll to top */
         window.scrollTo(0,0);
         var endTime=new Date().getTime();
       // alert('Elapsed time using ' + ((endTime-startTime)/1000)+' seconds.');

         return false;
      }  //end if

    return true; 

}  //end function



/* displays popup */
function viewMessage(messageString, parentObj, rolloverObj){

  
  var div_node   = document.createElement('div');
  
  var text_node1 = document.createTextNode(messageString);


  //get Pos of [X,Y]
  var objPos = findPos(rolloverObj);

div_node.appendChild(text_node1);

div_node.className="messagepopup";
div_node.setAttribute('id','messagepopup');
div_node.style.position="absolute";
div_node.style.top =  objPos[1];
div_node.style.left = objPos[0] +  (parentObj.offsetWidth / 2) + rolloverObj.offsetWidth;



document.body.appendChild(div_node);

}


function hideMessage(){

  var div_node = document.getElementById('messagepopup');
  document.body.removeChild(div_node);
}


function toInvList(submitted){


if (submitted){
	document.location = "horis.asp?Action=Call&Page=cr_credits";
}
else{
	document.location = document.referrer;  
}
}


function limitContent(obj, limit){

var content = obj.value;
var contentLength = content.length;
var lengthInd = document.getElementById("lengthInd");

if (contentLength >= limit){
	obj.value = content.substr(0,limit);
	lengthInd.className = "limit";
	lengthInd.innerHTML = limit;
}
else{
lengthInd.className = "normal";
lengthInd.innerHTML = contentLength;
}


}

function loadTime(){
d = new Date();
var theVal = (d.getTime() - theStart) / 1000; 

document.getElementById("clientTime").innerHTML= theVal+ "s" ;


var cookieTxt = getCookie("horisid");

if (cookieTxt.length > 0) {
   setInterval("checkCookie()", 100000);
}
   

}


function checkCookie(){

  if (getCookie("horisid") == "") {

    document.location="horis.asp?Action=Call&Page=Main&TimeOut=t";
  }

}


function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function toggleSuppSearch(div, objID){

var obj = document.getElementById(objID);


 if (div.options[div.selectedIndex].value == "CB"){	
 var myOption = document.createElement("option");
 myOption.value="5";
 myOption.text="Supplier";
 obj.add(myOption);
 }

if (div.options[div.selectedIndex].value == "WH"){
 	obj.remove(obj.options.length - 1);
 }
	

}

function imgonmouseover(imgObj){
  imgObj.src = imgObj.src.replace("blue", "grn");
}

function imgonmouseout(imgObj){
  imgObj.src = imgObj.src.replace("grn", "blue");
}

