$(document).ready(function(){
	function initElPopup(){
		var kont = $('.elPopup'),
			timer,
			enterHereYourDate = '27 Feb 2012 12:00:00';

		$('.elPopup_form_close').click(function(){
			clearInterval(timer);
			$('.elPopup').fadeOut(300,function(){
				kont.find('.elPopup_timer div span').text('');
			});
		})

		$('.elPopup').fadeIn(300,function(){
			var today = new Date(),
				eventDate = new Date(enterHereYourDate+' GMT+0300'),
				primitive = eventDate.getTime() - today.getTime();
			if(primitive>0){setTimeout(timeOutF,650)}
			else{
				animTimer(kont.find('.el_secsTop'),'00');
				animTimer(kont.find('.el_minsTop'),0);
				animTimer(kont.find('.el_hoursTop'),0);
				animTimer(kont.find('.el_daysTop'),0);
			}
		});

		function timeOutF(){
			var outDate = getOstDate(enterHereYourDate);
			animTimer(kont.find('.el_secsTop'),outDate[3]);
			animTimer(kont.find('.el_minsTop'),outDate[2]);
			animTimer(kont.find('.el_hoursTop'),outDate[1]);
			animTimer(kont.find('.el_daysTop'),outDate[0]);
			timer = setInterval(timerF,1000)
		}
		function timerF(){
			var outDate = getOstDate(enterHereYourDate);
			animTimer(kont.find('.el_secsTop'),outDate[3]);
			if(outDate[3]==59){animTimer(kont.find('.el_minsTop'),outDate[2])}
			if(outDate[3]==59&&outDate[2]==59){animTimer(kont.find('.el_hoursTop'),outDate[1])}
			if(outDate[3]==59&&outDate[2]==59&&outDate[1]==23){animTimer(kont.find('.el_daysTop'),outDate[0])}
		}
		function animTimer(kontSelector,val){
			var jKont = $(kontSelector),
				jKontNext = jKont.next();
			jKont.find('.el_hid span').text(val);
			jKontNext.find('.el_hid span').text(val);
				
			jKont.children('.el_hid').animate({height:'100%'},300,function(){
				jKont.children('.el_vis').css({height:0});
				jKont.children('div').toggleClass('el_vis').toggleClass('el_hid');
				
				jKontNext.children('.el_hid').animate({height:'100%'},300,function(){
					jKontNext.children('.el_vis').css({height:0});
					jKontNext.children('div').toggleClass('el_vis').toggleClass('el_hid');
				})
			})
		}
		
	}
	function getOstDate(eDate){
			var today = new Date(),
				eventDate = new Date(eDate+' GMT+0300'),
				primitive = eventDate.getTime() - today.getTime(),
				days,
				hours,
				mins,
				secs;
			days = parseInt(primitive / (1000*60*60*24));
			ost = primitive - (days*1000*60*60*24);
			hours = parseInt(ost / (1000*3600));
			ost -= hours*1000*3600;
			mins = parseInt(ost / (1000*60));
			ost -= mins*1000*60;
			secs = parseInt(ost / 1000);
			return([days,hours,mins,secs]);
		}
	
	initElPopup();
})
