//##########################################################
//			SMSClient Javascript Functions
//			==============================

//#########################################################
// Constants
var phoneregex =/^(5\d{4}|\+?\d{9,20}|4004|2842|7227)(\s*,\s*(5\d{4}|\+?\d{9,20}|4004|2842|7227))*$/;

// Trim functions
//   Returns string with whitespace trimmed
//-------------------------------------------------------------------
function LTrim(str) {
	for (var i=0; str.charAt(i)==" "; i++);
	return str.substring(i,str.length);
	}
function RTrim(str) {
	for (var i=str.length-1; str.charAt(i)==" "; i--);
	return str.substring(0,i+1);
	}
function Trim(str) {
	return LTrim(RTrim(str));
	}

// ##############################################################
//			Counts message characters			

function textCounter(field, countfield, maxlimit) {
      if (maxlimit == -1) {
          // if the limit is -1 it counts the caracteres typed.
          countfield.value = field.value.length  + count2Chars(field.value);
       }else{ 
        // There is a limit, counts the carecters left
	if (field.value.length > maxlimit) 		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else // otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length  - count2Chars(field.value);
     }
}

// ##############################################################
//	The chars €[\]^{|}~ need two bytes for be representend in the GSM char set, 
//   see http://www.csoft.co.uk/sms/character_sets/gsm.htm

function count2Chars(text){
  DOUBLE_CHARS = "[\\]^{|}~\u20AC\u00D1\u00F1";
  result = 0;
  i = 0;
        while (i < DOUBLE_CHARS.length){
          pos = -1;
          while ((pos=text.indexOf(DOUBLE_CHARS.charAt(i),pos+1)) != -1){
            result++;
          }
          i++;
        }
        return result;

}

//##########################################################
// 			Count chars on load if text loaded from resend or from outbox
 function countChar() {
 		if(document.sendsms) {
		    document.sendsms.remLen.value = 160 - document.sendsms.msgtext.value.length;			
 		}
 }
// ############################################################
//			Opens sub-window specifically for the address-book selection

function mywindow() {
	newWindow=window.open('mysms?mode=SmsRecipients','contacts','width=400,height=270,screenX=100,screenY=100,left=100,top=100,menubar=no,scrollbars=no,location=no,resizable=no,status=no,titlebar=no,toolbar=no');
	newWindow.focus();
}

//#####################################################################
 function mystatuswindow(msgid) {
   var myurl = "mysms?mode=GetMsgStatus&id="+msgid;
	newWindow=window.open(myurl,'status','width=400,height=300,screenX=100,screenY=100,left=100,top=100,menubar=no,scrollbars=yes,location=no,resizable=no,status=no,titlebar=no,toolbar=no');
	newWindow.focus();
}

// ###################################################################
//		Issue: PAGER-9 added parameter for pagerSMS
	function flashwindow() {
		var myurl = "mysms?mode=GetFlashMsg&pagerSMS="+document.sendsms.pagersms.value;
		newWindow=window.open(myurl,'status','width=400,height=350,screenX=100,screenY=100,left=100,top=100,menubar=no,scrollbars=yes,location=no,resizable=no,status=no,titlebar=no,toolbar=no');
		newWindow.focus();	
	}

// #####################################################################
//			Function transfers values from one selection box to another

function copyToList(from,to)
{
 fromList = eval('document.forms[1].' + from);  
 toList = eval('document.forms[1].' + to);

  if (toList.options.length > 0 && toList.options[0].value == 'temp')
  {
    toList.options.length = 0;
  }
  var sel = false;
  for (i=0;i<fromList.options.length;i++)
  {
    var current = fromList.options[i];
    if (current.selected)
    {
      sel = true;
      if (current.value == 'temp')
      {
        alert ('You cannot move this text!');
        return;
      }
      txt = current.text;
      val = current.value;
      toList.options[toList.length] = new Option(txt,val);
      fromList.options[i] = null;
      i--;
    }
  }
  if (!sel) alert ('You haven\'t selected any options!');
}

