var xmlHttp;
var vDivID;
var vDivType

// Set the horizontal and vertical position for the popup
PositionX = 100;
PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)
defaultWidth  = 660;
defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows
var AutoClose = true;

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4){
   var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;
}
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;
var optIE2='scrollbars=no,width=568,height=120,left='+PositionX+',top='+PositionY;


function sendSRMsg(vID,vTo,vItem) {
   dispWindow('emailemployees.php?to='+vTo+'&id='+vItem+'&it=vID',700,445,'SendMsg','');
}

function dispWindow(vURL,vWidth,vHgt,vTitle,vParams) {
   if (vParams == "") {
      vParams = "toolbar=0,directories=0,location=0,status=yes,menubar=0,resizable=yes,scrollbars=yes";
   }
   var vTop=(screen.height/2)-(vHgt/2);
   var vLeft=(screen.width/2)-(vWidth/2);
   vParams = "width="+vWidth+",height="+vHgt+",left="+vLeft+",top="+vTop+","+vParams
   window.open(vURL,vTitle,vParams);
}

function waitPreloadPage() {
   if (document.getElementById) {
      document.getElementById('prepage').style.visibility='hidden';
   } else {
      if (document.layers) { //NS4
         document.prepage.visibility = 'hidden';
      } else { //IE4
         document.all.prepage.style.visibility = 'hidden';
      }
   }
}

function SetDisp() {
   var answer = confirm("Save Rec/Pg and current page as your default display?");
   if (answer){
      dispWindow("setdisplay.php",330,120,"SetDisplay","");
   }
}

function Print() {
   var vReport = document.getElementById('Report').value;
   dispWindow(vReport,900,600,"Report","");
}

function CustDisplay(vCustID){
   dispWindow('customers_disp.php?id='+vCustID,775,650,'CustomerDisplay','');
}

function DispSO(vSOID){
   dispWindow('so_edit.php?1='+vSOID,800,650,'SOEdit','');
}

function dispCAHelp() {
   dispWindow("customersabbrv_help.php",350,310,"CAHelp","");
}

function resizeWindow(vWidth,vHeight) {
   var vLeft=(screen.width/2)-(vWidth/2);
   var vTop=(screen.height/2)-(vHeight/2);
   window.resizeTo(vWidth,vHeight);
   window.moveTo(vLeft,vTop);
   window.resizeTo(vWidth,vHeight);

}

