﻿// ********************
// Begin Popup Calendar
// Customized for ASP.Net Applications
// Farzad Khandan
// fkhandan@simiagaran.net
// www.simiagaran.net
// ********************
var popCalDstFld;
var temp;
var popCalWin;
var popCalDstFmt;
var popCalMonths;
var	popCalDays;
var	popCalToday;
var	popCalClose;
var	popCalTitle;

// ******************************
// Expected params:
// [0] Window Name
// [1] Destination Field
// ******************************
function popupCal()
{
	//debugger;			//remove slashes to activate debugging in Visual Studio
	var tmpDate         = new Date(); 
	var tmpString       = "";
	var tmpNum          = 0;
	var popCalDateVal;
	var dstWindowName   = "";

	//Initialize the window to an empty object.
	popCalWin = new Object();
	
	//Check for the right number of arguments
	if (arguments.length < 2)
	{
		alert("popupCal(): Wrong number of arguments.");
		return void(0);
	}
	//Get the command line arguments -- Localization is optional
	dstWindowName = popupCal.arguments[0];
	popCalDstFld = popupCal.arguments[1];
	temp = popupCal.arguments[1];
	popCalFirstDayWeek = 0;  //Saturday, First Day of Week
	
	//check destination field name
	if (popCalDstFld != "")
	  popCalDstFld = document.getElementById(popCalDstFld);

	//default localized short date format if not provided
    popCalDstFmt = "yyyy/dd/mm";

	//default localized months string if not provided
    popCalMonths = "فروردین,اردیبهشت,خرداد,تیر,مرداد,شهریور,مهر,آبان,آذر,دی,بهمن,اسفند";
 
	//default localized months string if not provided
	//if (popCalDays == "")
	popCalDays = "ش,ی ش,د ش,س ش,چ ش,پ ش,ج";
	
	//default localized today string if not provided
	popCalToday = "امروز";

	//default localized close string if not provided
	popCalClose = "خروج";

	//default window title if not provided
	popCalTitle = "تاریخ";
 
	tmpString = new String(popCalDstFld.value);  
	//If tmpString is empty (meaning that the field is empty) 
	//use todays date as the starting point
	if(tmpString == "")
		popCalDateVal = ShamsiToday(); 
	else
	{
		//Make sure the century is included, if it isn't, add this 
		//century to the value that was in the field
		if (tmpString.substr(0, 2) != "13")
		{
			popCalDateVal = "13" + tmpString;
		}
		else
		{
			popCalDateVal = ShamsiToday();
		}
	}
	
	//Make sure the date is a valid date.  Set it to today if it is invalid
	//"NaN" is the return value for an invalid date
	if(!IsValidShamsi(popCalDateVal))
	{
		popCalDateVal = ShamsiToday();
		popCalDstFld.value = "";
	}
			
	//Set the base date to midnight of the first day of the specified month, 
	//this makes things easier?
 	var dateString = FormatShamsiDate(GetShYear(popCalDateVal), GetShMonth(popCalDateVal), 1);

	//Call the routine to draw the initial calendar
	reloadCalPopup(dateString, dstWindowName);
	
	return void(0);
}
 
function closeCalPopup()
{
	//Can't tell the child window to close itself, the parent window has to 
	//tell it to close.
	popCalWin.close();
	return void(0);
}
 
function reloadCalPopup() //[0]dateString, [1]dstWindowName
{
	//Set the window's features here

	var windowFeatures = "toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no, height=270, width=270, top=" + ((screen.height - 270)/2).toString()+",left="+((screen.width - 270)/2).toString();
	var tmpDate = reloadCalPopup.arguments[0];
	
	if (!IsValidShamsi(tmpDate))
	    tmpDate = ShamsiToday();
	
	tmpDate = FormatShamsiDate(GetShYear(tmpDate), GetShMonth(tmpDate), 1);
	
	//Get the calendar data
	var popCalData = calPopupSetData(tmpDate,reloadCalPopup.arguments[1]);
 
	//Check to see if the window has been initialized, create it if it hasn't been
	if( popCalWin.toString() == "[object Object]" )
	{
		popCalWin = window.open("",reloadCalPopup.arguments[1],windowFeatures);
		popCalWin.opener = self;
		// Window im Vordergrund
		popCalWin.focus();
	}
	else 
	{
    popCalWin.document.close();
		popCalWin.document.clear();
  }
	
	//this is the line with the big problem
  popCalWin.document.write(popCalData);
	return void(1);
}
 