//#####################################################################
//                  Transfers selected recipients to main window 

function fillwin() {
    var numbers="";
	List = document.forms[1].chosen;
  	if (List.length && List.options[0].value == 'temp') return;
  	for (i=0;i<List.length;i++)
  	{
		if(i==0)
     		numbers = numbers + List.options[i].value;
		else
			numbers = numbers + ", " + List.options[i].value;
  	}
	var allnumbers = opener.document.sendsms.tofield.value;
	allnumbers = Trim(allnumbers);
	if(allnumbers == "") {
		opener.document.sendsms.tofield.value = opener.document.sendsms.tofield.value + numbers;
	}
	else {
		opener.document.sendsms.tofield.value = opener.document.sendsms.tofield.value + ", " + numbers;
	}
}

//######################################################################
//					Clears the To: Field

function clearfield() {
	document.sendsms.tofield.value="";
}

//#######################################################################
//					Disables date & Time fields for initial open 
function disableTime(){
    if(document.sendsms) {
		document.sendsms.datesend.disabled=true;
		document.sendsms.hour.disabled=true;
		document.sendsms.minutes.disabled=true;		
		document.sendsms.mail.disabled=true;
	}
}
// ############################################################# -->
//					Enable/Disable Time fields
function checkTime(){ 
     if(document.sendsms) {
       if( document.sendsms.sendwhen.checked==true) {   
		document.sendsms.datesend.disabled=false;
		document.sendsms.hour.disabled=false;
		document.sendsms.minutes.disabled=false;		
		document.sendsms.mail.disabled=false;
	   }	
	   if( document.sendsms.sendwhen.checked==false) {   
		document.sendsms.datesend.disabled=true;
		document.sendsms.hour.disabled=true;
		document.sendsms.minutes.disabled=true;		
		document.sendsms.mail.disabled=true;
	   }
	  }	   
}
//################################################################
//						on clicking Date button
	function onTime(){ 
     	if(document.sendsms) {
		    if(document.sendsms.sendwhen.checked==false) {
        		document.sendsms.sendwhen.checked = !document.sendsms.sendwhen.checked;
			}			
			document.sendsms.datesend.disabled=false;
			document.sendsms.hour.disabled=false;
			document.sendsms.minutes.disabled=false;		
			document.sendsms.mail.disabled=false;
	 	}
	}
	
//#################################################################
//                     Check whole sendsms form

function checkWholeForm(theForm) {
    var why = "";
    //BM-46 25-04-2007
    var creditDeducted = creditToDeduct(theForm.msgtext.value.length);
    var totalRecipients = getRecipientCount(theForm.tofield.value);
    creditDeducted = creditDeducted * totalRecipients;
    
    why += checkTo(theForm,theForm.tofield.value, theForm.stripOutDoggyNumbers.value);
    why += checkMsg(theForm.msgtext.value);	       
    why += checkTimeValue(theForm);	   
    if (why != "") {
       alert(why);
       return false;
    }
	else {
		if(confirm(creditDeducted + " Message Credits will be deducted."+ "\n"+ "Ok to send message?")) {
			return true;
		}
		else {					    
			return false;
		}
	}  
}

//#################################################################
//				Issue: BM-46 25-04-2007
//			Calculate the credit to be duducted
function creditToDeduct(msgTextLength){
    var creditDeducted = 1;
    if(msgTextLength > 160 && msgTextLength <= 320){
    	creditDeducted =2;    	
    }else if(msgTextLength > 320 && msgTextLength <= 480){
    	creditDeducted =3;
    }else if(msgTextLength >480){
    	creditDeducted =4;
    }
    return creditDeducted;
}