function popImage(imageURL,imageTitle){
   imgWin=window.open('about:blank','',optIE);
   with (imgWin.document){
      writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');
      writeln('<sc'+'ript>');
      writeln('var isIE;');
      writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
      writeln('   isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;');
      writeln('}');
      writeln('function reSizeToImage(){');
      writeln('   if (isIE){');
      writeln('      window.resizeTo(100,100);');
      writeln('      width=240-(document.body.clientWidth-document.images[0].width);');
      writeln('      height=100-(document.body.clientHeight-document.images[0].height);');
      writeln('      window.resizeTo(width,height);');
      writeln('   }');
      writeln('}');
      writeln('function doTitle(){');
      writeln('   document.title="'+imageTitle+'";');
      writeln('}');
      writeln('</sc'+'ript>');
      if ( !AutoClose ) {
         writeln('</head><body bgcolor=FFFFFF scroll="no" onload="reSizeToImage();doTitle();self.focus()">');
      } else {
         writeln('</head><body bgcolor=FFFFFF scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
         writeln('<img id="George" src='+imageURL+' style="display:block"></body></html>');
         close();
      }
   }
}

function generateReports() {
   resizeWindow(900,650);
   var ele = document.createElement('div');
   ele.style.position='absolute';
   ele.style.width='100%';
   ele.style.height='60%';
   ele.style.background = 'url("images/loading3.gif") no-repeat center center';
   document.getElementById('inv_report1').style.visibility = 'hidden';
   document.body.appendChild(ele);
   document.getElementById('inv_report1').submit();
}

function removeLoad() {
   document.getElementById('loadingData').style.display='none';
}

function confirmLO() {
   var answer = confirm('Logout?')
   if (answer){
      window.location = 'logout.php';
   }
}


/**
 * Magic time parsing, based on Simon Willison's Magic date parser
 * @see http://simon.incutio.com/archive/2003/10/06/betterDateInput
 * @author Stoyan Stefanov &lt;stoyan@phpied.com&gt;
 */


/**
 * This is the place to customize the result format,
 * once the date is figured out
 *
 * @param Date d A date object
 * @return string A time string in the preferred format
 */
function getReadable(d) {
    return padAZero(d.getHours())
           + ':'
           + padAZero(d.getMinutes())
           + ':'
           + padAZero(d.getSeconds());
}
/**
 * Helper function to pad a leading zero to an integer
 * if the integer consists of one number only.
 * This function s not related to the algo, it's for
 * getReadable()'s purposes only.
 *
 * @param int s An integer value
 * @return string The input padded with a zero if it's one number int
 * @see getReadable()
 */
function padAZero(s) {
    s = s.toString();
    if (s.length == 1) {
        return '0' + s;
    } else {
        return s;
    }
}


/**
 * Array of objects, each has:
 * <ul><li>'re' - a regular expression</li>
 * <li>'handler' - a function for creating a date from something
 *     that matches the regular expression</li>
 * <li>'example' - an array of examples that show matching examples</li>
 * Handlers may throw errors if string is unparseable.
 * Examples are used for automated testing, so they should be updated
 *   once a regexp is added/modified.
 */
var timeParsePatterns = [
    // Now
    {   re: /^now/i,
        example: new Array('now'),
        handler: function() {
            return new Date();
        }
    },
    // p.m.
    {   re: /(\d{1,2}):(\d{1,2}):(\d{1,2})(?:p| p)/,
        example: new Array('9:55:00 pm','12:55:00 p.m.','9:55:00 p','11:5:10pm','9:5:1p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(parseInt(bits[3], 10));
            return d;
        }
    },
    // p.m., no seconds
    {   re: /(\d{1,2}):(\d{1,2})(?:p| p)/,
        example: new Array('9:55 pm','12:55 p.m.','9:55 p','11:5pm','9:5p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(0);
            return d;
        }
    },
    // p.m., hour only
    {   re: /(\d{1,2})(?:p| p)/,
        example: new Array('9 pm','12 p.m.','9 p','11pm','9p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(0);
            d.setSeconds(0);
            return d;
        }
    },
    // hh:mm:ss
    {   re: /(\d{1,2}):(\d{1,2}):(\d{1,2})/,
        example: new Array('9:55:00','19:55:00','19:5:10','9:5:1','9:55:00 a.m.','11:55:00a'),
        handler: function(bits) {
            var d = new Date();
            d.setHours(parseInt(bits[1], 10));
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(parseInt(bits[3], 10));
            return d;
        }
    },
    // hh:mm
    {   re: /(\d{1,2}):(\d{1,2})/,
        example: new Array('9:55','19:55','19:5','9:55 a.m.','11:55a'),
        handler: function(bits) {
            var d = new Date();
            d.setHours(parseInt(bits[1], 10));
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(0);
            return d;
        }
    },
    // hhmmss
    {   re: /(\d{1,6})/,
        example: new Array('9','9a','9am','19','1950','195510','0955'),
        handler: function(bits) {
            var d = new Date();
            var h = bits[1].substring(0,2);
            var m = parseInt(bits[1].substring(2,4), 10);
            var s = parseInt(bits[1].substring(4,6), 10);
            if (isNaN(m)) {m = 0;}
            if (isNaN(s)) {s = 0;}
            d.setHours(parseInt(h, 10));
            d.setMinutes(parseInt(m, 10));
            d.setSeconds(parseInt(s, 10));
            return d;
        }
    },


];

/**
 * Method that loops through all regexp's examples and lists them.
 * Optionally, the method can also run tests with the examples.
 *
 * @param boolean run_test TRUE is tests should be run on the examples, FALSE if only to show examples
 * @return object An XML 'ul' node
 */
function getExamples(run_tests) {
    var xml = document.createElement('ul');
    xml.setAttribute('id', 'time-parser-examples');
    for (var i = 0; i < timeParsePatterns.length; i++) {
        try {
            var example = timeParsePatterns[i].example;
            for (var j = 0; j < example.length; j++) {
                var list_item = document.createElement('li');
                if (!run_tests) {
                    var list_item_value = document.createTextNode(example[j]);
                } else {
                    var parsed = parseTimeString(example[j])
                    var result = getReadable(parsed) + ' -> ' + parsed.toTimeString();
                    var list_item_value = document.createTextNode(example[j] + ' -> ' + result)
                }
                list_item.appendChild(list_item_value)
                xml.appendChild(list_item);
            }
        } catch(e){}
    }
    return xml;
}

/**
 * Parses a string to figure out the time it represents
 *
 * @param string s String to parse
 * @return Date a valid Date object
 * @throws Error
 */
function parseTimeString(s) {
    for (var i = 0; i < timeParsePatterns.length; i++) {
        var re = timeParsePatterns[i].re;
        var handler = timeParsePatterns[i].handler;
        var bits = re.exec(s);
        if (bits) {
            return handler(bits);
        }
    }
    throw new Error("Invalid time string");
}

function magicTimeUd(input,vField,vID) {
    var messagespan = input.id + '-messages';
    try {
        var d = parseTimeString(input.value);
        input.value = getReadable(d);
        input.className = '';
        try {
            // Human readable time
            el = document.getElementById(messagespan);
            el.firstChild.nodeValue = d.toTimeString();
            el.className = 'normal';
        }
        catch (e) {
            // the message div is not in the document
        }
    }
    catch (e) {
        input.className = 'error';
        try {
            el = document.getElementById(messagespan);
            var message = e.message;
            // Fix for IE6 bug
            if (message.indexOf('is null or not an object') > -1) {
                message = 'Invalid time string';
            }
            el.firstChild.nodeValue = message;
            el.className = 'error';
        } catch (e){} // no message div
    }
    updateTC(vField,vID);
}

function magicTime(input,vField,vID) {
    var messagespan = input.id + '-messages';
    try {
        var d = parseTimeString(input.value);
        input.value = getReadable(d);
        input.className = '';
        try {
            // Human readable time
            el = document.getElementById(messagespan);
            el.firstChild.nodeValue = d.toTimeString();
            el.className = 'normal';
        }
        catch (e) {
            // the message div is not in the document
        }
    }
    catch (e) {
        input.className = 'error';
        try {
            el = document.getElementById(messagespan);
            var message = e.message;
            // Fix for IE6 bug
            if (message.indexOf('is null or not an object') > -1) {
                message = 'Invalid time string';
            }
            el.firstChild.nodeValue = message;
            el.className = 'error';
        } catch (e){} // no message div
    }
}

//Javascript name: My Date Time Picker
//Date created: 16-Nov-2003 23:19
//Scripter: TengYong Ng
//Website: http://www.rainforestnet.com
//Copyright (c) 2003 TengYong Ng
//FileName: DateTimePicker.js
//Version: 0.8
//Contact: contact@rainforestnet.com
// Note: Permission given to use this script in ANY kind of applications if
//       header lines are left unchanged.

//Global variables
var winCal;
var dtToday=new Date();
var Cal;
var docCal;
var MonthName=["January", "February", "March", "April", "May", "June","July",
   "August", "September", "October", "November", "December"];
var WeekDayName=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var exDateTime;//Existing Date and Time

//Configurable parameters
var cnTop="200";//top coordinate of calendar window.
var cnLeft="500";//left coordinate of calendar window
var WindowTitle ="DateTime Picker";//Date Time Picker title.
var WeekChar=2;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed.
var CellWidth=20;//Width of day cell.
var DateSeparator="-";//Date Separator, you can change it to "/" if you want.
var TimeMode=24;//default TimeMode value. 12 or 24

var ShowLongMonth=true;//Show long month name in Calendar header. example: "January".
var ShowMonthYear=true;//Show Month and Year in Calendar header.
var MonthYearColor="#cc0033";//Font Color of Month and Year in Calendar header.
var WeekHeadColor="#0099CC";//Background Color in Week header.
var SundayColor="#6699FF";//Background color of Sunday.
var SaturdayColor="#CCCCFF";//Background color of Saturday.
var WeekDayColor="white";//Background color of weekdays.
var FontColor="blue";//color of font in Calendar day cell.
var TodayColor="#FFFF33";//Background color of today.
var SelDateColor="#FFFF99";//Backgrond color of selected date in textbox.
var YrSelColor="#cc0033";//color of font of Year selector.
var ThemeBg="";//Background image of Calendar window.
//end Configurable parameters
//end Global variable

function NewCal(pCtrl,pFormat,pShowTime,pTimeMode)
{
   Cal=new Calendar(dtToday);
   if ((pShowTime!=null) && (pShowTime))
   {
      Cal.ShowTime=true;
      if ((pTimeMode!=null) &&((pTimeMode=='12')||(pTimeMode=='24')))
      {
         TimeMode=pTimeMode;
      }
   }
   if (pCtrl!=null)
      Cal.Ctrl=pCtrl;
   if (pFormat!=null)
      Cal.Format=pFormat.toUpperCase();

   exDateTime=document.getElementById(pCtrl).value;
   if (exDateTime!="")//Parse Date String
   {
      var Sp1;//Index of Date Separator 1
      var Sp2;//Index of Date Separator 2
      var tSp1;//Index of Time Separator 1
      var tSp1;//Index of Time Separator 2
      var strMonth;
      var strDate;
      var strYear;
      var intMonth;
      var YearPattern;
      var strHour;
      var strMinute;
      var strSecond;
      //parse month
      Sp1=exDateTime.indexOf(DateSeparator,0)
      Sp2=exDateTime.indexOf(DateSeparator,(parseInt(Sp1)+1));

      if ((Cal.Format.toUpperCase()=="DDMMYYYY") || (Cal.Format.toUpperCase()=="DDMMMYYYY"))
      {
         strMonth=exDateTime.substring(Sp1+1,Sp2);
         strDate=exDateTime.substring(0,Sp1);
      }
      else if ((Cal.Format.toUpperCase()=="MMDDYYYY") || (Cal.Format.toUpperCase()=="MMMDDYYYY"))
      {
         strMonth=exDateTime.substring(0,Sp1);
         strDate=exDateTime.substring(Sp1+1,Sp2);
      }
      if (isNaN(strMonth))
         intMonth=Cal.GetMonthIndex(strMonth);
      else
         intMonth=parseInt(strMonth,10)-1;
      if ((parseInt(intMonth,10)>=0) && (parseInt(intMonth,10)<12))
         Cal.Month=intMonth;
      //end parse month
      //parse Date
      if ((parseInt(strDate,10)<=Cal.GetMonDays()) && (parseInt(strDate,10)>=1))
         Cal.Date=strDate;
      //end parse Date
      //parse year
      strYear=exDateTime.substring(Sp2+1,Sp2+5);
      YearPattern=/^\d{4}$/;
      if (YearPattern.test(strYear))
         Cal.Year=parseInt(strYear,10);
      //end parse year
      //parse time
      if (Cal.ShowTime==true)
      {
         tSp1=exDateTime.indexOf(":",0)
         tSp2=exDateTime.indexOf(":",(parseInt(tSp1)+1));
         strHour=exDateTime.substring(tSp1,(tSp1)-2);
         Cal.SetHour(strHour);
         strMinute=exDateTime.substring(tSp1+1,tSp2);
         Cal.SetMinute(strMinute);
         strSecond=exDateTime.substring(tSp2+1,tSp2+3);
         Cal.SetSecond(strSecond);
      }
   }
   winCal=window.open("","DateTimePicker","toolbar=0,status=0,menubar=0,fullscreen=no,width=195,height=245,resizable=0,top="+cnTop+",left="+cnLeft);
   docCal=winCal.document;
   RenderCal();
}

function RenderCal()
{
   var vCalHeader;
   var vCalData;
   var vCalTime;
   var i;
   var j;
   var SelectStr;
   var vDayCount=0;
   var vFirstDay;

   docCal.open();
   docCal.writeln("<html><head><title>"+WindowTitle+"</title>");
   docCal.writeln("<script>var winMain=window.opener;</script>");
   docCal.writeln("</head><body background='"+ThemeBg+"' link="+FontColor+" vlink="+FontColor+"><form name='Calendar'>");

   vCalHeader="<table border=1 cellpadding=1 cellspacing=1 width='100%' align=\"center\" valign=\"top\">\n";
   //Month Selector
   vCalHeader+="<tr>\n<td colspan='7'><table border=0 width='100%' cellpadding=0 cellspacing=0><tr><td align='left'>\n";
   vCalHeader+="<select name=\"MonthSelector\" onChange=\"javascript:winMain.Cal.SwitchMth(this.selectedIndex);winMain.RenderCal();\">\n";
   for (i=0;i<12;i++)
   {
      if (i==Cal.Month)
         SelectStr="Selected";
      else
         SelectStr="";
      vCalHeader+="<option "+SelectStr+" value >"+MonthName[i]+"\n";
   }
   vCalHeader+="</select></td>";
   //Year selector
   vCalHeader+="\n<td align='right'><a href=\"javascript:winMain.Cal.DecYear();winMain.RenderCal()\"><b><font color=\""+YrSelColor+"\"><</font></b></a><font face=\"Verdana\" color=\""+YrSelColor+"\" size=2><b> "+Cal.Year+" </b></font><a href=\"javascript:winMain.Cal.IncYear();winMain.RenderCal()\"><b><font color=\""+YrSelColor+"\">></font></b></a></td></tr></table></td>\n";
   vCalHeader+="</tr>";
   //Calendar header shows Month and Year
   if (ShowMonthYear)
      vCalHeader+="<tr><td colspan='7'><font face='Verdana' size='2' align='center' color='"+MonthYearColor+"'><b>"+Cal.GetMonthName(ShowLongMonth)+" "+Cal.Year+"</b></font></td></tr>\n";
   //Week day header
   vCalHeader+="<tr bgcolor="+WeekHeadColor+">";
   for (i=0;i<7;i++)
   {
      vCalHeader+="<td align='center'><font face='Verdana' size='2'>"+WeekDayName[i].substr(0,WeekChar)+"</font></td>";
   }
   vCalHeader+="</tr>";
   docCal.write(vCalHeader);

   //Calendar detail
   CalDate=new Date(Cal.Year,Cal.Month);
   CalDate.setDate(1);
   vFirstDay=CalDate.getDay();
   vCalData="<tr>";
   for (i=0;i<vFirstDay;i++)
   {
      vCalData=vCalData+GenCell();
      vDayCount=vDayCount+1;
   }
   for (j=1;j<=Cal.GetMonDays();j++)
   {
      var strCell;
      vDayCount=vDayCount+1;
      if ((j==dtToday.getDate())&&(Cal.Month==dtToday.getMonth())&&(Cal.Year==dtToday.getFullYear()))
         strCell=GenCell(j,true,TodayColor);//Highlight today's date
      else
      {
         if (j==Cal.Date)
         {
            strCell=GenCell(j,true,SelDateColor);
         }
         else
         {
            if (vDayCount%7==0)
               strCell=GenCell(j,false,SaturdayColor);
            else if ((vDayCount+6)%7==0)
               strCell=GenCell(j,false,SundayColor);
            else
               strCell=GenCell(j,null,WeekDayColor);
         }
      }
      vCalData=vCalData+strCell;

      if((vDayCount%7==0)&&(j<Cal.GetMonDays()))
      {
         vCalData=vCalData+"</tr>\n<tr>";
      }
   }
   docCal.writeln(vCalData);
   //Time picker
   if (Cal.ShowTime)
   {
      var showHour;
      showHour=Cal.getShowHour();
      vCalTime="<tr>\n<td colspan='7' align='center'>";
      vCalTime+="<input type='text' name='hour' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+showHour+" onchange=\"javascript:winMain.Cal.SetHour(this.value)\">";
      vCalTime+=" : ";
      vCalTime+="<input type='text' name='minute' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Minutes+" onchange=\"javascript:winMain.Cal.SetMinute(this.value)\">";
      vCalTime+=" : ";
      vCalTime+="<input type='text' name='second' maxlength=2 size=1 style=\"WIDTH: 22px\" value="+Cal.Seconds+" onchange=\"javascript:winMain.Cal.SetSecond(this.value)\">";
      if (TimeMode==12)
      {
         var SelectAm =(parseInt(Cal.Hours,10)<12)? "Selected":"";
         var SelectPm =(parseInt(Cal.Hours,10)>=12)? "Selected":"";

         vCalTime+="<select name=\"ampm\" onchange=\"javascript:winMain.Cal.SetAmPm(this.options[this.selectedIndex].value);\">";
         vCalTime+="<option "+SelectAm+" value=\"AM\">AM</option>";
         vCalTime+="<option "+SelectPm+" value=\"PM\">PM<option>";
         vCalTime+="</select>";
      }
      vCalTime+="\n</td>\n</tr>";
      docCal.write(vCalTime);
   }
   //end time picker
   docCal.writeln("\n</table>");
   docCal.writeln("</form></body></html>");
   docCal.close();
}

function GenCell(pValue,pHighLight,pColor)//Generate table cell with value
{
   var PValue;
   var PCellStr;
   var vColor;
   var vHLstr1;//HighLight string
   var vHlstr2;
   var vTimeStr;

   if (pValue==null)
      PValue="";
   else
      PValue=pValue;

   if (pColor!=null)
      vColor="bgcolor=\""+pColor+"\"";
   else
      vColor="";
   if ((pHighLight!=null)&&(pHighLight))
      {vHLstr1="color='red'><b>";vHLstr2="</b>";}
   else
      {vHLstr1=">";vHLstr2="";}

   if (Cal.ShowTime)
   {
      vTimeStr="winMain.document.getElementById('"+Cal.Ctrl+"').value+=' '+"+"winMain.Cal.getShowHour()"+"+':'+"+"winMain.Cal.Minutes"+"+':'+"+"winMain.Cal.Seconds";
      if (TimeMode==12)
         vTimeStr+="+' '+winMain.Cal.AMorPM";
   }
   else
      vTimeStr="";
   PCellStr="<td "+vColor+" width="+CellWidth+" align='center'><font face='verdana' size='2'"+vHLstr1+"<a href=\"javascript:winMain.document.getElementById('"+Cal.Ctrl+"').value='"+Cal.FormatDate(PValue)+"';"+vTimeStr+";window.close();\">"+PValue+"</a>"+vHLstr2+"</font></td>";
   return PCellStr;
}

function Calendar(pDate,pCtrl)
{
   //Properties
   this.Date=pDate.getDate();//selected date
   this.Month=pDate.getMonth();//selected month number
   this.Year=pDate.getFullYear();//selected year in 4 digits
   this.Hours=pDate.getHours();

   if (pDate.getMinutes()<10)
      this.Minutes="0"+pDate.getMinutes();
   else
      this.Minutes=pDate.getMinutes();

   if (pDate.getSeconds()<10)
      this.Seconds="0"+pDate.getSeconds();
   else
      this.Seconds=pDate.getSeconds();

   this.MyWindow=winCal;
   this.Ctrl=pCtrl;
   this.Format="ddMMyyyy";
   this.Separator=DateSeparator;
   this.ShowTime=false;
   if (pDate.getHours()<12)
      this.AMorPM="AM";
   else
      this.AMorPM="PM";
}

function GetMonthIndex(shortMonthName)
{
   for (i=0;i<12;i++)
   {
      if (MonthName[i].substring(0,3).toUpperCase()==shortMonthName.toUpperCase())
      {  return i;}
   }
}
Calendar.prototype.GetMonthIndex=GetMonthIndex;

function IncYear()
{  Cal.Year++;}
Calendar.prototype.IncYear=IncYear;

function DecYear()
{  Cal.Year--;}
Calendar.prototype.DecYear=DecYear;

function SwitchMth(intMth)
{  Cal.Month=intMth;}
Calendar.prototype.SwitchMth=SwitchMth;

function SetHour(intHour)
{
   var MaxHour;
   var MinHour;
   if (TimeMode==24)
   {  MaxHour=23;MinHour=0}
   else if (TimeMode==12)
   {  MaxHour=12;MinHour=1}
   else
      alert("TimeMode can only be 12 or 24");
   var HourExp=new RegExp("^\\d\\d$");
   if (HourExp.test(intHour) && (parseInt(intHour,10)<=MaxHour) && (parseInt(intHour,10)>=MinHour))
   {
      if ((TimeMode==12) && (Cal.AMorPM=="PM"))
      {
         if (parseInt(intHour,10)==12)
            Cal.Hours=12;
         else
            Cal.Hours=parseInt(intHour,10)+12;
      }
      else if ((TimeMode==12) && (Cal.AMorPM=="AM"))
      {
         if (intHour==12)
            intHour-=12;
         Cal.Hours=parseInt(intHour,10);
      }
      else if (TimeMode==24)
         Cal.Hours=parseInt(intHour,10);
   }
}
Calendar.prototype.SetHour=SetHour;

function SetMinute(intMin)
{
   var MinExp=new RegExp("^\\d\\d$");
   if (MinExp.test(intMin) && (intMin<60))
      Cal.Minutes=intMin;
}
Calendar.prototype.SetMinute=SetMinute;

function SetSecond(intSec)
{
   var SecExp=new RegExp("^\\d\\d$");
   if (SecExp.test(intSec) && (intSec<60))
      Cal.Seconds=intSec;
}
Calendar.prototype.SetSecond=SetSecond;

function SetAmPm(pvalue)
{
   this.AMorPM=pvalue;
   if (pvalue=="PM")
   {
      this.Hours=(parseInt(this.Hours,10))+12;
      if (this.Hours==24)
         this.Hours=12;
   }
   else if (pvalue=="AM")
      this.Hours-=12;
}
Calendar.prototype.SetAmPm=SetAmPm;

function getShowHour()
{
   var finalHour;
    if (TimeMode==12)
    {
      if (parseInt(this.Hours,10)==0)
      {
         this.AMorPM="AM";
         finalHour=parseInt(this.Hours,10)+12;
      }
      else if (parseInt(this.Hours,10)==12)
      {
         this.AMorPM="PM";
         finalHour=12;
      }
      else if (this.Hours>12)
      {
         this.AMorPM="PM";
         if ((this.Hours-12)<10)
            finalHour="0"+((parseInt(this.Hours,10))-12);
         else
            finalHour=parseInt(this.Hours,10)-12;
      }
      else
      {
         this.AMorPM="AM";
         if (this.Hours<10)
            finalHour="0"+parseInt(this.Hours,10);
         else
            finalHour=this.Hours;
      }
   }
   else if (TimeMode==24)
   {
      if (this.Hours<10)
         finalHour="0"+parseInt(this.Hours,10);
      else
         finalHour=this.Hours;
   }
   return finalHour;
}
Calendar.prototype.getShowHour=getShowHour;

function GetMonthName(IsLong)
{
   var Month=MonthName[this.Month];
   if (IsLong)
      return Month;
   else
      return Month.substr(0,3);
}
Calendar.prototype.GetMonthName=GetMonthName;

function GetMonDays()//Get number of days in a month
{
   var DaysInMonth=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
   if (this.IsLeapYear())
   {
      DaysInMonth[1]=29;
   }
   return DaysInMonth[this.Month];
}
Calendar.prototype.GetMonDays=GetMonDays;

function IsLeapYear()
{
   if ((this.Year%4)==0)
   {
      if ((this.Year%100==0) && (this.Year%400)!=0)
      {
         return false;
      }
      else
      {
         return true;
      }
   }
   else
   {
      return false;
   }
}
Calendar.prototype.IsLeapYear=IsLeapYear;

function FormatDate(pDate)
{
   if (this.Format.toUpperCase()=="DDMMYYYY")
      return (pDate+DateSeparator+(this.Month+1)+DateSeparator+this.Year);
   else if (this.Format.toUpperCase()=="DDMMMYYYY")
      return (pDate+DateSeparator+this.GetMonthName(false)+DateSeparator+this.Year);
   else if (this.Format.toUpperCase()=="MMDDYYYY")
      return ((this.Month+1)+DateSeparator+pDate+DateSeparator+this.Year);
   else if (this.Format.toUpperCase()=="MMMDDYYYY")
      return (this.GetMonthName(false)+DateSeparator+pDate+DateSeparator+this.Year);
}
Calendar.prototype.FormatDate=FormatDate;

function gotoPage(vSrc) {
   var vPage = document.getElementById('DPg'+vSrc).value;
   window.location.href = "disppage.php?num="+vPage;
}

function pageUpDn(vDirection) {
   window.location.href = "disppage.php?id=Item&num="+vDirection+"&url=items.php";
}

function recPerPage(vSrc){
   vRecPerPage = document.getElementById('RecPerPage'+vSrc).value;
   window.location.href = 'recperpage.php?num='+vRecPerPage;
}

function confirmDel(vID,vType) {
   var answer = confirm('Delete this '+vType+' #'+vID+'?');
   if (answer){
      Url = 'delrecord.php?id='+vID;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }

      xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4) {
            document.getElementById('Rec_'+vID).innerHTML="<div class='smalltxtbrd bttmlinelitebl'>Deleted "+vType+" "+vID+"...</div>";
            document.getElementById('pageStatus').style.visibility = "hidden";
          }
      }
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   }
}