function calPopupSetData(firstDay,dstWindowName)
{
	var popCalData = "";
    var lastDate = 0;
	var fnt = new Array( "<FONT SIZE=\"1\">", "<B><FONT SIZE=\"2\">", "<FONT SIZE=\"2\" COLOR=\"#EF741D\"><B>");
	var dtToday = ShamsiToday();
	var thisMonth = GetShMonth(firstDay);
	var thisYear = GetShYear(firstDay);
	var nPrevMonth = (thisMonth == 1 ) ? 12 : (thisMonth - 1);
	var nNextMonth = (thisMonth == 12 ) ? 1 : (thisMonth + 1);
	var nPrevMonthYear = (nPrevMonth == 12) ? (thisYear - 1): thisYear;
	var nNextMonthYear = (nNextMonth == 1) ? (thisYear + 1): thisYear;
	var sToday = dtToday;
	var sPrevMonth = FormatShamsiDate(nPrevMonthYear, nPrevMonth, 1);
	var sNextMonth = FormatShamsiDate(nNextMonthYear, nNextMonth, 1);
	var sPrevYear1 = FormatShamsiDate(thisYear-1, thisMonth, 1);
	var sNextYear1 = FormatShamsiDate(thisYear+1, thisMonth, 1);
 	var tmpDate = sNextMonth;
	
	lastDate = GetDayOfMonth(firstDay);

	if (this.popCalMonths.split) // javascript 1.1 defensive code
	{
		var monthNames = this.popCalMonths.split(",");
		var dayNames = this.popCalDays.split(",");
	}
	else  // Need to build a js 1.0 split algorithm, default English for now
	{
		var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		var dayNames = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
	}

 	var styles = "<style><!-- body{font-family:Arial,Helvetica,sans-serif;font-size:9pt}; td {  font-family: Arial, Helvetica, sans-serif; font-size: 9pt; color: #666666}; A { text-decoration: none; };TD.day { border-bottom: solid black; border-width: 0px; }--></style>"
	var cellAttribs = "align=\"center\" class=\"day\" BGCOLOR=\"#F1F1F1\"onMouseOver=\"temp=this.style.backgroundColor;this.style.backgroundColor='#CCCCCC';\" onMouseOut=\"this.style.backgroundColor=temp;\""
	var cellAttribs2 = "align=\"center\" BGCOLOR=\"#F1F1F1\" onMouseOver=\"temp=this.style.backgroundColor;this.style.backgroundColor='#CCCCCC';\" onMouseOut=\"this.style.backgroundColor=temp;\""
	var htmlHead = "<HTML><HEAD><TITLE>"+popCalTitle+"</TITLE>" + styles + "</HEAD><BODY dir=rtl BGCOLOR=\"#F1F1F1\" TEXT=\"#000000\" LINK=\"#364180\" ALINK=\"#FF8100\" VLINK=\"#424282\">";
	var htmlTail = "</BODY></HTML>";
	var closeAnchor = "<CENTER><input type=button value=\""+popCalClose+"\" onClick=\"javascript:window.opener.closeCalPopup()\"></CENTER>";            
	var todayAnchor = "<A HREF=\"javascript:window.opener.reloadCalPopup('"+sToday+"','"+dstWindowName+"');\">"+popCalToday+"</A>";
	var prevMonthAnchor = "<A HREF=\"javascript:window.opener.reloadCalPopup('"+sPrevMonth+"','"+dstWindowName+"');\">" + monthNames[nPrevMonth-1] + "</A>";
	var nextMonthAnchor = "<A HREF=\"javascript:window.opener.reloadCalPopup('"+sNextMonth+"','"+dstWindowName+"');\">" + monthNames[nNextMonth-1] + "</A>";
	var prevYear1Anchor = "<A HREF=\"javascript:window.opener.reloadCalPopup('"+sPrevYear1+"','"+dstWindowName+"');\">"+(thisYear-1)+"</A>";
	var nextYear1Anchor = "<A HREF=\"javascript:window.opener.reloadCalPopup('"+sNextYear1+"','"+dstWindowName+"');\">"+(thisYear+1)+"</A>";
		
	popCalData += (htmlHead + fnt[1]);
	popCalData += ("<DIV align=\"center\">");
	popCalData += ("<TABLE BORDER=\"0\" cellspacing=\"0\" callpadding=\"0\" width=\"250\"><TR><TD width=\"45\">&nbsp</TD>");
	popCalData += ("<TD width=\"45\" align=\"center\" " + cellAttribs2);
	popCalData += (" >");
	popCalData += (fnt[0]+prevYear1Anchor+"</FONT></TD>");
	popCalData += ("<TD width=\"70\" align=\"center\" "+cellAttribs2);
	popCalData += (" >");
	popCalData += (fnt[0]+todayAnchor+"</FONT></TD>");
	popCalData += ("<TD width=\"45\" align=\"center\" "+cellAttribs2);
	popCalData += (" >");
	popCalData += (fnt[0]+nextYear1Anchor+"</FONT></TD><TD width=\"45\">&nbsp</TD>");
	popCalData += ("</TR></TABLE>");
	popCalData += ("<TABLE BORDER=\"0\" cellspacing=\"0\" callpadding=\"0\" width=\"250\">");          
	popCalData += ("<TR><TD width=\"55\" align=\"center\" "+cellAttribs2);
	popCalData += (" >");
	popCalData += (fnt[0] + prevMonthAnchor + "</FONT></TD>");
	popCalData += ("<TD width=\"140\" align=\"center\">");
	popCalData += ("&nbsp;&nbsp;"+fnt[1]+"<FONT COLOR=\"#000000\">" + monthNames[thisMonth-1] + ", " + thisYear + "&nbsp;&nbsp;</FONT></TD>");
	popCalData += ("<TD width=\"55\" align=\"center\" "+cellAttribs2);
	popCalData += (" >");
	popCalData += (fnt[0]+nextMonthAnchor+"</FONT></TD></TR></TABLE><BR>");       
	popCalData += ("<TABLE BORDER=\"0\" cellspacing=\"2\" cellpadding=\"1\"  width=\"245\">" );
	popCalData += ("");
	popCalData += ("<TR>");
	
	/*
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[0]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[1]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[2]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[3]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[4]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[5]+"</FONT></TD>");
	popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[6]+"</FONT></TD>");
	*/
	var xday = 0;
	for (xday = 0; xday < 7; xday++)
	{
		popCalData += ("<TD width=\"35\" align=\"center\">"+fnt[1]+"<FONT COLOR=\"#000000\">"+dayNames[xday]+"</FONT></TD>");
	};
	popCalData += ("</TR>");
	
	var calDay = 0;
	var monthDate = 1;
	var weekDay = hshDayOfWeek(GetShYear(firstDay), GetShMonth(firstDay), GetShDay(firstDay));
	do
	{
		popCalData += ("<TR>");
		for (calDay = 0; calDay < 7; calDay++ )
		{
			if(((weekDay+7-popCalFirstDayWeek)%7 != calDay) || (monthDate > lastDate))
			{
				popCalData += ("<TD width=\"35\">"+fnt[1]+"&nbsp;</FONT></TD>");
				continue;
			}
			else
			{
				anchorVal = "<A HREF=\"javascript:window.opener.calPopupSetDate(window.opener.popCalDstFld,'" + FormatShamsiDate(thisYear, thisMonth, monthDate) + "');window.opener.closeCalPopup()\">";
				jsVal = "javascript:window.opener.calPopupSetDate(window.opener.popCalDstFld,'" + FormatShamsiDate(thisYear, thisMonth, monthDate) + "');window.opener.closeCalPopup()";

				popCalData += ("<TD width=\"35\" "+cellAttribs+" onClick=\""+jsVal+"\">");
				
				if ((GetShMonth(firstDay) == GetShMonth(dtToday)) && (monthDate == GetShDay(dtToday)) && (thisYear == GetShYear(dtToday)) )
					popCalData += (anchorVal+fnt[2]+monthDate+"</A></FONT></TD>");
				else
					popCalData += (anchorVal+fnt[1]+monthDate+"</A></FONT></TD>");
				
				weekDay++;
				monthDate++;
			}
		}
		weekDay = popCalFirstDayWeek;
		popCalData += ("</TR>");
	} while( monthDate <= lastDate );
	
	popCalData += ("</TABLE></DIV><BR>");
 
	popCalData += (closeAnchor+"</FONT>"+htmlTail);
	return( popCalData );
}
 