//#################################################################
//				Issue: BM-46 25-04-2007
//			Get the number of recipients in the toField
function getRecipientCount(val) {
      var index = 0;
      var index2 = 0;
      var total = 0;
      index2 = val.indexOf(",",0);
      if(index2 == -1) {
         total = 1;
       } else {
         total = total + 1;
         index = index2+1;
         index2 = val.indexOf(",",index2+1);
        // go through each number and count
         while(index2 != -1) {
              total = total + 1;
              index = index2+1;
              index2 = val.indexOf(",",index2+1);
         }
         total = total + 1;
      }
      return total;
 }

function checkPushForm(theForm) {
    var why = "";
    why += checkTo(theForm.tofield.value);
    why += checkMsg(theForm.msgtext.value);	
	why += checkURL(theForm.urlfield.value);    	   
    if (why != "") {
       alert(why);
       return false;
    }
	else {
		if(confirm("ok to send message?")) {
			return true;
		}
		else {					    
			return false;
		}
	}  
}



// checks the hour value
function checkHour() {    
	var hrpattern = /^[0-2][0-9]$/;
	if( hrpattern.test(document.sendsms.hour.value) ){
		if(document.sendsms.hour.value < 0 || document.sendsms.hour.value > 23) {
				alert("Please enter hours in 24 hour format: 00-24");
				document.sendsms.hour.value = "00";
		}		
	}
	else {
		alert("Please enter hours in 24 hour format: 00-24");
		document.sendsms.hour.value = "00";
	}
}

// checks the minute value
function checkMinute() {
	var hrpattern = /^[0-5][0-9]$/;
	if( hrpattern.test(document.sendsms.minutes.value) ){
		if(document.sendsms.minutes.value < 0 || document.sendsms.minutes.value > 59) {
				alert("Please enter minutes: 00-59");
				document.sendsms.minutes.value = "01";
		}		
	}
	else {
		alert("Please enter minutes: 00-59");
		document.sendsms.minutes.value = "01";
	}
}


// checks the To field
function checkTo(theForm, val, stripOutDoggyNumbers) {
	var error="";
	if(!(phoneregex.test(val))) {	
		error="Please enter a number in the correct format!\nMultiple numbers should be separated by commas!";
            if ((stripOutDoggyNumbers) && (val!=null) && (val.indexOf(",")!= -1)) {
               var num_array=val.split(",");
               var correctNum=0;
               var cleanedNumbers = "";
               var doggyNum=0;
               var num_index = 0;
               while ((num_index) < num_array.length) {
                 if (phoneregex.test(num_array[num_index])) {
                    correctNum = correctNum+1;
                    if (cleanedNumbers.length >0){
                      cleanedNumbers= cleanedNumbers+",";
                    }
                    cleanedNumbers = cleanedNumbers + num_array[num_index];
                 }else{
                    doggyNum = doggyNum +1;
                 }
                num_index= num_index+1;
               }
               if ((correctNum >0) && (confirm("There are "+ doggyNum + " incorrect numbers.\n"+ "Should those number taken away from the list?"))) {
                  theForm.tofield.value = cleanedNumbers; 
                  error= "ºThe incorrect numbers have been taken away\n Please send the message again.";
	       }else{
                 error=" There are "+ doggyNum + " numbers with an incorrect format.\n Please enter a number in the correct format!\n Multiple numbers should be separated by commas!";
               } 
            }
	}
	return error;
}

// checks the message field
function checkMsg(val) {
	var error="";
	if (val=="") {
		error="Please enter the message text!\n";
	}
	return error;
}

// checks the message field
function checkURL(val) {
	var error="";
	if (val=="") {
		error="Please enter the URL!\n";
	}
	return error;
}

