/* PopUp Calendar v2.1 
© PCI, Inc.,2000 • Freeware
webmaster@personal-connections.com
+1 (925) 955 1624
© Codepath Ltd. 2009. Server Date capture, Lead-Time calculations, day pattern exclusions, explicit date inclusions, bug fixes and Actinic Integration.
Permission granted  for unlimited use so far  as the copyright notice above remains intact. */

// v1.4.1  Only inc lead days after the cut time on processing days
// v1.6  dateStr var in Holday fn declared with string seperators to assure string type 2/12/09

var ppcDF = "d/m/Y";
var ppcMN = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
//var ppcWN = new Array("Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday");
var ppcWN = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var ppcER = new Array(5);
ppcER[0] = "Sorry, the required DHTML functions of the delivery date calendar are disabled or not supported by your browser.";
ppcER[1] = "The Delivery Date field on the website is not assigned or not accessible.";
ppcER[2] = "Sorry, the chosen date is not acceptable.  Please refer to our delivery terms and conditions.";
ppcER[3] = "Unknown error occured while displaying the delivery date calendar.";
ppcER[4] = "Valid delivery dates could not be displayed for this item.  Please Contact us.";
var ppcUC = false;
var ppcUX = 4;
var ppcUY = 4;
var holMax = 0;
var forcedMax = 0;
var varcolor = "#cccccc";  // background color for the non-selecteble dates
var varblock = "Y";  //block holidays (in data.js) or not (Y/N)
var varavailable = "Unavailable";
var monthamount = "6";//amount of months in the selector
var groupDefs;

/* Do not edit below this line unless you are sure of what are you doing! */

var ppcIE=true;
var ppcNN=!ppcIE;
//var ppcNN=((navigator.appName == "Netscape")&&(document.layers));

var ppcTT="<table width=\"200\" class=\"test\" cellspacing=\"1\" cellpadding=\"2\" bgcolor=\"#eeeeee\">\n";
var ppcCD=ppcTT;var ppcFT="<font face=\"MS Sans Serif, sans-serif\" size=\"1\" color=\"#666666\">";var ppcFC=true;

var ppcTI=false;var ppcSV=null;var ppcRL=null;var ppcXC=null;var ppcYC=null;
var ppcML=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var ppcNow=new Date();var ppcPtr=new Date();
var ppcWE = ppcWN;
var x; 
var holidayArr  = new Array();
var blockHolidays = true;

if (ppcNN) {
 window.captureEvents(Event.RESIZE);
 window.onresize = restoreLayers;
 document.captureEvents(Event.MOUSEDOWN|Event.MOUSEUP);
 document.onmousedown = recordXY;
 document.onmouseup = confirmXY;}


function restoreLayers(e) {
 if (ppcNN) {
  with (window.document) {
   open("text/html");
   write("<html><head><title>Restoring the layer structure...</title></head>");
   write("<body bgcolor=\"#FFFFFF\" onLoad=\"history.go(-1)\">");
   write("</body></html>");
   close();}}}

function recordXY(e) {
 if (ppcNN) {
  ppcXC = e.x;
  ppcYC = e.y;
  document.routeEvent(e);}}

function confirmXY(e) {
 if (ppcNN) {
  ppcXC = (ppcXC == e.x) ? e.x : null;
  ppcYC = (ppcYC == e.y) ? e.y : null;
  document.routeEvent(e);}}


// Strips the product reference from the name of the ID'd control on the qty on conf page - control name is Q_ followed by prod ref v1.5
//function getRefFromSource(sourceValue){
//  var sourceString = document.getElementById(sourceValue).innerHTML;
//  var nStart = sourceString.indexOf('Q_') + 2;
//  var returnVal = sourceString.substring(nStart);
//  var nEnd = returnVal.indexOf('"');
//  returnVal = returnVal.substring(0,nEnd);
//  return returnVal;
//}