function calPopupSetDate()
{
	calPopupSetDate.arguments[0].value = calPopupSetDate.arguments[1];
}

// utility function
function padZero(num)
{
  return ((num <= 9) ? ("0" + num) : num);
}

// Format short date
function constructDate(d,m,y)
{
  var fmtDate = this.popCalDstFmt
  fmtDate = fmtDate.replace ('dd', padZero(d))
  fmtDate = fmtDate.replace ('d', d)
  fmtDate = fmtDate.replace ('MM', padZero(m))
  fmtDate = fmtDate.replace ('M', m)
  fmtDate = fmtDate.replace ('yyyy', y)
  fmtDate = fmtDate.replace ('yy', padZero(y%100))
  return fmtDate;
}

// ******************
// End Popup Calendar
// ******************

// SHAMSI ROUTINES
var grgSumOfDays=Array(Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365),Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366));
var hshSumOfDays=Array(Array(0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 365), Array(0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366));

function ShamsiToday()
{
	var t = new Date()
	return ToShamsi(t.getYear(), t.getMonth()+1, t.getDate(), "");
}

function ToShamsi(grgYear,grgMonth,grgDay,Format)
{
	/* FireFox correction: */
	if (grgYear < 1000)
	{
		if (grgYear > 100) grgYear -= 100;
		grgYear += 2000;
	}
	/* End FireFox Correction */
	var hshYear = grgYear-621; 
	var hshMonth,hshDay;
	
	var grgLeap=grgIsLeap (grgYear);
	var hshLeap=hshIsLeap (hshYear-1);
	
	var hshElapsed;
	var grgElapsed = grgSumOfDays[(grgLeap ? 1:0)][grgMonth-1]+grgDay;

	var XmasToNorooz = (hshLeap && grgLeap) ? 80 : 79;

	if (grgElapsed <= XmasToNorooz)
	{
		hshElapsed = grgElapsed+286;
		hshYear--;
		if (hshLeap && !grgLeap)
			hshElapsed++;
	}
	else
	{
		hshElapsed = grgElapsed - XmasToNorooz;
		hshLeap = hshIsLeap (hshYear);
	}

	for (var i=1; i <= 12 ; i++)
	{
		if (hshSumOfDays [(hshLeap ? 1:0)][i] >= hshElapsed)
		{
			hshMonth = i;
			hshDay = hshElapsed - hshSumOfDays [(hshLeap ? 1:0)][i-1];
			break;
		}
	}

//	hshMonth = hshMonth + 1;
//	if (hshMonth > 12) hshMonth = 1; 

	var yy, mm, dd;
	yy = (hshYear < 100) ? hshYear + 1300 : hshYear;
	mm = (hshMonth < 10) ? "0" + hshMonth : hshMonth;
	dd = (hshDay < 10) ? "0" + hshDay : hshDay;
	
	if (Format=="Long")
		return hshDayName(hshDayOfWeek(hshYear,hshMonth,hshDay)) + "  " + hshDay + " " + calNames("hf", hshMonth-1) + " " + hshYear;
	else
		return yy + "/" + mm + "/" + dd;
}

