/**
* Функции для орректировки дат
**/
(function($){

	// Корректировка времени
	$.timeCorrect = function(obj, collback){
		var str = obj.value.replace(/\W/,':');
		var arr = str.split(":");
		var h = parseInt(arr[0], 10) || 0;
		var m = parseInt(arr[1], 10) || 0 ;
		collback = collback || false;		
			
		h = h>=24 ? 23 : h;
		h = h<10 ? "0" + String(h) : String(h);
		m = m>60 ? 59 : m;
		m = m<10 ? "0" + String(m) : String(m);
		
		obj.value = h+":"+m;
		if(collback) collback(obj);
	}
	
	// Корректировка дат
	$.dateCorrect = function(obj, collback){
		var d,m,y;
		var str = $(obj).val();
		var arr = str.match(/(\d+)/g);
		collback = collback || false;
		
		if(! arr )
		{
			$(obj).val("");
			if(collback) collback(obj);
			return;
		}
					
		d =  parseInt(arr[0], 10) || 0 ;
		m =  parseInt(arr[1], 10) || 0 ;
		y =  parseInt(arr[2], 10) || 0 ;		
			
		d = d > 0 ? ( d < 10 ? [0,d].join("") : (d < 31 ? d.toString() : "31" ) ) : "01";
		m = m > 0 ? ( m < 10 ? [0,m].join("") : (m < 12 ? m.toString() : "12" ) ) : "01";
		y = y > 0 ? ( y < 1000 ? (y+2000).toString() :  y.toString() ) : "2009";
		
		$(obj).val([d,m,y].join("."));
		if(collback) collback(obj);
	}
	
	// Устанавливаем настройки по умолчанию для календарика	
	$.fn.disabled = function(){
		if(this.is(':input')){
			this.addClass('disabled').css({opacity: .6}).get(0).disabled = true;
		}else{
			this.addClass('disabled').find(':input').each(function(i){
				$(this).disabled();
			});
		}	
		return this;	
	}
	
	$.fn.enabled = function(){
		if(this.is(':input')){
			this.removeClass('disabled').css({opacity: 1}).get(0).disabled = false;
		}else{
			this.removeClass('disabled').find(':input').each(function(i){
				$(this).enabled();
			});
		}
		return this;		
	}
	
/*	$.fn.shadow = function(){
    	var that = this.parent('.ui-dialog');
		var id = that.attr('aria-labelledby') + "-shadow";
		if( !$("#"+id).length ) 
			$(that).before('<div class="ui-widget-shadow ui-corner-all" id="'+id+'"></div>');
        var shadow = $("#"+id);
			shadow.width( $(that)[0].offsetWidth )
	                  .height( $(that)[0].offsetHeight )
	                   .css({ 
	                      position: 'absolute',
	                      left: $(that)[0].offsetLeft,
	                      top: $(that)[0].offsetTop,
						  zIndex: $(that)[0].zIndex
	                   });	       		         
    	return this;
 	};*/

})(jQuery);





/**
* Функция рисующая интерфейс
**/
(function($){
	$.fn.interface = function(){
		var parentObj = this;
		var finished_class = 'esa-interface-finished';
		
		// Прикрепляем календарь
		parentObj.find('input.date').each(function(i){
			if($(this).is('.'+finished_class)) return;			
			$(this).addClass(finished_class).datepicker({
				dateFormat: 'dd.mm.yy', 
				changeYear: true, 
				changeMonth: true,
				yearRange: '-10:+10',
				showAnim: 'show',
				showOn: 'button',
				constrainInput: false,
				buttonText: '<span class="calendar"></span>',
				dayNames: ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
				dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
				dayNamesShort: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
				firstDay: 1,
				monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
				monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек']
			}).focus(function(){this.select()}).blur(function(){$.dateCorrect(this)});
		});
		
		// Делаем кнопочки
		parentObj.find('button').each(function(i){
			if($(this).is('.'+finished_class)) return;
			var html = '<table cellpadding="0" cellspacing="0"><tbody><tr>';
			var text = $(this).text();
			if( $(this).is('.icon, .ui-datepicker-trigger') ){
				var icon_class = $(this).find('span').get(0).className;				
				$(this).removeClass('icon');				
				html += '<td class="icon"><span class="ui-icon ui-icon-'+icon_class+'"></span></td>';	
			}			
			if( $.trim(text) != '' ) html += '<td class="label">'+text+'</td>';
			html += '</tr></tbody></table>';			
			$(this).html(html);
			
			$(this).addClass(finished_class).addClass('ui-button').addClass('ui-state-default').hover(function(){
				if(! $(this).is('.disabled') ) $(this).addClass('ui-state-hover');
			}, function(){
				if(! $(this).is('.disabled') ) $(this).removeClass('ui-state-hover');
			});
			
			if( $(this).is('.disabled') ){
				$(this).disabled();
			} 
			
		});
		
		
		
	}
})(jQuery);


function goTo(url, protected, mesage){
	protected = protected || false;
	
	if( ! protected ){
		window.location.href = url;
		return;
	}
	
	mesage = mesage || 'Bведите ваш системный пароль:';
	
	// Предотвращаем повторное открытие
	if( $("#confirmActionDialog").length > 0 ) return;
	
	var tmpl = '<div id="confirmActionDialog"><form action="'+ url +'" method="post"><div class="mesage">' + mesage +'</div><div><input type="Password" name="password" /><div></form></div>'	;
	 	$(tmpl).dialog({
				//modal: true, 
				resizable: false, 
				title: "Подтверждение действия",
				dialogClass: 'confirmActionDialog',
				buttons: {
					'Отмена': function(){
							$(this).dialog('close');
						},
					'Подтвердить': function(){
							if( ! $(':password', this).val() ){
								alert('Вы не указали пароль'); return false;
							}
							$('form', this).submit();
						}
				},
				position: ['center', 'center'],
				//open: function(){ $(".ui-widget-overlay").css('zIndex', $(this).parent('.ui-dialog').css('zIndex')-2); },
				close: function(){ $(this).remove(); } // Удаляем при закрытии, чтобы можно было открыть снова
			});
}