function GetXmlHttpObject() {
   var xmlHttp=null;

   try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
   }
   catch (e) {
      // Internet Explorer
      try {
         xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
      }
      catch (e) {
         xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
      }
   }
   return xmlHttp;
}

function stateChange() {
   if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete') {
      document.getElementById('Stats').innerHTML=xmlHttp.responseText;
      document.getElementById('pageStatus').style.visibility = "hidden";
   }
}

function stateChange2() {
   if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete') {
      document.getElementById('newItem').innerHTML=xmlHttp.responseText;
      document.getElementById('pageStatus').style.visibility = "hidden";
   }
}

function stateChange3() {
   if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete') {
   }
}

function stateChange4() {
   if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete') {
      document.getElementById('newAcct').innerHTML=xmlHttp.responseText;
      document.getElementById('AcctStatus').style.visibility = "hidden";
   }
}

function stateChange5() {
   if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete') {
      document.getElementById('newMU').innerHTML=xmlHttp.responseText;
      document.getElementById('MUStatus').style.visibility = "hidden";
   }
}

function updateItem(vField,vID){
   vDivID = vID;
   document.getElementById('itemStatus_'+vID).style.visibility = "visible";
   vTotCnt = document.getElementById('TotCnt_'+vID).value;
   vCntr = document.getElementById('Cntr_'+vID).value;
   vValue = document.getElementById(vField+'_'+vID).value;
   Url = 'items_update.php?id='+vID+'&fld='+vField+'&val='+vValue+'&tc='+vTotCnt+'&c='+vCntr;
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }
   document.getElementById('pageStatus').style.visibility = "visible";
   xmlHttp.onreadystatechange=stateChange;
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function addItem(){
   document.getElementById('itemStatus').style.visibility = "visible";
   vName = document.getElementById('Name').value;
   vRefNum = document.getElementById('RefNum').value;
   vInvItemType = document.getElementById('Accnt').value;
   vDescription = document.getElementById('Description').value;
   vQnty = document.getElementById('Qnty').value;
   vAmtPur = document.getElementById('AmtPur').value;
   vPrice = document.getElementById('Price').value;
   vPrice2 = document.getElementById('Price2').value;
   vPrice3 = document.getElementById('Price3').value;
   vCost = document.getElementById('Cost').value;
   vTaxable = document.getElementById('Taxable').value;
   vDispCat = document.getElementById('DispCat').value;
   vDispCat = document.getElementById('CatalogID').value;
   vSmallImg = document.getElementById('SmallImg').value;
   vLargeImg = document.getElementById('LargeImg').value;
   vEnabled = document.getElementById('Enabled').value;

   if (vName == "" || vRefNum == "" || vAccnt == "" || vQnty == "" || vPrice == "" || vPrice2 == "" || vPrice3 == "" || vCost == "" || vDispCat == "" || vCatalogID == "") {
      alert("Please fill-in all required fields and try again...");
      document.getElementById('itemStatus').style.visibility = "hidden";
      return;
   } else {
      Url = 'items_add.php?1='+escape(vName)+'&2='+escape(vRefNum)+'&3='+escape(vInvItemType)+'&4='+escape(vDescription)+'&5='+vQnty+'&6='+vAmtPur+'&7='+vPrice+'&8='+vPrice2+'&9='+vPrice3+'&10='+vCost+'&11='+vTaxable+'&12='+escape(vDispCat)+'&13='+escape(vSmallImg)+'&14='+escape(vLargeImg)+'&15='+vEnabled;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }
      xmlHttp.onreadystatechange=stateChange2;
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   }
}

