/**
 * @author mnkosolapov
 */

$(document).ready(function(){
	var ser_time = 0;
	var theDate = 0;
	var arrayMonth = new Array();
	arrayMonth[0] = 'Января';
	arrayMonth[1] = 'Февраля';
	arrayMonth[2] = 'Марта'; 
	arrayMonth[3] = 'Апреля'; 
	arrayMonth[4] = 'Мая'; 
	arrayMonth[5] = 'Июня';
	arrayMonth[6] = 'Июля'; 
	arrayMonth[7] = 'Августа';
	arrayMonth[8] = 'Сентября'; 
	arrayMonth[9] = 'Октября'; 
	arrayMonth[10] = 'Ноября'; 
	arrayMonth[11] = 'Декабря'; 
	$('#date-block_t').everyTime(120000, "soon", function() {
	  	$.ajax({
	     url: "/exact_time.php",
	     beforeSend: function(){
	     },
	     success: function(answ){
	 		ser_time = answ;
	        theDate = new Date(ser_time+1 * 1000);
	        if (cur_time = clock(theDate)){
	          $('#date-block_t').html(clock(theDate));
	        }
	        if (cur_time = todayStr(theDate)){
	         $('#date-block_d').html(todayStr(theDate));
	        }
	     }
	    });
	  });
	$('#date-block_t').everyTime(1000, "soon", function() {
		if(ser_time == 0) {
			$.ajax({
			     url: "/exact_time.php",
			     beforeSend: function(){
			     },
			     success: function(answ){
			 		ser_time = answ;
			        theDate = new Date(ser_time+1 * 1000);
			        $('#date-block_t').html(clock(theDate));
			        $('#date-block_d').html(todayStr(theDate));
			     }
			    });			
		} else { 
	        theDate = new Date(ser_time * 1000);
	        $('#date-block_t').html(clock(theDate));
	        $('#date-block_d').html(todayStr(theDate));
	        ser_time = parseInt(ser_time) + 1;
		}
    });
  function d2(val) {
    if (val < 10) val = "0"+val;
      return val;
  }
  function clock(date) {
    if(typeof date === 'undefined' || date == 'NaN' || date == 'Invalid Date') {
      return ;
    } else {
      return d2(date.getHours()+1)+":"+d2(date.getMinutes());
    }
  }
  function todayStr(date) { 
	  if(typeof date === 'undefined' || date == 'NaN' || date == 'Invalid Date') {
		  return ;
	  } else {
		  return date.getDate()+" "+arrayMonth[date.getMonth()]+" "+(date.getFullYear()) ;
	  }
  }  
});