function ToGregorian (hshYear,hshMonth,hshDay)
{
	var grgYear = hshYear+621;
	var grgMonth,grgDay;

	var hshLeap=hshIsLeap (hshYear);
	var grgLeap=grgIsLeap (grgYear);

	var hshElapsed=hshSumOfDays [hshLeap ? 1:0][hshMonth-1]+hshDay;
	var grgElapsed;

	if (hshMonth > 10 || (hshMonth == 10 && hshElapsed > 286+(grgLeap ? 1:0)))
	{
		grgElapsed = hshElapsed - (286 + (grgLeap ? 1:0));
		grgLeap = grgIsLeap (++grgYear);
	}
	else
	{
		hshLeap = hshIsLeap (hshYear-1);
		grgElapsed = hshElapsed + 79 + (hshLeap ? 1:0) - (grgIsLeap(grgYear-1) ? 1:0);
	}

	for (var i=1; i <= 12; i++)
	{
		if (grgSumOfDays [grgLeap ? 1:0][i] >= grgElapsed)
		{
			grgMonth = i;
			grgDay = grgElapsed - grgSumOfDays [grgLeap ? 1:0][i-1];
			break;
		}
	}

	return grgYear+"/"+grgMonth+"/"+grgDay;
}

function grgIsLeap (Year)
{
	return ((Year%4) == 0 && ((Year%100) != 0 || (Year%400) == 0));
}