function printData() {
   dispWindow('print_data.php',1000,500,'PrintData','');
}

function delPage() {
   var answer = confirm('Delete all items displayed on this page?');
   if (answer){
      window.location.href = 'items_del.php?id=page';
   }
}

function updateField(fld,id,filtr) {
   var myurl = 'updatefield.php';
   newVal =document.getElementById(fld + '_' + id).value;
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
      alert ('Your browser does not support AJAX!');
      return;
   }

   document.getElementById('Status_'+id).style.visibility='visible';
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('Rec_'+id).innerHTML=xmlHttp.responseText;
         //document.getElementById('Status_'+id).style.visibility='hidden';
       }
   }
   xmlHttp.open('GET', myurl + '?1=' + escape(fld) + '&2=' + filtr + '&3=' + escape(newVal), true);
   xmlHttp.send(null);
}


function updateMU(fld,id,cntr) {
   var myurl = 'mu_update.php';
   newVal =document.getElementById(fld + '_' + id).value;
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
      alert ('Your browser does not support AJAX!');
      return;
   }

   document.getElementById('Status_'+id).style.visibility='visible';
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('Rec_'+id).innerHTML=xmlHttp.responseText;
         document.getElementById('Status_'+id).style.visibility='hidden';
       }
   }
   xmlHttp.open('GET', myurl + '?1=' + escape(id) + '&2=' + fld + '&3=' + escape(newVal)+'&4='+cntr, true);
   xmlHttp.send(null);
}

