
var popUpCal = {
    selectedMonth: new Date().getMonth(), // 0-11
    selectedYear: new Date().getFullYear(), // 4-digit year
    selectedDay: new Date().getDate(),
    calendarId: 'calendarDiv',
    inputClass: 'calendarSelectDate',
    
	init: function () {
        var x = getElementsByClass(popUpCal.inputClass, document, 'input');
        var y = document.getElementById(popUpCal.calendarId);
        // set the calendar position based on the input position
        for (var i=0; i<x.length; i++) {
            x[i].onfocus = function () {
				popUpCal.selectedMonth = new Date().getMonth();
                setPos(this, y); // setPos(targetObj,moveObj)
                y.style.display = 'block';
                popUpCal.drawCalendar(this); 
                popUpCal.setupLinks(this);
            }
        }
    },
    
    drawCalendar: function (inputObj) {
		
		var html = '';
		html = '<a id="closeCalender" style="background-color:white;">Затвори</a>';
		html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
    	html += '	<td><a id="prevMonth"><< Назад</a></td>';
		html += '	<td><a id="nextMonth">Напред >></a></td>';
		html += '</tr></table>';
		html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
		html += '<th colspan="7" class="calendarHeader">'+getMonthName(popUpCal.selectedMonth)+' '+popUpCal.selectedYear+'</th>';
		html += '</tr><tr class="weekDaysTitleRow">';
        var weekDays = new Array('Пн','Вт','Ср','Че','Пе','Съ','Не');
        for (var j=0; j<weekDays.length; j++) {
			html += '<td>'+weekDays[j]+'</td>';
        }
		
        var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        var numRows = 0;
        var printDate = 1;
        if (startDay != 7) {
            numRows = Math.ceil(((startDay+1)+(daysInMonth))/7); 
        }
		

        if (startDay != 7) {
// MCVB 
//	var noPrintDays = startDay + 1; 
			var noPrintDays = startDay; 
			
        } else {
            var noPrintDays = 0; 
        }
		var today = new Date().getDate();
		var thisMonth = new Date().getMonth();
		var thisYear = new Date().getFullYear();
        // create calendar rows
        for (var e=0; e<numRows; e++) {
			html += '<tr class="weekDaysRow">';
            // create calendar days
            for (var f=0; f<7; f++) {
				if ( (printDate == today) 
					 && (popUpCal.selectedYear == thisYear) 
					 && (popUpCal.selectedMonth == thisMonth) 
					 && (noPrintDays == 0)) {
					html += '<td id="today" class="weekDaysCell">';
				} else {
                	html += '<td class="weekDaysCell">';
				}
                if (noPrintDays == 0) {
					if (printDate <= daysInMonth) {
						html += '<a>'+printDate+'</a>';
					}
                    printDate++;
                }
                html += '</td>';
                if(noPrintDays > 0) noPrintDays--;
            }
            html += '</tr>';
        }
		html += '</table>';
        
        var calendarDiv = document.getElementById(popUpCal.calendarId);
        calendarDiv.innerHTML = html;
        
        document.getElementById('closeCalender').onclick = function () {
            calendarDiv.style.display = 'none';
        }
        document.getElementById('prevMonth').onclick = function () {
            popUpCal.selectedMonth--;
            if (popUpCal.selectedMonth < 0) {
                popUpCal.selectedMonth = 11;
                popUpCal.selectedYear--;
            }
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
        document.getElementById('nextMonth').onclick = function () {
            popUpCal.selectedMonth++;
            if (popUpCal.selectedMonth > 11) {
                popUpCal.selectedMonth = 0;
                popUpCal.selectedYear++;
            }
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
        
    }, 
    
    setupLinks: function (inputObj) {
        
        var y = document.getElementById('calendar');
        var x = y.getElementsByTagName('a');
        for (var i=0; i<x.length; i++) {
            x[i].onmouseover = function () {
                this.parentNode.className = 'weekDaysCellOver';
            }
            x[i].onmouseout = function () {
                this.parentNode.className = 'weekDaysCell';
            }
            x[i].onclick = function () {
                document.getElementById(popUpCal.calendarId).style.display = 'none';
                popUpCal.selectedDay = this.innerHTML;
                inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);		
            }
        }
    }
    
}

if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", popUpCal.init, false );
else if ( typeof window.attachEvent != "undefined" )
    window.attachEvent( "onload", popUpCal.init );
else {
    if ( window.onload != null ) {
        var oldOnload = window.onload;
        window.onload = function ( e ) {
            oldOnload( e );
            popUpCal.init();
        };
    }
    else
        window.onload = popUpCal.init;
}


function formatDate(Day, Month, Year) {
    Month++; 
    if (Month <10) Month = '0'+Month; 
    if (Day < 10) Day = '0'+Day; 
    var dateString = Day+'/'+Month+'/'+Year;
    return dateString;
}

function getMonthName(month) {
    var monthNames = new Array('Януари','Февруари','Март','Април','Май','Юни','Юли','Август','Септември','Октомври','Ноември','Декември');
    return monthNames[month];
}

function getDayName(day) {
    var dayNames = new Array('Понеделни','Вторник','Сряда','Четвъртък','Петък','Събота','Неделя')
    return dayNames[day];
}

function getDaysInMonth(year, month) {
    return 32 - new Date(year, month, 32).getDate();
}

function getFirstDayofMonth(year, month) {
    var day;
    day = new Date(year, month, 0).getDay();
    return day;
}


function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null ) node = document;
    if ( tag == null ) tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}