function getCalendarFor(target,group,event,rules,prodRefSource) {
 ppcSV = target;
 ppcRL = rules;
// alert(serverDateRev.getSeconds()); //!!!
 groupDefs = new groupDefsObject(group);
if (groupDefs.leadDays >= 0){
  //  if (ppcFC) {setCalendar();ppcFC = false;}
  setCalendar();
  if ((ppcSV != null)&&(ppcSV)) {
   //target.name = "O_" + getRefFromSource(prodRefSource); //  Qty on separate page only - Have to rename target control with productref to satisfy form validation.  Ref n/a as variable from qty on conf page so have to pass in a padded var and strip it - v1.5
   if (ppcIE) {
    var obj = document.getElementById('PopUpCalendar');
    var scrollX = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
    var scrollY = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    obj.style.left = scrollX+event.clientX + 'px';
    obj.style.top  = scrollY+event.clientY + 'px';
    obj.style.visibility = "visible";}
   else if (ppcNN) {
    var obj = document.layers['PopUpCalendar'];
    obj.left = ppcXC
    obj.top  = ppcYC
    obj.visibility = "show";}
   else {showError(ppcER[0]);}}
  else {showError(ppcER[1]);}}
 else {showError(ppcER[4], 'Unknown Product Group');}}

function switchMonth(param) {
 var tmp = param.split("|");
 setCalendar(tmp[0],tmp[1]);}

function moveMonth(dir) {
 var obj = null;
 var limit = false;
 var tmp,dptrYear,dptrMonth;
 if (ppcIE) {obj = document.ppcMonthList.sItem;}
 else if (ppcNN) {obj = document.layers['PopUpCalendar'].document.layers['monthSelector'].document.ppcMonthList.sItem;}
 else {showError(ppcER[0]);}
 if (obj != null) {
  if ((dir.toLowerCase() == "back")&&(obj.selectedIndex > 0)) {obj.selectedIndex--;}
  else if ((dir.toLowerCase() == "forward")&&(obj.selectedIndex < + monthamount-1)) {obj.selectedIndex++;}
  else {limit = true;}}
 if (!limit) {
  tmp = obj.options[obj.selectedIndex].value.split("|");
  dptrYear  = tmp[0];
  dptrMonth = tmp[1];
  setCalendar(dptrYear,dptrMonth);}
 else {
  if (ppcIE) {
   obj.style.backgroundColor = "#a8efeb";
   window.setTimeout("document.ppcMonthList.sItem.style.backgroundColor = '#FFFFFF'",50);}}}

function getSurchargeComponentIndex(){
  return 1;
}

/*
function selectDate(param) {
 var arr   = param.split("|");
 var year  = arr[0];
 var month = arr[1];
 var date  = arr[2];
 var ptr = parseInt(date);
 var surchargeComponentIndex; // 1 or 2 for first or second hidden delivery surcharge
 var surchargeComponent;      // the actual component

 ppcPtr.setDate(ptr);
 if ((ppcSV != null)&&(ppcSV)) {
  if (validDate(date)){
    ppcSV.value = dateFormat(year,month,date);
    surchargeComponentIndex = getSurchargeComponentIndex();

    if ((year==(serverDateRev.getFullYear()+"")) && // if selected day is today
        (month==(serverDateRev.getMonth()+"")) &&
        (date==(serverDateRev.getDate()+"")))
      surchargeComponentIndex = 2
    else
      surchargeComponentIndex = 1;


    for (var ii=1; ii<=2; ++ii){ // set correct value for first 2 v_prodcode_? components - these are the delivery surcharges
      surchargeComponent = document.getElementsByName('v_' + ppcSV.name.substring(2) + '_' + ii);
      if (surchargeComponent.length == 1){
        surchargeComponent[0].checked = (surchargeComponentIndex==ii);
      }
    }

    hideCalendar();
  }
  else
  {
    showError(ppcER[2]);
	if (ppcTI){
	  clearTimeout(ppcTI);
	  ppcTI = false;
	}
   }
 }
 else 
 {
  showError(ppcER[1]);
  hideCalendar();
 }
}
*/