function addEmployee(){
   document.getElementById('employStatus').style.visibility = "visible";
   vLastName = document.getElementById('LastName').value;
   vFirstName = document.getElementById('FirstName').value;
   vHomePhone = document.getElementById('HomePhone').value;
   vEmail = document.getElementById('Email').value;
   vCell = document.getElementById('Cell').value;
   vLoginUser = document.getElementById('LoginUser').value;
   vLoginPasswd = document.getElementById('LoginPasswd').value;
   vUsrLvl = document.getElementById('UsrLvl').value;
   vAbbrv = document.getElementById('Abbrv').value;
   vEnabled = document.getElementById('Enabled').value;
   vNotes = document.getElementById('Notes').value;
   if (vLastName == "" || vFirstName == "" || vLoginUser == "" || vLoginPasswd == "" || vUsrLvl == "" || vAbbrv == "" || vEnabled == "" ) {
      alert("Please fill-in all required fields and try again...");
      document.getElementById('employStatus').style.visibility = "hidden";
      return;
   } else {
      Url = 'employees_add.php?1='+escape(vLastName)+'&2='+escape(vFirstName)+'&3='+escape(vHomePhone)+'&4='+escape(vEmail)+'&5='+escape(vCell)+'&6='+escape(vLoginUser)+'&7='+escape(vLoginPasswd)+'&8='+escape(vAbbrv)+'&9='+escape(vUsrLvl)+'&10='+escape(vEnabled)+'&11='+escape(vNotes);
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }

      xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4) {
            document.getElementById('newEmployee').innerHTML=xmlHttp.responseText;
            document.getElementById('pageStatus').style.visibility = "hidden";
            // Update EMployee Display
            Url = 'employees_div3.php';
            xmlHttp = GetXmlHttpObject();

            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4) {
                  document.getElementById('Employees').innerHTML=xmlHttp.responseText;
                }
            }
            xmlHttp.open('GET',Url,true);
            xmlHttp.send(null);
          }
      }
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   }
}

function dispMenu(){
   if(navigator.appVersion.indexOf("MSIE")==-1){
      return;
   }
   var i,k,g,lg,r=/\s*p7hvr/,nn='',c,cs='p7hvr',bv='p7menubar';
   for(i=0;i<10;i++){
      g=document.getElementById(bv+nn);
      if(g){
         lg=g.getElementsByTagName("LI");
         if(lg){
            for(k=0;k<lg.length;k++){
               lg[k].onmouseover=function(){
                  c=this.className;cl=(c)?c+' '+cs:cs;
                  this.className=cl;
               };
               lg[k].onmouseout=function(){
                  c=this.className;
                  this.className=(c)?c.replace(r,''):'';
               };
            }
         }
      }
      nn=i+1;
   }
}

function checkall(){
   _CBValue = document.getElementById("HdrItemCB").checked;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="checkbox" && a.substr(0,6)=="ItemCB"){
         document.ActionForm.elements[i].checked=_CBValue;
      }
   }
}

