var backgroundObject;
var isLinux = navigator.userAgent.indexOf('Linux');
var ticTac = undefined;

function windowHeight() {
	if (document.innerHeight) h=document.innerHeight;
	else if (document.documentElement.clientHeight)	h=document.documentElement.clientHeight;
	else if (document.body)	h=document.body.clientHeight; 
	return h;
};

function introducFilm(flashSrc) {
	var flashvars = {};
	var params = {wmode: 'transparent',	allowScriptAccess: 'sameDomain'};
	var attributes = {};
	// Linux: RESTECP pentru un flash de tot rahatu' care nu stie transparenta, deci vedem o poza, ca-n 2000
	//if(isLinux == -1) swfobject.embedSWF(flashSrc, "background", "100%", "100%", "9.0.0","expressInstall.swf", flashvars, params, attributes);
	// il pastram pentru cazul in care trebuie sa-l afisam brusc inapoi
	//filmObject = $('#background').get();
};

var frame = {
	setezInaltime : function(){
		if ($('#fereastra').height() > windowHeight()) {
			var frameVerticalHeightNoPadding = $(document).height() - (21+118);
			var frameVerticalHeight = $(document).height();			
		} else {
			var frameVerticalHeightNoPadding = windowHeight() - (21+118);
			var frameVerticalHeight = windowHeight();
		};
		$('#background').css({'height': frameVerticalHeight + 'px'});
		$('#frame #inner-frame .vertical, #frame #inner-frame .vertical .corner').css({'height': frameVerticalHeightNoPadding + 'px'});
		$('#frame, #frame #inner-frame').css({'height': frameVerticalHeight + 'px'});
	}
};

var fereastra = {
	draggableSettings: {containment: 'document'},
	draggable: function(){
		$('.draggable').draggable(this.draggableSettings).css({'cursor': 'move'});
		return this;
	},
	aducInauntru: function(){
		$('.draggable').each(function(){
			// daca iese in dreapta o aduc la loc
			// e bine sa luam in calcul cazul in care ce vrem noi sa pozitionam e pozitionat in alt container, care are deja offset
			if($(this).offset().left + $(this).width() > $(window).width()) $(this).css('left', ($(this).parent().offset().left - $(this).width())+'px');
			// buuuun: daca fereastra iese din ecran in partea de jos o aduc inapoi, dar nu mai sus de marginea de sus a paginii
			if($(this).offset().top + $(this).height() > windowHeight()) $(this).css('top', Math.max(windowHeight()-$(this).height(), 0));
		});
		return this;
	}
};