// checks the date and time to send message - format and whether after
// current date
function checkTimeValue(form) {
	var error="";
	var Proceed=0;
	if(form.sendwhen.checked==true) {
		var datestring = /^[0-3][0-9]\/[0-1][0-9]\/[2][0][0-9][0-9]$/;
		hrsend= form.hour.value;			 
		minsend=form.minutes.value;
		if(! datestring.test(form.datesend.value) ){
			error="Please enter a date in the correct format!\n";
		}		
		else {
			today = new Date();
			daysend=form.datesend.value;			
			day=daysend.substr(0,2);
			month=daysend.substr(3,2);
			year=daysend.substr(6,4);
			if(month > 0 && day > 0 && year > 0) {
					var maxDays = 31;
					if (month == 4 || month == 6 || month == 9 || month == 11)
					{
						maxDays = 30;
					}
					if (month == 2)
					{
						if (year % 4 > 0)
							maxDays =28;
						else
							if (year % 100 == 0 && year % 400 > 0)
								maxDays = 28;
							else
								maxDays = 29;
					 }
					 if (day <= maxDays)
					 {
						Proceed = 1;
					 }
			}
			if(Proceed == 0)
				error="A valid date has not been entered!\n";
			else{
				tosend=new Date(year,(month-1),day,hrsend,minsend,0);
				if((tosend.getTime() - today.getTime()) < 0) {
					error="Please enter a date after current date!\n";
				}
				
			}			
		}
	}
	return error;
}

// ###############################################################
//#####################################################################
//                  Gets selected members when saving group 

function getMembers() {
    var numbers="";
	var name = document.savecontact.namefield.value;
	name = Trim(name);
	List = document.forms[1].chosen;
	if(	name == "") {
		alert('Please enter a name for this group!');
		return false;
	}
  	if (List.length  == 0){
		alert('Please choose members for this group!');
		return false;
	} 
	else {
  		for (i=0;i<List.length;i++)
  		{
			if(i==0)			    
     			numbers = numbers + List.options[i].value;
			else
				numbers = numbers + "," + List.options[i].value;
  		}	
		document.savecontact.numberchosen.value = numbers;
		return true;
	}
}

// ###############################################################
//#####################################################################
//     				Checks delete Contact

function deleteconfirm() {
		if(confirm("This contact will be deleted! Are you sure?")) {
				return true;	
		}
		else {
			return false;
		}	
}

// ###############################################################
//						checks if contact has number

	function chkcontact(form) {
	        var address = form.addressfield.value;
			var name = form.namefield.value;				
			address = Trim(address);	
			name = Trim(name);	
			if (address == "" || name == "") {
					alert("Please enter all details for this contact!");
					return false;
			}
			else {
					if(confirm("ok to save contact?")) {
						 return true;
					}
					else {					    
						return false;
					}
			}
	
	}	
// #############################################################
//                New Contact Function
		function chknewcontact(form) {
		    var address = form.addressfield.value;
			var name = form.namefield.value;			
			address = Trim(address);
			name = Trim(name);
			
			if(!(phoneregex.test(address))) {	
				alert("Please enter a number in the correct format!\nMultiple numbers should be separated by commas!");
				return false;
			}
			
			if (name == "") {
					alert("Please enter a name for this contact!");
					return false;
			}
			else {
					if(confirm("ok to create new contact?")) {
						 return true;
					}
					else {					    
						return false;
					}
			}	
		}	

// ############################################################


// ############################################################
//					Request Credit function 
//BM-15 REQUEST CREDIT - included the check isNumeric

function checkCreditRequest(form){
	var credits = form.creditsfield.value;
	if (credits == "") {
		alert("Please enter a credit amount to be requested!");
		return false;
	}
	else if(IsNumeric(credits) == false){
		alert("Non numeric value entered- Please enter a valid number");
		return false;
	}
	else {
			if(confirm("Are you sure you wish to make a credit request?")) {
				 return true;
			}
			else {					    
				return false;
			}
	}	
}

// ############################################################
//				BM-15 REQUEST CREDIT
//			Validate that the value is numeric 
function IsNumeric(sText)

{
   var ValidChars =  "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;   
   }

//##############################################################
//                New Group Function