function setPos(targetObj,moveObj) {
    var coors = findPos(targetObj);
    moveObj.style.position = 'absolute';
    moveObj.style.top = coors[1]+20 + 'px';
    moveObj.style.left = coors[0] + 'px';
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}






				

				var dtCh= "/";
				var minYear=1980;
				var maxYear=2100;
				
				function isInteger(s){
					var i;
					for (i = 0; i < s.length; i++){   
						var c = s.charAt(i);
						if (((c < "0") || (c > "9"))) return false;
					}

					return true;
				}
				
				function stripCharsInBag(s, bag){
					var i;
					var returnString = "";

					for (i = 0; i < s.length; i++){   
						var c = s.charAt(i);
						if (bag.indexOf(c) == -1) returnString += c;
					}
					return returnString;
				}
				
				function daysInFebruary (year){

					return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
				}
				function DaysArray(n) {
					for (var i = 1; i <= n; i++) {
						this[i] = 31
						if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
						if (i==2) {this[i] = 29}
				   } 
				   return this
				}
				
				function isDate(dtStr){
					var daysInMonth = DaysArray(12)
					var pos1=dtStr.indexOf(dtCh)
					var pos2=dtStr.indexOf(dtCh,pos1+1)
					var strDay=dtStr.substring(0,pos1)
					var strMonth=dtStr.substring(pos1+1,pos2)
					var strYear=dtStr.substring(pos2+1)
					strYr=strYear
					if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
					if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
					for (var i = 1; i <= 3; i++) {
						if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
					}
					month=parseInt(strMonth)
					day=parseInt(strDay)
					year=parseInt(strYr)
					if (pos1==-1 || pos2==-1){
						alert("Датата трябва да е във формат : ден/месец/година")
						return false
					}
					if (strMonth.length<1 || month<1 || month>12){
						alert("Моля, въведете валиден МЕСЕЦ")
						return false
					}
					if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
						alert("Моля, въведете валиден ДЕН")
						return false
					}
					if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
						alert("Моля въведете валидна ГОДИНА между "+minYear+" и "+maxYear)
						return false
					}
					
					if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
//						alert("Моля, въведете валидна ДАТА!")
						return false
					}
				return true
				}
				
				function ValidateForm(){
					var dt=document.archive.search_date
					if (isDate(dt.value)==false){
						dt.focus()
						return false
					}
					return true
				 }
				