function GetAcctID(){
   vAcctID = document.getElementById('AccountID').value;
   vSOID = document.getElementById('SOID').value;
   vDateStamp = escape(document.getElementById('DateStamp').value);
   vStatus = escape(document.getElementById('Status').value);
   vPONum = escape(document.getElementById('PONum').value);
   document.getElementById('SODetailsStatus').style.visibility = "hidden";
   if(vAcctID != ""){
      Url = 'so_load_acct.php?1='+vAcctID+'&2='+vSOID+'&3='+vDateStamp+'&4='+vStatus+'&5='+vPONum;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }

      xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4) {
            document.getElementById('SODetails').innerHTML=xmlHttp.responseText;
            document.getElementById('SODetailsStatus').style.visibility = "hidden";
          }
      }
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   } else {
     alert ('Invalid AccountID, skipping loading Account data...');
     return;
   }
}

function ItemAdd(){
   vAcctID = document.getElementById('AccountID').value;
   vSOID = document.getElementById('SOID').value;
   vQty = document.getElementById('AddItemQty').value;
   vItemID = document.getElementById('AddItemID').value;
   document.getElementById('SOItemsAddStatus').style.visibility = "visible";
   if(vQty > 0){
      Url = 'so_additem.php?1='+vAcctID+'&2='+vSOID+'&3='+vItemID+'&4='+vQty;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }

      xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4) {
            document.getElementById('SOItems').innerHTML=xmlHttp.responseText;
            document.getElementById('SOItemsAddStatus').style.visibility = "hidden";
            document,getElementById('AddItemQty').value="";
          }
      }
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   } else {
      alert("Invalid Quantity Amount");
   }
}

function updateSO(vDiv,vFld) {
   vValue = document.getElementById(vFld).value;
   Url = 'so_update.php?1='+vSOID+'&2='+vFld+'&3='+escape(vValue);
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }

   if(vDiv==1) {
      document.getElementById('SODetails').style.visibility = "visible";
   } else if (vDiv==2) {
      document.getElementById('SODetailsStatus').style.visibility = "visible";
   }
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         if(vDiv==1) {
            document.getElementById('SODetails').innerHTML=xmlHttp.responseText;
            document.getElementById('SODetailsStatus').style.visibility = "hidden";
         } else if (vDiv==2) {
            document.getElementById('SONotes').innerHTML=xmlHttp.responseText;
            document.getElementById('SONotesStatus').style.visibility = "hidden";
         }
       }
   }
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function udItem(vCntr,vFld) {
   vValue = document.getElementById(vFld+'_'+vCntr).value;
   vSOID = document.getElementById('SOID').value;
   vSOIID = document.getElementById('SOIID_'+vCntr).value;
   Url = 'so_updateitem.php?1='+vSOID+'&2='+vSOIID+'&3='+vFld+'&4='+escape(vValue);
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }

   document.getElementById('SOItemStatus_'+vSOIID).style.visibility = "visible";
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('SOItem_'+vSOIID).innerHTML=xmlHttp.responseText;
         //document.getElementById('SOItemStatus_'+vSOIID).style.visibility = "hidden";
       }
   }
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
   // set time, it's in milliseconds
   var today = new Date();
   today.setTime( today.getTime() );

   /*  if the expires variable is set, make the correct
   expires time, the current script below will set
   it for x number of days, to make it for hours,
   delete * 24, for minutes, delete * 60 * 24 */
   if ( expires ){
      expires = expires * 1000 * 60 * 60 * 24;
   }
   var expires_date = new Date( today.getTime() + (expires) );

   document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
   ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
   // first we'll split this cookie up into name/value pairs
   // note: document.cookie only returns name=value, not the other components
   var a_all_cookies = document.cookie.split( ';' );
   var a_temp_cookie = '';
   var cookie_name = '';
   var cookie_value = '';
   var b_cookie_found = false; // set boolean t/f default f

   for ( i = 0; i < a_all_cookies.length; i++ )
   {
      // now we'll split apart each name=value pair
      a_temp_cookie = a_all_cookies[i].split( '=' );


      // and trim left/right whitespace while we're at it
      cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

      // if the extracted name matches passed check_name
      if ( cookie_name == check_name )
      {
         b_cookie_found = true;
         // we need to handle case where cookie has no value but exists (no = sign, that is):
         if ( a_temp_cookie.length > 1 )
         {
            cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
         }
         // note that in cases where cookie is initialized but no value, null is returned
         return cookie_value;
         break;
      }
      a_temp_cookie = null;
      cookie_name = '';
   }
   if ( !b_cookie_found )
   {
      return null;
   }
}

function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function AddToCart(ItemID) {
   if (eval('document.ItemForm_'+ItemID+'.Qty.value') == "" || eval('document.ItemForm_'+ItemID+'.Qty.value') < 1) {
       alert("Invalid Qty...");return;
   } else {
       document.getElementById('ItemForm_'+ItemID).submit();
   }
}

function removeCheckedItems(){
   vID = "";
   x = 0;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="checkbox" && a.substr(0,6)=="ItemCB" && document.ActionForm.elements[i].checked == 1){
         x++;
         if (i == 0) {
            vID = a.substr(7);
         } else {
            vID = vID + ',' + a.substr(7);
         }
      }
   }
   if (vID != "") {
      var answer = confirm("Delete the "+x+" selected shopping cart item(s)?");
      if (answer){
         window.location.href = 'shopcart_del.php?id=' + vID;
      }
   } else {
      alert("No items selected to delete...");
   }
}

function removeCheckedItems2(vGroupID){
   vID = "";
   x = 0;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="checkbox" && a.substr(0,6)=="ItemCB" && document.ActionForm.elements[i].checked == 1){
         x++;
         if (vID == "") {
            vID = document.getElementById("SLID_"+a.substr(7)).value;
         } else {
            vID = vID + "," + document.getElementById("SLID_"+a.substr(7)).value;
         }
      }
   }
   if (vID != "") {
      var answer = confirm("Delete the "+x+" selected shopping list item(s)?");
      if (answer){
         window.location.href = 'shoplists_itemdel.php?1=' + vGroupID + '&2=' + vID;
      }
   } else {
      alert("No items selected to delete...");
   }
}

function QtyChng(ItemID,Qty){
   if ( Qty > 0) {
      window.location.href = 'shopcart_qty.php?id=' + ItemID + '&qty=' + Qty;
   } else {
      alert("Invalid quantity amount...");
   }
}

function UpdateQty(){
   vID = "";
   x = 0;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="text" && a.substr(0,4)=="Qty_"){
         x++;
         b = document.ActionForm.elements[i].value;
         if (vID == "") {
            vID = a.substr(4)+'-'+b;
         } else {
            vID = vID + ',' + a.substr(4)+'-'+b;
         }
      }
   }
   if (vID != "") {
      window.location.href = 'shopcart_qty2.php?id=' + vID;
   } else {
      alert("No items found to update quantities...");
   }
}

function UpdateSLQty(vGroupID){
   vID = "";
   x = 0;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="text" && a.substr(0,4)=="Qty_"){
         x++;
         b = document.ActionForm.elements[i].value;
         if (vID == "") {
            vID = a.substr(4)+'-'+b;
         } else {
            vID = vID + ',' + a.substr(4)+'-'+b;
         }
      }
   }
   if (vID != "") {
      window.location.href = 'shoplists_qty.php?1='+vGroupID+'&2='+vID;
   } else {
      alert("No items found to update quantities...");
   }
}