function selectDate(param) {

//alert(param);
 var arr   = param.split("|");
 var year  = arr[0];
 var month = arr[1];
 var date  = arr[2];
 var ptr = parseInt(date, 10);
 var surchargeComponentIndex; // 1 or 2 for first or second hidden delivery surcharge
 var surchargeComponent;      // the actual component
 var jn_deliveryDay = "nextday";			// delivery day  - sameday or nextday
 var jn_offDay = "sameday"; 

 ppcPtr.setDate(ptr);

 if ((ppcSV != null)&&(ppcSV)) {

  if (validDate(date)){

    ppcSV.value = dateFormat(year,month,date);

    surchargeComponentIndex = getSurchargeComponentIndex();

	var chkyear = serverDateRev.getFullYear()+ "";
	var chkmonth = serverDateRev.getMonth()+"";
	var chkdate = serverDateRev.getDate()+"";
	//alert(chkmonth);

	/*
	if ((year==(serverDateRev.getFullYear()+"")) && // if selected day is today

			(month==(erverDateRev.getMonth())+"") &&

			(date==serverDateRev.getDate())+""))
	*/

	if ((year==chkyear) && (month==chkmonth) && (date==chkdate))
	
	{
		//alert("Same Day Delivery");
		surchargeComponentIndex = 2;

		jn_deliveryDay = "sameday";

		jn_offDay = "nextday";

	} else {

		surchargeComponentIndex = 1;

		jn_deliveryDay = "nextday";

		jn_offDay = "sameday";

	}





    for (var ii=1; ii<=5; ++ii){ // set correct value for first 2 v_prodcode_? components - these are the delivery surcharges

      surchargeComponent = document.getElementsByName('v_' + ppcSV.name.substring(2) + '_' + ii + '_' + jn_deliveryDay);

      if (surchargeComponent.length == 1){ 

        surchargeComponent[0].checked = true; // (surchargeComponentIndex==ii);

      }

    }



	for (var ii=1; ii<=5; ++ii){ 

      surchargeComponent = document.getElementsByName('v_' + ppcSV.name.substring(2) + '_' + ii + '_' + jn_offDay);

      if (surchargeComponent.length == 1){ 

        surchargeComponent[0].checked = false; // (surchargeComponentIndex==ii);

      }

    }



    hideCalendar();

  }

  else

  {

    showError(ppcER[2]);

	if (ppcTI){

	  clearTimeout(ppcTI);

	  ppcTI = false;

	}

   }

 }

 else 

 {

  showError(ppcER[1]);

  hideCalendar();

 }

}

function setCalendar(year,month) {
 if (year  == null) {year = getFullYear(ppcNow);}
 if (month == null) {month = ppcNow.getMonth();setSelectList(year,month);}
 if (month == 1) {ppcML[1]  = (isLeap(year)) ? 29 : 28;}
 ppcPtr.setYear(year);
 ppcPtr.setMonth(month);
 ppcPtr.setDate(1);
 updateContent();}

function updateContent() {
 generateContent();
 if (ppcIE) {document.getElementById('monthDays').innerHTML = ppcCD;}
 else if (ppcNN) {
  with (document.layers['PopUpCalendar'].document.layers['monthDays'].document) {
   open("text/html");
   write("<html>\n<head>\n<title>DynDoc</title>\n</head>\n<body bgcolor=\"#FFFFFF\">\n");
   write(ppcCD);
   write("</body>\n</html>");
   close();}}
 else {showError(ppcER[0]);}
 ppcCD = ppcTT;}