function newgroup() {
   var numbers="";
	List = document.forms[1].chosen;
	if(document.savecontact.namefield.value == "" || document.savecontact.namefield.value == " ") {
		alert('Please enter a name for this group!');
		return false;	
	}	
  	if (List.length && List.options[0].value == 'temp'){
		alert('Please choose members for this group!');
		return false;
	} 
	else {
  		for (i=0;i<List.length;i++)
  		{
			if(i==0)
     			numbers = numbers + List.options[i].value;
			else
				numbers = numbers + "," + List.options[i].value;
  		}	
		document.savecontact.numberchosen.value = numbers;		
		return true;
	}
	
}
//#############################################################
//                 Check saved template
	function chktemplate(){
	   var tplate = document.savetemplate.msgtext.value;
	   tplate = Trim(tplate);
	   var colonregex = /;+/;
	    if(document.savetemplate.templates.selectedIndex == 0 )
	    {
			alert('Please choose a template to edit!');
			return false;		
		}
		if(tplate == "")
	    {
			alert('Template must have text!');
			return false;		
		}
		if(colonregex.test(tplate)) {
			alert('Please do not use semicolons in the message text!');
			return false;		
		}
			
		else {
			if(confirm("ok to save this template?")) {
				return true;
			}
			else {
				return false;
			}
		}
			
	}
	
// #############################################################
//                Checks deletion of a template

	function chkdeletetemplate() {
		if(document.deletetemplate.deletename.value == "" ) {
				alert('Choose template to delete!');
			    return false;		
		}
					
		if(confirm("This template will be deleted! Are you sure?")) {
				return true;	
		}
		else {
			return false;
		}	
	}

//##############################################################
// #############################################################
//                Checks new template

	function chknewtemplate() {
	    var newname = document.newtemplate.tempname.value;
		var newtplate = document.newtemplate.temptext.value;
		newname = Trim(newname);
		newtplate = Trim(newtplate);
		var nameregex = /^[\w\s]{1,50}$/
		if(!(nameregex.test(newname))) {
			alert('Please use letters, numbers and underscore only for template name!');
			return false;	
		}	
		if(newname == "" || newtplate == "") {
			alert('Please enter template name and text');
			return false;		
		}			
		else {
		    if(confirm("This template will be added to available user templates. Is this ok?")) {
				return true;
			}
			else {
				return false;
			}
		}	
	}

//##############################################################
//				Parses template name and text on selection

	function getnametext() {	    
		var fullvalue=document.savetemplate.templates.options[document.savetemplate.templates.selectedIndex].value;
		index=fullvalue.indexOf(";",0);
		index2=fullvalue.indexOf(";",index+1);
		var id = fullvalue.substring(0,index);
		var name = fullvalue.substring(index+1,index2);
		var text = fullvalue.substring(index2+1);
		
	  	document.savetemplate.id.value=id;
		document.savetemplate.msgtext.value=text;
		document.deletetemplate.deletename.value=name;		  
	 }
	 
// ############################################################  
//                          Confirms delete pending message	
	function delpending() {
		if(confirm("This message will be deleted! Are you sure?")) {
			return true;	
		}
		else {
			return false;
		}		
	}
	
// ##############################################################	
//                             Archive stuff

 function archiveInbox() {
		if(confirm("The entire inbox will be archived. Are you sure?")) {
			return true;	
		}
		else {
			return false;
		}				
 }
 
 function archiveSent() {
		if(confirm("The entire sent messages box will be archived. Are you sure?")) {
			return true;	
		}
		else {
			return false;
		}				
 } 
 
 // ##############################################################
 //      Checks contacts upload
 
 function chkfile(form) {
		var file = form.filename.value;
		file = Trim(file);
		if(file=="") {
			alert("Please select a file first!");
			return false;
		}
		//Oisin
		if((file.indexOf(".csv") == -1 ) && (file.indexOf(".CSV") == -1 ) && (file.indexOf(".xls") == -1 ) && (file.indexOf(".XLS") == -1 )){
			alert("You must select a csv or xls file!");
			return false;
		}
		
		else {
			if(confirm("ok to upload this file?")) {
				return true;
			}
			else {
				return false;
			}		
		}

}
 