function hshIsLeap (Year)
{
	Year = (Year - 474) % 128;
	Year = ((Year >= 30) ? 0 : 29) + Year;
	Year = Year - Math.floor(Year/33) - 1;
	return ((Year % 4) == 0);
}


function hshDayOfWeek(hshYear, hshMonth, hshDay)
{
	var value;
	value = hshYear - 1376 + hshSumOfDays[0][hshMonth-1] + hshDay - 1;

	for (var i=1380; i<hshYear; i++)
		if (hshIsLeap(i)) value++;
	for (var i=hshYear; i<1380; i++)
		if (hshIsLeap(i)) value--;

	value=value%7;
	if (value<0) value=value+7;

	return (value);
}

function hshDayName(DayOfWeek)
{
	return calNames("df", DayOfWeek%7);
}

 function calNames(calendarName, monthNo)
 {
  switch (calendarName)
 {
   case "hf": return Array("فروردين", "ارديبهشت", "خرداد", "تير", "مرداد", "شهريور", "مهر", "آبان", "آذر", "دي", "بهمن", "اسفند")[monthNo];
   case "ge": return Array(" January ", " February ", " March ", " April ", " May ", " June ", " July ", " August ", " September ", " October ", " November ", " December ")[monthNo];
   case "gf": return Array("ژانويه", "فوريه", "مارس", "آوريل", "مه", "ژوئن", "ژولاي", "آگوست", "سپتامبر", "اکتبر", "نوامبر", "دسامبر")[monthNo];
   case "df": return Array("شنبه", "يکشنبه", "دوشنبه", "سه شنبه", "چهارشنبه", "پنجشنبه", "جمعه")[monthNo];
   case "de": return Array("Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")[monthNo];
   }
  }

function formatTime()
{
	var t = new Date();
	var h = t.getHours();
	var m = t.getMinutes();
	return ((h < 10) ? "0" + h : h) + ":" + ((m < 10) ? "0" + m : m);
}

var shDaysInMonth = Array(31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29);
var shLeapDaysInMonth = Array(31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30);
function IsValidShamsi(str)
{
	if (str == null || str.length != 10) return false;
	var y = parseInt(str.substr(0, 4), 10);
	var m = parseInt(str.substr(5, 2), 10);
	var d = parseInt(str.substr(8, 2), 10);
	
	if (y < 1300 || y > 2000 || m < 1 || m > 12 || d < 1 || d > 31) return false;
	if (hshIsLeap(y)) return (d <= shLeapDaysInMonth[m-1]);
	else return (d <= shDaysInMonth[m-1]);
}

function GetDayOfMonth(sh)
{
	if (sh == null) return 0;
	var y = parseInt(sh.substr(0, 4), 10);
	var m = parseInt(sh.substr(5, 2), 10);
	return (hshIsLeap(y) ? shLeapDaysInMonth[m-1] : shDaysInMonth[m-1]);
}

function GetShDay(sh)
{
	return (sh == null ? 0 : parseInt(sh.substr(8, 2), 10));
}

function GetShMonth(sh)
{
	return (sh == null ? 0 : parseInt(sh.substr(5, 2), 10));
}

function GetShYear(sh)
{
	return (sh == null ? 0 : parseInt(sh.substr(0, 4), 10));
}

function FormatShamsiDate(shy, shm, shd)
{
	var yy, mm, dd;
	yy = (shy < 100) ? shy + 1300 : shy;
	mm = (shm < 10) ? "0" + shm : shm;
	dd = (shd < 10) ? "0" + shd : shd;
	return (yy + "/" + mm + "/" + dd);
}
