// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 edited by ROI team (Both date formats)
// Date: dd/mm/yyyy - EU format, mm/dd/yyyy - US format
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar.js(this file) and calendar.html

var NUM_CENTYEAR = 30;// if two digit year input dates after this year considered 20 century.

var calendarObject = new Object();
var RE_NUM = /^\-?\d+$/;

function calendarPath(){ return APP_PATH+"/js/calendar/"; }

function ROICalendar() {

	// assigning methods
	this.gen_date = cal_gen_date;
	this.prs_date = cal_prs_date;
	this.popup = cal_popup;
	this.refresh = cal_refresh;
	
	//set properties
	this.dateformat = 0;//set format to 'european' (0 - EU, 1 - US, 2 - Custom datetimepattern )
	// Pri DateFormat = 2 nuzhno ukazyvat' datetimepattern i DateSeparator yavno pri ob'yavlenii kalendarya na stranitse
	this.datetimepattern = 'dd/MM/yyyy';
	this.dateseparator = '/';
	this.resultSubmit = true;
	this.weekstart = 1;//default monday
	calendarObject = this;
}

function cal_popup(obj_target, left, top) {
	if (!obj_target) return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null) return cal_error("Error calling the calendar: parameter specified is not valid target control");

	this.target = obj_target;
	
	this.dt_current = this.prs_date(this.target.value);
	if (!this.dt_current) return;
	
	this.left = left-50;
	this.top = top-30;
	
	var obj_calwindow = window.open(
		calendarPath() + 'calendar.html?datetime=' + this.dt_current.valueOf()+"&dateformat="+this.dateformat+"&weekstart=" + this.weekstart,
		'Calendar', 'width=300,height=190'+',status=no,resizable=no,top=' + this.top + ',left=' + this.left + ',dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}
function cal_refresh(new_date) {
	this.dt_current = new Date(new_date);
	if (!this.dt_current) return;
	
	var obj_calwindow = window.open(
		calendarPath() + 'calendar.html?datetime=' + this.dt_current.valueOf()+"&dateformat="+this.dateformat + "&weekstart=" + this.weekstart,
		'Calendar', 'width=300,height=190'+',status=no,resizable=no,top=' + this.top + ',left=' + this.left + ',dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}

// date generating function
function cal_gen_date(dt_datetime) {
	var res = "";
	var fullYear = "";
	if (this.dateformat == 0) {
		res = (dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
			+ (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
			+ dt_datetime.getFullYear();
	}
	else if (this.dateformat == 1) {
		res = (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
			+ (dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
			+ dt_datetime.getFullYear();
	} 
	else if (this.dateformat == 2) {
		res = this.datetimepattern;
		res = res.replace("dd",(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate());
		res = res.replace("d", dt_datetime.getDate());
		res = res.replace("MM",(dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1));
		res = res.replace("M", dt_datetime.getMonth() + 1);
		res = res.replace("yyyy", dt_datetime.getFullYear());
		fullYear = dt_datetime.getFullYear();		
		res = res.replace("yy", (fullYear + "").substr(2,2));                  // dt_datetime.getYear() - возвращает 108 (вместо 08) в FF и 2008 в IE7
	}
	return (res);
}

// date parsing function
function cal_prs_date(str_date) {
	if (this.dateformat == 0) {
	    return cal_prs_dateEU(str_date);
	}
	else if (this.dateformat == 1) {
	    return cal_prs_dateUS(str_date);
	}
	else if (this.dateformat == 2) {
	    return cal_prs_dateUni(str_date, this.datetimepattern, this.dateseparator);
	}
}
function cal_prs_dateEU(str_date) {
	if (str_date.length == '')
	{
		return new Date();
	}

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd/mm/yyyy.");
	if (!arr_date[0]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[1]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[1] < 1 || arr_date[1] > 12) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[1]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
	dt_date.setDate(arr_date[0]);
	if (dt_date.getMonth() != (arr_date[1]-1)) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}
function cal_prs_dateUS(str_date) {

	if (str_date.length == '')
	{
		return new Date();
	}
	
	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is mm/dd/yyyy.");
	if (!arr_date[1]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return cal_error ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[0]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return cal_error ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[0] < 1 || arr_date[0] > 12) return cal_error ("Invalid month value: '" + arr_date[0] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[0]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[0], 0);
	dt_date.setDate(arr_date[1]);
	if (dt_date.getMonth() != (arr_date[0]-1)) return cal_error ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}
// 12/11/2007 Artem?
// V svyazi s vnedreniem sistemy internatsionalizatsii dobavlena funktsiya dlya rasparsivaniya daty v ukazannom formate. V kachestve formata
// mozhno ukazat' neobhodimyi DateTimePattern i DateSeparator (peredat' v parametry datetimepattern i dateseparator).
// datetimepattern - stroka, soderzhaschaya format, gde dd-den', MM-mesyats, yy-god, yyyy-god polnost'yu. dd, MM i yyyy dolzhny byt' razdeleny
// znakom, sootvetstvuyuschim dateseparator.
function cal_prs_dateUni(str_date, datetimepattern, dateseparator) {
    
	if (str_date.length == 0)
	{
		return new Date();
	}
	
	var months = -1;
	var days = -1;
	var years = -1;	
	
	// Data i Pattern razbivayutsya s pomosh'yu separatora, poluchivshiesya massivy sravnivayutsya, i esli oni ravny (data sootvetstvuet formatu),
	// s pomosch'yu pattern'a proishodit opredelenie, kakoi pozitsii sootvetstvuet znachenie dnya, mesyatsa i goda.
	var arr_date = str_date.split(dateseparator);
	var arr_pattern = datetimepattern.split(dateseparator);
    if (arr_date.length != arr_pattern.length) return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is "+datetimepattern+'.');

	for(var i=0; i<arr_pattern.length; i++) {
	    if(arr_pattern[i].indexOf('M') > -1) {
	        months = i;
	    } 
	    else if(arr_pattern[i].indexOf('d') > -1) {
	        days = i;
	    } 
	    else if(arr_pattern[i].indexOf('y') > -1) {
	        years = i;
	    }
	}	
	
	// Proveryaetsya, sootvetstvuet li znachenie daty formatu, pravil'no li vvedeno znachenie mesyatsa i dnya, i esli vse pravil'no, formiruetsya i 
	// vozvraschaetsya znachenie daty.
    if(days != -1) {
	    if (!arr_date[days]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	    if (!RE_NUM.exec(arr_date[days])) return cal_error ("Invalid day of month value: '" + arr_date[days] + "'.\nAllowed values are unsigned integers.");
	}
	if (!arr_date[months]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[months])) return cal_error ("Invalid month value: '" + arr_date[months] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[years]) return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[years])) return cal_error ("Invalid year value: '" + arr_date[years] + "'.\nAllowed values are unsigned integers.");	

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[months] < 1 || arr_date[months] > 12) return cal_error ("Invalid month value: '" + arr_date[months] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[months]-1);
	 
	if (arr_date[years] < 100) arr_date[years] = Number(arr_date[years]) + (arr_date[years] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[years]);

    if(days != -1) {
	    var dt_numdays = new Date(arr_date[years], arr_date[months], 0);
	    dt_date.setDate(arr_date[days]);
	    if (dt_date.getMonth() != (arr_date[months]-1)) return cal_error ("Invalid day of month value: '" + arr_date[days] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");
	}

	return (dt_date)
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}