var videos = {
	bag: function(){
		$.get('../videos/videos.txt', function(data){
			$('#videos ul#video-list').html('');
			if(data.length > 0) {
				var videoData = data.split('\n');
				for(i=0;i<videoData.length;i++) {
					videoData[i] = videoData[i].split('~');
					var titluHTML = '<h4>' + videoData[i][0] + '</h4>';
					var ziuaHTML = '<p>' + videoData[i][1] + '</p>';
					var fotoHTML = '<img src="videos/' + videoData[i][2] + '" alt="' + videoData[i][0] + '" />';
					var video = '<li class="clearfix"><a class="vid_'+videoData[i][4]+'" rel="' + videoData[i][3] + '" href="http://www.youtube.com/watch?v=' + videoData[i][3] + '"' + ' target="_blank"' + '>' + ziuaHTML + fotoHTML + titluHTML + '</a></li>'
					$('#videos ul#video-list').prepend(video);
				};
				$('#videos ul#video-list li:first').attr('class', 'first current clearfix').next().addClass('current').next().addClass('current');
				$('#videos ul#video-list li:last').addClass('last');
//				$('#videos').addClass('pardon');
			}
			else $('#videos').hide();
		});
		$('#videos').hover(
			function(){
				if ( !$('#videos ul#video-list li.first').hasClass('last') ) {
					$(this).addClass('mouseover');
					$('#videos.mouseover').animate({borderWidth: '0'}, 400, function(){
						$('#videos.mouseover').addClass('expanded');
					});
					function scrollHandler (event){
						if ( event.wheelDelta ) delta = event.wheelDelta/120;
						if ( event.detail     ) delta = -event.detail/3;
						if ( $.browser.opera  ) delta = -event.wheelDelta;
						className = delta < 0 ? '.next' : '.prev';
						$('ul#video-search li' + className).trigger('click');
					}
					// sa dam roata
					eventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel';
					if ($.browser.msie && $.browser.version != '7.0') eventName = 'onmousewheel';
					$('#videos').css({'overflow':'auto'}).unbind(eventName).bind(eventName, scrollHandler);
				};
			},
			function(){
				$(this).attr('class', '');
			}
		);
		
		// testez pentru #video/cutare
		if(location.hash){
			try{
				var myHashArray = location.hash.replace('#', '').split('/');
				switch(myHashArray[0]){
					case 'video':
						window.setTimeout("videos.playVideo('" + myHashArray[1] + "')", 4000);
					break;
				}
			}
			catch(err){}
		}
		
		return this;
	},
	playVideo: function(videoClass){
			$('ul#video-list li a.vid_'+videoClass).trigger('click');
	},
	play: function(){
		$('ul#video-list li a').live('click', function(){
			location.hash = '#video/' + $(this).attr('class').replace('vid_', '');
			$('#youtube').html('');
			var movie = $(this).attr('rel');
			$('#youtube').append('<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/' + movie +'&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + movie + '&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>').append('<a href="inchide-ma">Inchide</a>');
			$('body').addClass('movie-time');
			// asta inseamna ca camera dispare
			$('#background').remove();
			// si apare imaginea frumoasa
			$('<div id="background"></div>').appendTo('body');
			flex.resize();
			return false;
		});
		$('#youtube a').live('click', function(){
			$('#youtube').html('');
			$('#background').remove();
			// afisam, brusc, imaginea de la camera
			$('body').removeClass('movie-time').append(filmObject);
			flex.reset();
			location.hash = '#';
			return false;
		});
		return this;
	},
	navighez: function(){
		$('ul#video-search li').click(function(){
			var newElement = $(this).hasClass('next') ? $('ul#video-list li.current:last').next() : $('ul#video-list li.current:first').prev();
			if (newElement.length != 0) {
				var lastElement = $(this).hasClass('next') ? $('ul#video-list li.current:first') : $('ul#video-list li.current:last');
				lastElement.removeClass('current');
				newElement.addClass('current');
			}
		});
		return this;
	}
};

var overlay = {
	scoate: function(){
		var delay = setInterval(function() {
				$('#overlay').slideUp(250).addClass('hidden');
				clearInterval(delay);
		}, 3000);
	},
	pune: function(){
		$('#overlay').removeClass('hidden');
	}
};


var flex = {
	flexImage: new Image,
	defaultRatio: .75,
	load: function(){
		var time = (new Date).getTime(); // incepem testul
		var maxTime = 2000;
		$('<div id="flex"></div>').css({overflow:'hidden',position:'absolute',top:0,left:0,width:'100%',height:'100%',zIndex:-1}).append('<img />').appendTo('body');
		this.flexImage = $('div#flex img').css({width:'100%'});
		$(this.flexImage).bind('load',function(){
			if((new Date).getTime() - time < maxTime) flashSrc = "swf/dodge.swf?stream=high";
			else flashSrc = "swf/dodge.swf?stream=low";
			introducFilm(flashSrc);
		});
		this.flexImage.attr('src', 'img/flex.jpg?' + (new Date).getTime());
		this.resize();
	},
	reset: function() {
		$('#flex').height(0).hide();
	},
	resize: function(){
		if($('div#background').length) {
			$('#flex').show();
			var referenceHeight = $(document).height() > windowHeight() ? $(document).height() : windowHeight();
			$('#flex').css({height: referenceHeight+'px'});
			if(referenceHeight > $(window).width()*this.defaultRatio) this.flexImage.css({width: (referenceHeight / this.defaultRatio)+'px'});
			else $('div#flex img').css({width: '100%'}); // aici a fost referire la this.flexImage: problema IE
		}
		else $('#flex').hide();
	}
};

var counter = {
	init: function(interval, selector){
		var initialInterval = interval;
		var initialDate = new Date();
		var initialSecunde = Math.floor(initialDate.getTime() / 1000);
		var termenLimita = initialSecunde + initialInterval;
		if(ticTac == undefined) ticTac = setInterval(function(){
			var acumDate = new Date();
			var acumSecunde = Math.floor(acumDate.getTime() / 1000);
			var acumInterval = termenLimita - acumSecunde;
			if ( acumInterval<=0 ) {$(selector).html("00:00:00"); counter.stop();}
			acumInterval = Math.abs(acumInterval);
			var totalMinute = Math.floor(acumInterval/60);
			var totalOre = Math.floor(totalMinute/60);
			var totalZile = Math.floor(totalOre/24);
			var secunde = acumInterval%60<10 ? '0' + acumInterval%60 : acumInterval%60;
			var minute = totalMinute%60<10 ? '0' + totalMinute%60 : totalMinute%60;
			var ore = totalOre%24<10 ? '0' + totalOre%24 : totalOre%24;
			var zile = totalZile!=0 ? totalZile<10 ? '0' + totalZile : totalZile : undefined;
			var output = zile!=undefined ? zile + ':' + ore + ':' + minute + ':' + secunde : ore + ':' + minute + ':' + secunde;
			//console.log(acumInterval);
			$(selector).html(output);
		}, 1000);
	},
	stop: function(){
		clearInterval(ticTac);
	}
};

var datePickerSettings = {
	yearRange: '1909:2009',
	dateFormat: 'yy-mm-dd',
	firstDay: 1, // adica luni
	defaultDate: '-18y', // acum 18 ani
	monthNames: ['ianuarie', 'februarie', 'martie', 'aprilie', 'mai', 'iunie', 'iulie', 'august', 'septembrie', 'octombrie', 'noiembrie', 'decembrie'],
	dayNamesMin: ['Du', 'Lu', 'Ma', 'Mi', 'Jo', 'Vi', 'Sa'], clearText: '', closeText: '', prevText: '', nextText: '', currentText: ''
};

$(function(){
	fereastra.draggable();
	videos.bag().navighez();
	frame.setezInaltime();
	$(window).resize(function(){
		//if(console) console.log('resize');
		flex.reset(); // ca sa nu fie luat in calcul cind se pozitioneaza frame
		frame.setezInaltime();
		fereastra.aducInauntru();
		flex.resize();
	});
	flex.load();
	$('input#datanasterii').datepicker(datePickerSettings);
	$('h1 a').attr('target', '_blank');
	$(window).trigger('resize');
});

$(window).load(function(){
	videos.play();
	overlay.scoate();
});