function generateContent() {
 var year  = getFullYear(ppcPtr);
 var month = ppcPtr.getMonth();
 var date  = 1;
 var day   = ppcPtr.getDay();
 
//if (day == 0) {day = 6}  //removed from original.  Was causing a 1 day mismatch but why there in the first place?  Attempt at leap year correction??
//else (day = day-1);
 var len   = ppcML[month];
 var bgr,cnt,tmp = "";
 var j,i = 0;
 for (j = 0; j < 7; ++j) {
  if (date > len) {break;}
  for (i = 0; i < 7; ++i) {
  bgr = (holiday(i, date,month,year)) ? varcolor : "#FFFFFF";
   if (((j == 0)&&(i < day))||(date > len)) {tmp  += makeCell("#FFFFFF",year,month,0);} // Codepath explicit white replaced bgr for null days 
   else {tmp  += makeCell(bgr,year,month,date);++date;}} 
  ppcCD += "<tr align=\"center\">\n" + tmp + "</tr>\n";tmp = "";}
 ppcCD += "</table>\n";
 ppcCD += "<table width=\"100%\" bgcolor=\"#FFFFFF\"><tr><td align=\"left\">Standard Delivery - £5.95</td></tr><tr><td align=\"left\">Same Day Delivery - £7.95</td></tr></table>";
}
function makeCell(bgr,year,month,date) {

 var param = "\'"+year+"|"+month+"|"+date+"\'";
 var td1 = "<td width=\"20\" bgcolor=\""+bgr+"\" ";
 var td2 = (ppcIE) ? "</font></span></td>\n" : "</font></a></td>\n";
 var evt = "onMouseOver=\"this.style.backgroundColor=\'#5F7BE0\'\" onMouseOut=\"this.style.backgroundColor=\'"+bgr+"\'\" onMouseUp=\"selectDate("+param+")\" ";
 var ext = "<span Style=\"cursor: hand\">";
 var lck = "<span Style=\"cursor: default\">";
 var lnk = "<a href=\"javascript:selectDate("+param+")\" onMouseOver=\"window.status=\' \';return true;\">";
 var cellValue = (date != 0) ? date+"" : "";
 //if ((ppcNow.getDate() == date)&&(ppcNow.getMonth() == month)&&(getFullYear(ppcNow) == year)) { // BOLD TODAY
 // cellValue = "<b>"+cellValue+"</b>";}
 var cellCode = "";
 if ((date == 0) || (bgr== varcolor && blockHolidays))
{
  if (ppcIE) {cellCode = td1+"Style=\"cursor: default\" title=Unavailable>"+lck+ppcFT+cellValue+td2;}
  else {cellCode = td1+">"+ppcFT+cellValue+td2;}}
 else {
  if (ppcIE) {cellCode = td1+evt+"Style=\"cursor: hand\">"+ext+ppcFT+cellValue+td2;}
  else {
   if (date < 10) {cellValue = "&nbsp;" + cellValue + "&nbsp;";}
   cellCode = td1+">"+lnk+ppcFT+cellValue+td2;}}
 return cellCode;}

function setSelectList(year,month) {
 var i = 0;
 var obj = null;
 if (ppcIE) {obj = document.ppcMonthList.sItem;}
 else if (ppcNN) {obj = document.layers['PopUpCalendar'].document.layers['monthSelector'].document.ppcMonthList.sItem;}
 else {/* NOP */}
 while (i < + monthamount) {
  obj.options[i].value = year + "|" + month;
  obj.options[i].text  = ppcMN[month] + " - " + year;
  i++;
  month++;
  if (month == 12) {year++;month = 0;}}}

function hideCalendar() {
 if (ppcIE) {document.getElementById('PopUpCalendar').style.visibility = "hidden";}
 else if (ppcNN) {document.layers['PopUpCalendar'].visibility = "hide";window.status = " ";}
 else {/* NOP */}
 ppcTI = false;
 setCalendar();
 ppcSV = null;
 if (ppcIE) {var obj = document.ppcMonthList.sItem;}
 else if (ppcNN) {var obj = document.layers['PopUpCalendar'].document.layers['monthSelector'].document.ppcMonthList.sItem;}
 else {/* NOP */}
 obj.selectedIndex = 0;
}

function showError(message, message2) {
 if (message2 != null)
   message2 = "( Ref: " + message2 + " )";
 window.alert("[ Delivery Date Selection Error ]\n\n" + message + "\n\n" + message2);
}

function isLeap(year) {
 if ((year%400==0)||((year%4==0)&&(year%100!=0))) {return true;}
 else {return false;}}

function getFullYear(obj) {
 //if (ppcNN) {return obj.getYear() + 1900;}
 //else {return obj.getYear();}
 return obj.getFullYear(); // Codepath
}