// #############  The Date Picker Functions #################### -->

var weekend = [0,6];
var weekendColor = "#e0e0e0";
var fontface = "Arial";
var fontsize = 1;

var gNow = new Date();
var ggWinCal;
isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;

Calendar.Months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];

// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function Calendar(p_item, p_WinCal, p_month, p_year, p_format) {
	if ((p_month == null) && (p_year == null))	return;

	if (p_WinCal == null)
		this.gWinCal = ggWinCal;
	else
		this.gWinCal = p_WinCal;
	
	if (p_month == null) {
		this.gMonthName = null;
		this.gMonth = null;
		this.gYearly = true;
	} else {
		this.gMonthName = Calendar.get_month(p_month);
		this.gMonth = new Number(p_month);
		this.gYearly = false;
	}

	this.gYear = p_year;
	this.gFormat = p_format;
	this.gBGColor = "#e9d8ec";
	this.gFGColor = "#9966CC";
	this.gTextColor = "white";
	this.gHeaderColor = "black";
	this.gReturnItem = p_item;
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;
Calendar.print = Calendar_print;

function Calendar_get_month(monthNo) {
	return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	/* 
	Check for leap year ..
	1.Years evenly divisible by four are normally leap years, except for... 
	2.Years also evenly divisible by 100 are not leap years, except for... 
	3.Years also evenly divisible by 400 are leap years. 
	*/
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return Calendar.DOMonth[monthNo];
	
		return Calendar.lDOMonth[monthNo];
	} else
		return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

function Calendar_print() {
	ggWinCal.print();
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

// This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists.
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
	var vCode = "";
	var vHeader_Code = "";
	var vData_Code = "";
	
	// Begin Table Drawing code here..
	vCode = vCode + "<TABLE BORDER=1 BGCOLOR=\"" + this.gBGColor + "\">";
	
	vHeader_Code = this.cal_header();
	vData_Code = this.cal_data();
	vCode = vCode + vHeader_Code + vData_Code;
	
	vCode = vCode + "</TABLE>";
	
	return vCode;
}

Calendar.prototype.show = function() {
	var vCode = "";
	
	this.gWinCal.document.open();

	// Setup the page...
	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("</head>");

	this.wwrite("<body " + 
		"link=\"" + this.gLinkColor + "\" " + 
		"bgcolor=\"#9966CC\" " +
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
		
	this.wwriteA("<FONT FACE='" + fontface + "' SIZE=2><B>");
	this.wwriteA(this.gMonthName + " " + this.gYear);
	this.wwriteA("</B><BR>");

	// Show navigation buttons
	var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];
	
	this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" +
		");" +
		"\"><<<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\"><<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("&nbsp;&nbsp;&nbsp;&nbsp;</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">><\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" +
		");" +
		"\">>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for the month..
	vCode = this.getMonthlyCalendarCode();
	this.wwrite(vCode);

	this.wwrite("</font></body></html>");
	this.gWinCal.document.close();
}