function moveToShopList(){
   vID = "";
   x = 0;
   ShopList = document.getElementById('sltShopList').value;
   if (ShopList != "-1") {
      for(i=0; i<document.ActionForm.elements.length; i++){
         a = document.ActionForm.elements[i].name;
         if(document.ActionForm.elements[i].type=="checkbox" && a.substr(0,6)=="ItemCB" && document.ActionForm.elements[i].checked == 1){
            x++;
            if (vID == "") {        
               vID = document.getElementById('ItemID_'+a.substr(7)).value;
            } else {
               vID = vID + ',' + document.getElementById('ItemID_'+a.substr(7)).value;
            }
         }
      }
      if (vID != "") {
         var answer = confirm("Move the "+x+" selected shopping cart item(s) to "+ShopList+" shopping list?");
         if (answer){
            window.location.href = 'shoplists_moveto.php?gid='+ShopList+'&id=' + vID;
         } else {
            document.all('sltShopList').selectedIndex=0
         }
      } else {
         document.all('sltShopList').selectedIndex=0
         alert("No item(s) selected to be moved to Temporary shopping list, please select items to move and try again...");
      }
   }
}

function moveSLtoCart(){
   vID = "";
   x = 0;
   for(i=0; i<document.ActionForm.elements.length; i++){
      a = document.ActionForm.elements[i].name;
      if(document.ActionForm.elements[i].type=="checkbox" && a.substr(0,6)=="ItemCB" && document.ActionForm.elements[i].checked == 1){
         x++;
         if (vID == "") {        
            vID = document.getElementById('SLID_'+a.substr(7)).value;
         } else {
            vID = vID + ',' + document.getElementById('SLID_'+a.substr(7)).value;
         }
      }
   }
   if (vID != "") {
      var answer = confirm("Move the "+x+" selected shopping list item(s) to shopping cart?");
      if (answer){
         window.location.href = 'shoplists_tocart.php?1='+ vID;
      }
   } else {
      alert("No item(s) selected to be moved to shopping cart, please select items to move and try again...");
   }
}

function moveSLtoCart2(vGroupID){
   var answer = confirm("Move the contents of the shopping list, "+vGroupID+", to the shopping cart?");
   if (answer){
      window.location.href = 'shoplists_tocart2.php?1='+ vGroupID;
   }
}

function ClearCart(){
   var answer = confirm("Clear all items from shopping cart?");
   if (answer){
      window.location.href = 'shopcart_clear.php';
   }
}

function ShopListDel(vGroupID) {
   if (vGroupID != "") {
      var answer = confirm("Delete the shopping list, "+vGroupID+"?");
      if (answer){
         window.location.href = 'shoplists_del.php?id=' + vGroupID;
      }
   }
}

function shopListChngName(vGroupID) {
   vGroupIDNew = document.getElementById('GroupID_'+vGroupID).value;
   if (vGroupID != vGroupIDNew) {
      var answer = confirm("Rename shopping cart, "+vGroupID+", to "+vGroupIDNew+"?");
      if (answer){
         window.location.href = 'shoplists_rename.php?1='+vGroupID+'&2='+vGroupIDNew;
      }
   } else {
      alert("No change in shopping list name, skipping rename...");
   }
}

function udSOField(vSOID,vFld) {
   vValue = document.getElementById(vFld).value;
   Url = 'so_update.php?1='+vSOID+'&2='+vFld+'&3='+escape(vValue);
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }

   document.getElementById('SOStatus').style.visibility = "visible";
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         if(vDiv==1) {
            document.getElementById('SODetails').innerHTML=xmlHttp.responseText;
            document.getElementById('SODetailsStatus').style.visibility = "hidden";
         } else if (vDiv==2) {
            document.getElementById('SONotes').innerHTML=xmlHttp.responseText;
            document.getElementById('SONotesStatus').style.visibility = "hidden";
         }
       }
   }
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function addAcct(){
   document.getElementById('AcctStatus').style.visibility = "visible";
   vFirstName = document.getElementById('FirstName').value;
   vLastName = document.getElementById('LastName').value;
   vBCompany = document.getElementById('BCompany').value;
   vBAdd1 = document.getElementById('BAdd1').value;
   vBAdd2 = document.getElementById('BAdd2').value;
   vBCity = document.getElementById('BCity').value;
   vBState = document.getElementById('BState').value;
   vBZip1 = document.getElementById('BZip1').value;
   vBZip2 = document.getElementById('BZip2').value;
   vRemarks = document.getElementById('Remarks').value;
   vSCompany = document.getElementById('SCompany').value;
   vSAdd1 = document.getElementById('SAdd1').value;
   vSAdd2 = document.getElementById('SAdd2').value;
   vSCity = document.getElementById('SCity').value;
   vSState = document.getElementById('SState').value;
   vSZip1 = document.getElementById('SZip1').value;
   vSZip2 = document.getElementById('SZip2').value;
   vEmail = document.getElementById('Email').value;
   vBTel1 = document.getElementById('BTel1').value;
   vBTel2 = document.getElementById('BTel2').value;
   vBTel3 = document.getElementById('BTel3').value;
   vFax1 = document.getElementById('Fax1').value;
   vFax2 = document.getElementById('Fax2').value;
   vFax3 = document.getElementById('Fax3').value;
   vPassword = document.getElementById('Password').value;
   vEmailInv = document.getElementById('EmailInv').value;
   vTerms = document.getElementById('Terms').value;
   vTaxExempt = document.getElementById('TaxExempt').value;
   vTaxID = document.getElementById('TaxID').value;
   vSalesID = document.getElementById('SalesID').value;
   vEmailPromo = document.getElementById('EmailPromo').value;
   vNewsLetter = document.getElementById('NewsLetter').value;
   
   if (vFirstName == "" || vLastName == "" || vBCompany == "" || vBAdd1 == "" || vBCity == "" || vBState == "" || vBZip1== "" || vSCompany == "" || vSAdd1 == "" || vSCity == ""|| vSState == ""|| vSZip1 == ""|| vEmail == ""|| vBTel1 == ""|| vBTel2 == ""|| vBTel3 == ""|| vFax1 == ""|| vFax2 == ""|| vFax3 == "" || vPassword == "" || vEmailInv == "" || vTerms == "" || vTaxExempt == "" || vSalesID == "" || vEmailPromo == "" || vNewsLetter == "" ) {
      alert("Please fill-in all required fields and try again...");
      document.getElementById('AcctStatus').style.visibility = "hidden";
      return;
   } else {
      if (vPassword.length < 6) {
         alert("Password to short 6 chars minimum...");
         document.getElementById('AcctStatus').style.visibility = "hidden";
         return;
      }
      Url = 'acct_add.php?1='+escape(vFirstName)+'&2='+escape(vLastName)+'&3='+escape(vBCompany)+'&4='+escape(vBAdd1)+'&5='+escape(vBAdd2)+'&6='+escape(vBCity)+'&7='+escape(vBState)+'&8='+escape(vBZip1)+'&9='+escape(vBZip2)+'&10='+escape(vRemarks)+'&11='+escape(vSCompany)+'&12='+escape(vSAdd1)+'&13='+escape(vSAdd2)+'&14='+escape(vSCity)+'&15='+escape(vSState)+'&16='+escape(vSZip1)+'&17='+escape(vSZip2)+'&18='+escape(vEmail)+'&19='+escape(vBTel1)+'&20='+escape(vBTel2)+'&21='+escape(vBTel3)+'&22='+escape(vFax1)+'&23='+escape(vFax2)+'&24='+escape(vFax3)+'&25='+escape(vPassword)+'&26='+escape(vEmailInv)+'&27='+escape(vTerms)+'&28='+escape(vTaxExempt)+'&29='+escape(vTaxID)+'&30='+escape(vSalesID)+'&31='+vEmailPromo+'&32='+vNewsLetter;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }
      xmlHttp.onreadystatechange=stateChange4;
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   }
}