function validDate(date) {
 var reply = true;
 if (ppcRL == null) {/* NOP */}
 else {
  var arr = ppcRL.split(":");
  var mode = arr[0];
  var arg  = arr[1];
  var key  = arr[2].charAt(0).toLowerCase();
  if (key != "d") {
   var day = ppcPtr.getDay();
   var orn = isEvenOrOdd(date);
   reply = (mode == "[^]") ? !((day == arg)&&((orn == key)||(key == "a"))) : ((day == arg)&&((orn == key)||(key == "a")));}
  else {reply = (mode == "[^]") ? (date != arg) : (date == arg);}}
 return reply;}

function isEvenOrOdd(date) {
 if (date - 21 > 0) {return "e";}
 else if (date - 14 > 0) {return "o";}
 else if (date - 7 > 0) {return "e";}
 else {return "o";}}

function dateFormat(year,month,date) {
 if (ppcDF == null) {ppcDF = "m/d/Y";}
 var day = ppcPtr.getDay();
 var crt = "";
 var str = "";
 var chars = ppcDF.length;
 for (var i = 0; i < chars; ++i) {
  crt = ppcDF.charAt(i);
  switch (crt) {
   case "M": str += ppcMN[month]; break;
   case "m": str += (month<9) ? ("0"+(++month)) : ++month; break;
   case "Y": str += year; break;
   case "y": str += year.substring(2); break;
   case "d": str += ((ppcDF.indexOf("m")!=-1)&&(date<10)) ? ("0"+date) : date; break;
   case "W": str += ppcWN[day]; break;
    default: str += crt;}}
 return unescape(str);}

function setMonths(parm) { 
 ppcMN = parm;
}

function setBlockDays(arr) { 
 holidayArr  = arr.split(",");
 for (holMax = 0; holidayArr[holMax]!=""; ++holMax){}

} 

function setForceDays(arr) { 
 forcedArr  = arr.split(",");
 for (forcedMax = 0; forcedArr[forcedMax]!=""; ++forcedMax){}

} 

function checkDay(testDay, testArray){
 for (var i=0; i < 8 ; ++i){ // always hit undefined if all 7 days pass to return false
//   alert(testDay + ' ' + testArray[i]);
   if (testDay==testArray[i])
     return true
   else	{
     if (testArray[i] == undefined)
	   return false;
   }	   
 }
}

function holiday(dayNumOfWeek,date,month,year){  
 month=month+1; // zero based adjustment

 var dateStr= padZero(date) + '' + padZero(month) + '' + year        // Date for holiday/forced day comparison purposes - ddmmyyyy
 var dateStrRev=  year + '' + padZero(month) + '' + padZero(date);   // Date for sysdate comparison purposes - yyyymmdd
 var holiday=false;
 var forcedDate=false;

 // PHASE 1: Disallow completed days - bail immediately

if (dateStrRev < groupDefs.earliestDeliveryDate){
  return true;
}
 
 // PHASE 2: If the day is specified (in calendar_data.js) as an exceptional holiday or non-processing day then bail immediately.
 for (var i=0; i < holMax ; ++i){ 
   if (dateStr==holidayArr[i])
     return true;
 }

 // PHASE 3: If the day is specified (in calendar_data.js) as an exceptional (forced) processing day then flag as forced.
 for (var i=0; i < forcedMax ; ++i){ 
   if (dateStr==forcedArr[i]){
     forcedDate=true;
	 break;
   }
 }
 // If the days is a forced inclusion, or a generally allowed day of the week then allow, else block.
 if (!forcedDate && checkDay(dayNumOfWeek, groupDefs.noDelDays)){
   holiday=true;
 }
 return holiday;
}

function padZero(nVal){
  if (nVal < 10)
    return "0" + nVal
  else
    return nVal;
}