Calendar.prototype.showY = function() {
	var vCode = "";
	var i;
	var vr, vc, vx, vy;		// Row, Column, X-coord, Y-coord
	var vxf = 285;			// X-Factor
	var vyf = 200;			// Y-Factor
	var vxm = 10;			// X-margin
	var vym;				// Y-margin
	if (isIE)	vym = 75;
	else if (isNav)	vym = 25;
	
	this.gWinCal.document.open();

	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("<style type='text/css'>\n<!--");
	for (i=0; i<12; i++) {
		vc = i % 3;
		if (i>=0 && i<= 2)	vr = 0;
		if (i>=3 && i<= 5)	vr = 1;
		if (i>=6 && i<= 8)	vr = 2;
		if (i>=9 && i<= 11)	vr = 3;
		
		vx = parseInt(vxf * vc) + vxm;
		vy = parseInt(vyf * vr) + vym;

		this.wwrite(".lclass" + i + " {position:absolute;top:" + vy + ";left:" + vx + ";}");
	}
	this.wwrite("-->\n</style>");
	this.wwrite("</head>");

	this.wwrite("<body " + 
		"link=\"" + this.gLinkColor + "\" " + 
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
	this.wwrite("<FONT FACE='" + fontface + "' SIZE=2><B>");
	this.wwrite("Year : " + this.gYear);
	this.wwrite("</B><BR>");

	// Show navigation buttons
	var prevYYYY = parseInt(this.gYear) - 1;
	var nextYYYY = parseInt(this.gYear) + 1;
	
	this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\" alt='Prev Year'><<<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for each month..
	var j;
	for (i=11; i>=0; i--) {
		if (isIE)
			this.wwrite("<DIV ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");
		else if (isNav)
			this.wwrite("<LAYER ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");

		this.gMonth = i;
		this.gMonthName = Calendar.get_month(this.gMonth);
		vCode = this.getMonthlyCalendarCode();
		this.wwrite(this.gMonthName + "/" + this.gYear + "<BR>");
		this.wwrite(vCode);

		if (isIE)
			this.wwrite("</DIV>");
		else if (isNav)
			this.wwrite("</LAYER>");
	}

	this.wwrite("</font><BR></body></html>");
	this.gWinCal.document.close();
}

Calendar.prototype.wwrite = function(wtext) {
	this.gWinCal.document.writeln(wtext);
}

Calendar.prototype.wwriteA = function(wtext) {
	this.gWinCal.document.write(wtext);
}

Calendar.prototype.cal_header = function() {
	var vCode = "";
	
	vCode = vCode + "<TR>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Sun</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Mon</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Tue</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Wed</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Thu</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Fri</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='16%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Sat</B></FONT></TD>";
	vCode = vCode + "</TR>";
	
	return vCode;
}

Calendar.prototype.cal_data = function() {
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay=vDate.getDay();
	var vDay=1;
	var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
	var vOnLastDay=0;
	var vCode = "";

	/*
	Get day for the 1st of the requested month/year..
	Place as many blank cells before the 1st day of the month as necessary. 
	*/

	vCode = vCode + "<TR>";
	for (i=0; i<vFirstDay; i++) {
		vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(i) + "><FONT SIZE='2' FACE='" + fontface + "'> </FONT></TD>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay; j<7; j++) {
		vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
			"<A HREF='#' " + 
				"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
				this.format_data(vDay) + 
				"';window.close();\">" + 
				this.format_day(vDay) + 
			"</A>" + 
			"</FONT></TD>";
		vDay=vDay + 1;
	}
	vCode = vCode + "</TR>";

	// Write the rest of the weeks
	for (k=2; k<7; k++) {
		vCode = vCode + "<TR>";

		for (j=0; j<7; j++) {
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
				"<A HREF='#' " + 
					"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
					this.format_data(vDay) + 
					"';window.close();\">" + 
				this.format_day(vDay) + 
				"</A>" + 
				"</FONT></TD>";
			vDay=vDay + 1;

			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode = vCode + "</TR>";
		if (vOnLastDay == 1)
			break;
	}
	
	// Fill up the rest of last week with proper blanks, so that we get proper square blocks
	for (m=1; m<(7-j); m++) {
		if (this.gYearly)
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'> </FONT></TD>";
		else
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>";
	}
	
	return vCode;
}

Calendar.prototype.format_day = function(vday) {
	var vNowDay = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear = gNow.getFullYear();

	if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
		return ("<FONT COLOR=\"RED\"><B>" + vday + "</B></FONT>");
	else
		return (vday);
}

Calendar.prototype.write_weekend_string = function(vday) {
	var i;

	// Return special formatting for the weekend day.
	for (i=0; i<weekend.length; i++) {
		if (vday == weekend[i])
			return (" BGCOLOR=\"" + weekendColor + "\"");
	}
	
	return "";
}

Calendar.prototype.format_data = function(p_day) {
	var vData;
	var vMonth = 1 + this.gMonth;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
	var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
	var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
	var vY4 = new String(this.gYear);
	var vY2 = new String(this.gYear.substr(2,2));
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;

	switch (this.gFormat) {
		case "MM\/DD\/YYYY" :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
			break;
		case "MM\/DD\/YY" :
			vData = vMonth + "\/" + vDD + "\/" + vY2;
			break;
		case "MM-DD-YYYY" :
			vData = vMonth + "-" + vDD + "-" + vY4;
			break;
		case "MM-DD-YY" :
			vData = vMonth + "-" + vDD + "-" + vY2;
			break;

		case "DD\/MON\/YYYY" :
			vData = vDD + "\/" + vMon + "\/" + vY4;
			break;
		case "DD\/MON\/YY" :
			vData = vDD + "\/" + vMon + "\/" + vY2;
			break;
		case "DD-MON-YYYY" :
			vData = vDD + "-" + vMon + "-" + vY4;
			break;
		case "DD-MON-YY" :
			vData = vDD + "-" + vMon + "-" + vY2;
			break;

		case "DD\/MONTH\/YYYY" :
			vData = vDD + "\/" + vFMon + "\/" + vY4;
			break;
		case "DD\/MONTH\/YY" :
			vData = vDD + "\/" + vFMon + "\/" + vY2;
			break;
		case "DD-MONTH-YYYY" :
			vData = vDD + "-" + vFMon + "-" + vY4;
			break;
		case "DD-MONTH-YY" :
			vData = vDD + "-" + vFMon + "-" + vY2;
			break;

		case "DD\/MM\/YYYY" :
			vData = vDD + "\/" + vMonth + "\/" + vY4;
			break;
		case "DD\/MM\/YY" :
			vData = vDD + "\/" + vMonth + "\/" + vY2;
			break;
		case "DD-MM-YYYY" :
			vData = vDD + "-" + vMonth + "-" + vY4;
			break;
		case "DD-MM-YY" :
			vData = vDD + "-" + vMonth + "-" + vY2;
			break;

		default :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
	}

	return vData;
}

function Build(p_item, p_month, p_year, p_format) {
	var p_WinCal = ggWinCal;
	gCal = new Calendar(p_item, p_WinCal, p_month, p_year, p_format);

	// Customize your Calendar here..
	this.gBGColor = "#e9d8ec";	
	this.gTextColor = "white";
	this.gHeaderColor = "black";	
	gCal.gLinkColor="#6C2D73";
	
	

	// Choose appropriate show function
	if (gCal.gYearly)	gCal.showY();
	else	gCal.show();
}

function show_calendar() {
	/* 
		p_month : 0-11 for Jan-Dec; 12 for All Months.
		p_year	: 4-digit year
		p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
		p_item	: Return Item.
	*/

	p_item = arguments[0];
	if (arguments[1] == null)
		p_month = new String(gNow.getMonth());
	else
		p_month = arguments[1];
	if (arguments[2] == "" || arguments[2] == null)
		p_year = new String(gNow.getFullYear().toString());
	else
		p_year = arguments[2];
	if (arguments[3] == null)
		p_format = "DD/MM/YYYY";
	else
		p_format = arguments[3];

	vWinCal = window.open("", "Calendar", 
		"width=250,height=250,status=no,resizable=no,top=200,left=200");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, p_month, p_year, p_format);
}
/*
Yearly Calendar Code Starts here
*/
function show_yearly_calendar(p_item, p_year, p_format) {
	// Load the defaults..
	if (p_year == null || p_year == "")
		p_year = new String(gNow.getFullYear().toString());
	if (p_format == null || p_format == "")
		p_format = "DD/MM/YYYY";

	var vWinCal = window.open("", "Calendar", "scrollbars=yes");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, null, p_year, p_format);
}

//  ##################  End date Picker Functions  ############# 
//  ############################################################ 