function addMU(){
   document.getElementById('MUStatus').style.visibility = "visible";
   vMethod = document.getElementById('Method').value;
   vType = document.getElementById('Type').value;
   vTypeID = document.getElementById('TypeID').value;
   vMUType = document.getElementById('MUType').value;
   vMUTypeID = document.getElementById('MUTypeID').value;
   vMUPerc = document.getElementById('MUPerc').value;
   vStartDate = document.getElementById('StartDate').value;
   vEndDate = document.getElementById('EndDate').value;
   vEnabled = document.getElementById('Enabled').value;
   if (vMethod == "" || vType == "" || vTypeID == "" || vMUType == "" || vMUTypeID == "" || vMUPerc == "" || vEnabled == "" ) {
      alert("Please fill-in all required fields and try again...");
      document.getElementById('MUStatus').style.visibility = "hidden";
      return;
   } else {
      if(vStartDate != "") {
         if (!isDate(vStartDate)) {
            alert("Invalid Start Date...");
            document.getElementById('MUStatus').style.visibility = "hidden";
            return;
         }
      }
      if(vEndDate != "") {
         if (!isDate(vEndDate)) {
            alert("Invalid End Date...");
            document.getElementById('MUStatus').style.visibility = "hidden";
            return;
         }
      }
      Url = 'mu_add.php?1='+escape(vMethod)+'&2='+escape(vType)+'&3='+escape(vTypeID)+'&4='+escape(vMUType)+'&5='+escape(vMUTypeID)+'&6='+escape(vMUPerc)+'&7='+escape(vStartDate)+'&8='+escape(vEndDate)+'&9='+escape(vEnabled);
      window.location=Url;
   }
}

function isDate(dateStr) {
   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
   var matchArray = dateStr.match(datePat); // is the format ok?

   if (matchArray == null) {
      alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
      return false;
   }

   month = matchArray[1]; // parse date into variables
   day = matchArray[3];
   year = matchArray[5];

   if (month < 1 || month > 12) { // check month range
      alert("Month must be between 1 and 12.");
      return false;
   }

   if (day < 1 || day > 31) {
      alert("Day must be between 1 and 31.");
      return false;
   }

   if ((month==4 || month==6 || month==9 || month==11) && day==31) {
      alert("Month "+month+" doesn`t have 31 days!")
      return false;
   }

   if (month == 2) { // check for february 29th
      var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
      if (day > 29 || (day==29 && !isleap)) {
         alert("February " + year + " doesn`t have " + day + " days!");
         return false;
      }
   }
   return true; // date is valid
}

function updateMUAdd(){
   vMethod = document.getElementById('Method').value;
   vType = document.getElementById('Type').value;
   vTypeID = document.getElementById('TypeID').value;
   vMUType = document.getElementById('MUType').value;
   vMUTypeID = document.getElementById('MUTypeID').value;
   vMUPerc = document.getElementById('MUPerc').value;
   vStartDate = document.getElementById('StartDate').value;
   vEndDate = document.getElementById('EndDate').value;
   vEnabled = document.getElementById('Enabled').value;
   vDiscPerc = document.getElementById('DiscPerc').value;
   Url = 'mu_add_update.php?1='+escape(vMethod)+'&2='+escape(vType)+'&3='+escape(vTypeID)+'&4='+escape(vMUType)+'&5='+escape(vMUTypeID)+'&6='+escape(vMUPerc)+'&7='+escape(vStartDate)+'&8='+escape(vEndDate)+'&9='+vEnabled+'&10='+vDiscPerc;
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }

   document.getElementById('MUStatus').style.visibility = "visible";
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('newMU').innerHTML=xmlHttp.responseText;
       }
   }
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function checkBoxMU(vState){
   for(i=0; i<document.MarkUpsForm.elements.length; i++){
      if(document.MarkUpsForm.elements[i].type=="checkbox"){
         document.MarkUpsForm.elements[i].checked=vState;
      }
   }
}

function copyMU(){
   // Verify that something has been checked
   x=0;
   vType = document.getElementById('OptType').value;
   vTypeID = document.getElementById('OptTypeID').value.toUpperCase();
   vClear = document.getElementById('OptClear').value;
   for(i=0; i<document.MarkUpsForm.elements.length; i++){
      if(document.MarkUpsForm.elements[i].type=="checkbox" && document.MarkUpsForm.elements[i].checked==1){
         x++;
         a = document.MarkUpsForm.elements[i].name;
         if (x == 1) {
            vID = a.substr(3);
         } else {
            vID = vID + ',' + a.substr(3);
         }
      }
   }
   if(x==0){
      alert("No MarkUps selected to copy...");
   } else {
      if(vTypeID != ""){
         if((vType == "Acct" && vTypeID == parseInt(vTypeID)) || vType == "Group" ) {
            if(vClear == "Y"){
               vClrMsg = " "; 
            } else {
               vClrMsg = " NOT to "
            }
            var answer = confirm('Copy '+x+' selected markup(s) to type "'+vType+'" named "'+vTypeID+'", and'+vClrMsg+'clear any existing MarkUps found to have the same Type and TypeID?');
            if (answer){
               dispWindow('mu_copy.php?1='+vID+'&2='+vType+'&3='+vTypeID+'&4='+vClear,400,120,"CopyMarkUps","");
            }
         } else {
            alert("Invalid TypeID, should be an ID number for Type 'Acct'...");
         }
      } else {
         alert("Type ID can not be blank...");
      }
   }
}

function quickFilterMU(){
   vTypeID=document.getElementById('QFTypeID').value;
   window.location = 'mu_quickfilter.php?1='+vTypeID;
}

function printCart() {
   if(top.document.title == 'D and N Sales - Shopping Cart Print'){
      window.print()
   } else {
      dispWindow('shopcart_print.php',900,600,"ShopCart","");
   }
}

function updateOptMU(){
   vOptType = document.getElementById('OptType').value;
   vOptTypeID = document.getElementById('OptTypeID').value;
   vOptClear = document.getElementById('OptClear').value;
   Url = 'mu_opt_update.php?1='+escape(vOptType)+'&2='+escape(vOptTypeID)+'&3='+escape(vOptClear);
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ('Browser does not support HTTP Request');
     return;
   }

   document.getElementById('OptStatus').style.visibility = "visible";
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('MarkUps_Opts').innerHTML=xmlHttp.responseText;
       }
   }
   xmlHttp.open('GET',Url,true);
   xmlHttp.send(null);
}

function updateSOAdd(){
   vAcctID = document.getElementById('AccountID').value;
   var answer = confirm("Fill-in data from Acct#, "+vAcctID+"?");
   if (answer){
      Url = 'so_add_update.php?1='+vAcctID;
      xmlHttp = GetXmlHttpObject();
      if (xmlHttp==null) {
        alert ('Browser does not support HTTP Request');
        return;
      }

      document.getElementById('soAddStatus').style.visibility = "visible";
      xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4) {
            document.getElementById('newSO').innerHTML=xmlHttp.responseText;
          }
      }
      xmlHttp.open('GET',Url,true);
      xmlHttp.send(null);
   }
}


function updateEmployee(fld,id,filtr) {
   var myurl = 'employees_update.php';
   newVal =document.getElementById(fld + '_' + id).value;
   xmlHttp = GetXmlHttpObject();
   if (xmlHttp==null) {
      alert ('Your browser does not support AJAX!');
      return;
   }

   document.getElementById('Status_'+id).style.visibility='visible';
   xmlHttp.onreadystatechange = function() {
       if (xmlHttp.readyState == 4) {
         document.getElementById('Employee_'+id).innerHTML=xmlHttp.responseText;
         //document.getElementById('Status_'+id).style.visibility='hidden';
       }
   }
   xmlHttp.open('GET', myurl + '?1=' + escape(fld) + '&2=' + filtr + '&3=' + escape(newVal), true);
   xmlHttp.send(null);
}