function groupDefsObject(group){
 var countedDays = 0;
 var countedProcessingDays = 0;
 var forcedDate = false;
 var processingDay = true;      
 var workDate = new Date();
 var dateStr = '';
 var noProDays = [0];           // Array of no processing days
 var cutTime = 0;               // The time at which the current day is no longer a processing/delivery day
 
 this.leadDays = -99;           // the number of lead days required for the group based on the server time and the group rules
 this.earliestDeliveryDate = "";// The first day delivery is permitted based on the server date + the appropriate number of permitted processing
 this.noDelDays = [0];  
 
 with (this) {  
   switch (group){
     case 1: leadDays=0; cutTime=1458; noProDays = [0];   noDelDays = [0];   ; break
     case 2: leadDays=1; cutTime=1458; noProDays = [0];   noDelDays = [0];   ; break
     case 3: leadDays=2; cutTime=1458; noProDays = [0];   noDelDays = [0];   ; break
     case 4: leadDays=1; cutTime=1358; noProDays = [0];   noDelDays = [0];   ; break
     case 5: leadDays=1; cutTime=1158; noProDays = [0,6]; noDelDays = [0,6]; ; break
     case 6: leadDays=1; cutTime=1158; noProDays = [0,6]; noDelDays = [0,1,6]; 
   }
   // add an extra required lead day if after the cut-off for today
   var serverTime = parseInt(serverDateRev.getHours() + "" + padZero(serverDateRev.getMinutes()), 10);
	 
   // starting at the server date, keep stepping forward one day until we have counted off the required amount of processing lead days

   
   workDate.setDate(serverDateRev.getDate());

   if (serverTime > cutTime && !checkDay(workDate.getDay(), noProDays)) // inc lead days if after cut time on a processing day
     leadDays++;

   
   while (countedProcessingDays<leadDays) {
     processingDay = true; // default
     //If the day is specified (in calendar_data.js) as an exceptional holiday or non-processing day then bail immediately.
     dateStr = padZero(workDate.getDate()) + padZero(workDate.getMonth()+1) + workDate.getFullYear();
	 for (var i=0; i < holMax ; ++i){ 
       if (dateStr==holidayArr[i]){
         processingDay = false;
		 break;
	   }
     }

     // If the day is specified (in calendar_data.js) as an exceptional (forced) processing day then flag as forced.
     if (processingDay){
  	   for (var i=0; i < forcedMax ; ++i){ 
         if (dateStr==forcedArr[i]){
           forcedDate=true;
      	   break;
         }
       }
       // If the days is a forced inclusion, or a generally allowed day of the week then allow, else block.
        if (forcedDate || !checkDay(workDate.getDay(), noProDays)) 
     	  countedProcessingDays++;
     }
     workDate.setDate(workDate.getDate()+1); // add a day to the work date
   } // end loop

   //this.endDate.setTime(workDate);
   earliestDeliveryDate = workDate.getFullYear() +''+ padZero(workDate.getMonth()+1) + ''+ padZero(workDate.getDate());
   //alert(earliestDeliveryDate); //!!!
   //alert(workDate.getFullYear());
   //alert(padZero(workDate.getMonth()+1));
   //alert(padZero(workDate.getDate()));
   //alert('combined earliest date: ' + earliestDeliveryDate); //!!!
   //alert(leadDays); //!!!
 } 
}

function setDateCookie(dateArray){
//setCookie('cserverDate0', dArr[0]);

  // write the elements of dateArray to the cookie.
  for (var i=0; i < 6 ; ++i)
    setCookie('cserverDate' + i, dArr[i]);
}

function getDateCookie(){
//dArr[0] = getCookie('cserverDate0');

  // read the elements of the cookie into the dArr var
  for (var i=0; i < 6 ; ++i)
    dArr[i] = getCookie('cserverDate'+i);
}

function readDateLast(){
  getDateCookie();
  serverDateRev = new Date(dArr[0],dArr[1]-1,dArr[2],dArr[3],dArr[4],dArr[5]);
  //alert('constructed: ' + serverDateRev.toString()); //!!!
}


function scriptPage(){
  var sPage = window.location.href;
  var lastDot = sPage.lastIndexOf('.');
  var sExt = sPage.substring(lastDot+1);
  if (sExt.indexOf('pl') == 0) // if page extention starts .pl??? then get last server date from cookie.
    return true
  else
    return false;
}

function setDatesReadOnly(){
  var infoPrompts;
  var lFoundPrompt = true;
  var i = 0;
  while (lFoundPrompt){
    infoPrompts = document.getElementsByName('O_' + i);
    if (infoPrompts.length > 0)
      infoPrompts.item(0).readOnly = true
    else
      lFoundPrompt = false;  
    i++;  
  }    
}








