var pu = 'services/AjaxPlaylist.html'; // playlist service url
var vu = 'services/AjaxVote.html'; // vote service url

var preCookie = 'dev_';


var msgAjaxError = 'Vzdialená strana neodpovedá. Skúste znova.';
var msgUploadError = 'Video sa nepodarilo odoslať. Skúste znova.';
var msgAnalError = 'Chýbaju dáta!';
var msgCommentError = 'Musíte vyplniť text komentára!';
var msgLoginError = 'Musíte byť prihlásený!';
var msgConfirmDelete = 'Naozaj chcete zmazať video?';

var dbgFlag = true; // magic debugging

document.observe('dom:loaded', function(){ // one and only domload observer, order is important!
	FormStyle.work('.j-formstyle');																								// styled selects
	limeMain('.j-lime input, input.j-lime, .j-lime textarea, textarea.j-lime');		// input limiter
	savoMain('.j-savo input, input.j-savo, .j-savo textarea, textarea.j-savo');		// input cleaner
	$$('.j-expander').each(function(el){ autoExpandContract(el); })								// textarea expander
	
	loginInit(); 											// login vs search switch
	scrollInit(); 										// featured custom scrollers start
	analyticsInit(); 									// observing ajax links and events
	selectorInit(); 									// selects embed & url in video detail
	playlistHover('#main-more .j-playlist .i');	// events for hovering in user videos list
	playlistInit(); 									// observing add to playlist links
	displaySwitch(); 									// switching of category display
	featureInit();										// animations and events on homepage featured box
	profileSwitch(); 									// profile edit switching
	tabInit(); 												// all tabs start here
	playlistRefresh(true);						// ajax refresh of playlist
	playlistManage();									// disabling links of videos
	playlistAuto();										// auto advance
	similarInit();										// animations for similair videos
	voteInit(); 											// comment voting
	submitInit(); 										// events for submit link buttons
	deleteInit(); 										// delete confirmation observer
	calendarInit();										// calendar row resizing
	centerInit();											// centering items
	elipsisInit();										// adds elipsis
	birdInit();										// slavik
});

function dbg(output) {
	if (getCookie('debug') == '1') console.log(output);
}


function commentAjaxRefresh() {
	limeMain('.b-comment-list .j-lime input, .b-comment-list input.j-lime, .b-comment-list .j-lime textarea, .b-comment-list textarea.j-lime');		// input limiter
	savoMain('.b-comment-list .j-savo input, .b-comment-list input.j-savo, .b-comment-list .j-savo textarea, .b-comment-list textarea.j-savo');		// input cleaner
	$$('.b-comment-list .j-expander').each(function(el){ autoExpandContract(el); })								// textarea expander
	voteInit(); 											// comment voting
	submitInit(); 										// events for submit link buttons
}

function birdInit() {
	dbg('birdInit');

	if ($('j-contentsvote') != null) {
		$('j-contentsvote').observe('click', function(ev) {
			params = $('slavik-form').serialize();

			new Ajax.Request('services/AjaxPlaylistSlavik.html', {
				method: 'post',
				parameters: params,

				onSuccess: function (rq) {
					$('update-slavik').update(rq.responseText);
				}
			});
			
			return false;
		});
	}

	dbg('birdInit');
}

function similarInit() {
	dbg('similarInit');

	if ($$('#similar-wrap').size()) {
		ss = new UI.Carousel('similar-wrap');

		current = ss.currentIndex() + 1;
		count = $$('#similar-wrap .wi').size();

		$$('#similar-wrap .m-move').first().insert({ top: '<li class="position">' + current + ' z ' + count + '</li>' });

		ss.observe('scroll:ended', function(ev) {
			current = ss.currentIndex() + 1;
			count = $$('#similar-wrap .wi').size();
			text = Math.round(current) + ' z ' + count;

			$$('#similar-wrap .m-move .position').first().update(text);
		});
	}

	dbg('similarInit');
}

function elipsisInit() {
	dbg('elipsisInit');

	$$('.j-elipsis').invoke('remove');
	
	$$('.b-grid .grid-none').each(function(el) {
		el.insert({ after: '<b class="j-elipsis">...</b>' });
	});

	dbg('elipsisInit');
}

function centerInit() {
	dbg('centerInit');

	$$('.j-center').each(function(el) {
		ma = (el.up().getWidth() - el.getWidth()) / 2 - 1;
		el.setStyle({ 'marginLeft': ma+'px' });
	});

	dbg('centerInit');
}

function loginInit () {
	dbg('loginInit');
	
	if ($$('#search-form img').size()) { $$('#search-form .m-meta').invoke('setStyle', { 'marginLeft': '55px'}); }

	$$('.login-target').each(function(el) {
		el.observe('click', function(ev) {
			$$('#login-form, #search-form').invoke('toggle');
		});
	});

	dbg('loginInit');
}

function submitInit () {
	dbg('submitInit');

	$$('.j-submit').each(function(el){
		el.observe('click', function(ev){
			if (el.hasClassName('j-submit-disabled')) {
				ev.stop();
			}
			if (el.up('#comment-form')) {
				if (el.up('#comment-form').down('textarea').getValue() == 'Text príspevku') {
					ev.stop();
					alert(msgCommentError);
				}
			}
		})
	});

	dbg('submitInit');
}

function calendarInit () {
	dbg('calendarInit');

	var max = 0;

	$$('.l-calendar .i').each(function(el){
		el.setStyle({ 'height': 'auto' });
		height = el.getHeight();
		if (height > max) max = height;
		if (height > 40) height = height + 20;
	});

	$$('.l-calendar .i').each(function(el){
		el.setStyle({ 'height': max+'px' });

		el.observe('click', function(ev) {

			el1 = ev.element();
			ev.stop();
			
			if (!el1.hasClassName('i')) el1 = el1.up('li');
		
			// ak mame idecko tak ho priradime a ideme dalej
			if (id = el1.readAttribute('id')) {
				id = id.replace('calendar-', '');
				el1.up('.b-calendar').removeClassName('b-grid').addClassName('b-list');
				Effect.ScrollTo('days-'+id, { duration:'0.5', offset:0 });
			} else {
				// inak sa prehodi len zobrazenie na list
				el1.up('.b-calendar').removeClassName('b-grid').addClassName('b-list');
			}
		});
	});

	if ($$('.b-calendar').size()) {
		sw = $$('.b-calendar .m-switch li a');
		sw.each(function(el){
			el.observe('click', function(ev){
				el = ev.element();
				st = el.classNames().toString();
				st = st.replace('j-analytics ', '');
				el.up('.b-calendar').removeClassName('b-grid').removeClassName('b-list').removeClassName('b-line').addClassName('b-'+st);
				ev.stop();
			});
		});
	}

	dbg('calendarInit');
}

function deleteInit () {
	dbg('deleteInit');

	$$('.j-video-delete').each(function(el){
		el.observe('click', function(ev){
			ev.stop();
			el = ev.element();
			an = confirm(msgConfirmDelete);

			if (an){
				window.location = el.readAttribute('href');
			}
		})
	});

	dbg('deleteInit');
}

function selectorInit() {
	dbg('selectorInit');

	$$('.j-selector').each(function(el){
		el.observe('click', function(ev){
			el.down('input').select();
		});
	});

	dbg('selectorInit');
}

function analyticsInit() {
	dbg('analyticsInit');

	dt = '';

	$$('.j-analytics, .j-playlist-add, .j-tab li a').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();

			if (el.hasAttribute('href')) {
				dt = el.readAttribute('href');
			} else {
				cl = $w(el.className);
				cl.each(function(it){
					yt = it.replace('j-analytics-', '');
					if (it.length != yt.length) dt = window.location+'#'+yt;
				});

				if (dt == '') dt = msgAnalError;
			}

			if (window.pageTracker) pageTracker._trackPageview(dt);
		});
	});

	dbg('analyticsInit');
}

function voteInit() {
	dbg('voteInit');

	$$('.i-voting').each(function(el){
		if (!el.hasClassName('i-voting-disabled')) {
			el.down('.up').observe('click', function(ev){
				ev.stop();
				voteAjax(el, 1);
			});
			el.down('.down').observe('click', function(ev){
				ev.stop();
				voteAjax(el, -1);
			});
		} else {
			el.down('.up').observe('click', function(ev){ ev.stop(); });
			el.down('.down').observe('click', function(ev){ ev.stop(); });
		}
	});

	dbg('voteInit');
}

function voteAjax(el, vt) {
	dbg('voteAjax');

	new Ajax.Request(vu, {
		method: 'post',
		parameters: {
			comment: el.up('.i').identify(),
			vote: vt
		},
		onCreate: function() { el.addClassName('i-voting-spell'); },
		onFailure: function() { el.removeClassName('i-voting-spell'); alert(msgAjaxError); },
		onSuccess: function (rq) {
			el.removeClassName('i-voting-spell');
			el.addClassName('i-voting-disabled');
			el.update(rq.responseText);
			[el.down('.up'), el.down('.down')].each(function(el){
				el.observe('click', function(ev){
					ev.stop();
				});
			});
		}
	});

	dbg('voteAjax');
}


function setCookie(cn, cv, ce) {
	var today = new Date();
	today.setTime( today.getTime() );
	if (ce) ce = ce * 1000 * 60 * 60 * 24;
	var ce_date = new Date( today.getTime() + (ce) );

	if (window.location.hostname == 'localhost') cookiedomain = '';

	document.cookie = preCookie + cn + "=" +escape(cv) +	((ce) ? ";expires=" + ce_date.toGMTString() : "") + (";path=/") +	((cookiedomain) ? ";domain=" + cookiedomain : "");
}

function getCookie(cn) {
	if (document.cookie.length > 0) {
		ca = document.cookie.indexOf(preCookie + cn + '=');

		if (ca != -1) {
			ca = ca + preCookie.length + cn.length + 1;
			cb = document.cookie.indexOf(';', ca);
			if (cb == -1) cb = document.cookie.length;
			return unescape(document.cookie.substring(ca, cb));
		}
	}

	return '';
}

function displaySwitch() {
	dbg('displaySwitch');

	if ($$('.b-switch').size()) {
		vpgl = getCookie('vpgl');

		if (vpgl == '') {
			setCookie('vpgl', 'grid', 365);
			vpgl = 'grid';
		}
		
		$$('.b-switch').each(function(el){ el.removeClassName('b-grid').removeClassName('b-list').removeClassName('b-line').addClassName('b-'+vpgl); });

		sw = $$('.b-switch .m-switch li a');
		sw.each(function(el){
			el.observe('click', function(ev){
				el = ev.element();
				st = el.classNames().toString();
				st = st.replace('j-analytics ', '');
				el.up('.b-video').removeClassName('b-grid').removeClassName('b-list').removeClassName('b-line').addClassName('b-'+st);
				setCookie('vpgl', st, 365);
				elipsisInit();
				ev.stop();
			});
		});
	}

	dbg('displaySwitch');
}

function playlistHover(ll) {
	dbg('playlistHover');

	ll = $$(ll);
	
	if (ll.size()) {
		if (ll.first().up('#main-playlist') != undefined) {
			if ($$('#j-player').size()) {
				idx = $('j-player').down().identify().replace('activevideo-', '');

				ll.each(function(el) {
					if (el.identify().replace('j-playlist-video-', '') == idx) el.addClassName('playing').addClassName('active');
				});			
			}
		}

		ll.each(function(el){
			el.observe('mouseenter', function(ev){
				el = ev.element();

				if (!el.hasClassName('i')) el = el.up('.i');
			
				ll.invoke('removeClassName', 'active');
				el.addClassName('active');
			});

			el.observe('mouseleave', function(ev){
				ll.invoke('removeClassName', 'active');
				if (el.up('#main-playlist') != undefined && ($$('#main-playlist .playing').size())) $$('#main-playlist .playing').first().addClassName('active');
			});

			el.observe('click', function(ev){
				el = ev.element();
				window.location = el.down('a').readAttribute('href');
			});
		});
	}

	dbg('playlistHover');
}


var te;
var tf;

function featureSlide(start) {
	ci = sf.currentIndex(start);

	if ((start == 1) || (ci == fl.size() - 1)) cm = 0;
	else cm = ci + 1;

	fl.each(function(el){
		el.removeClassName('active');
	});

	sf.scrollTo(cm);
	fl[cm].addClassName('active');
}

function featureInit() {
	dbg('featureInit');

	if ($$('#j-fader-content').size()) {
		fl = $$('#j-fader-control .i');
		ft = $$('#j-fader-content .i');
		sf = new UI.Carousel('j-fader-content');

		featureSlide(1);

		tf = setInterval('featureSlide()', 5000);

		fl.each(function(el){
			el.observe('mouseenter', function(ev){
				el = ev.element();
				clearTimeout(te);
				clearInterval(tf);

				te = setTimeout(function(){
					if (!el.hasClassName('i')) el = el.up('.i');
					fl.invoke('removeClassName', 'active');
					clearInterval(tf);
					el.addClassName('active');
					sf.scrollTo(fl.indexOf(el));
				}, 500);

				el.observe('mouseleave', function(ev){
					clearInterval(tf);
					tf = setInterval('featureSlide()', 5000);
				});
			});
		});
	}

	dbg('featureInit');
}

function playlistArray() {
	ar = getCookie('pllc');
	ar = ar.split(';');
	ar.pop();

	if (ar[0] == '') ar.shift();
	return ar;
}

function playlistMove(start, override) {
	if (start) {
		window.location = $$('#ajax-playlist li.i ').first().down('em').down('a').readAttribute('href');
	} else {
		plap = getCookie('plap');

		if (plap == 'auto' || override == true) {
			nx = $$('#ajax-playlist ul li.active').first().next();

			if (nx != null) {
				window.location = nx.down('em').down('a').readAttribute('href');
			} else {
				vl.invoke('removeClassName', 'active');
				playlistMode('manual');
			}
		}
	}
}

function onPlayerReady() {
	if($$('#j-player').size()) {
		flash = $('flash1').down();					
		if ($$('#more-playlist .j-playlist .i').last() == $$('#more-playlist .j-playlist .playing').first()) { flash.disableNext(); }
		else { flash.enableNext(); }
	}
}

function onPlaybackStart(id) {
	dbg('onPlaybackStart');
	dbg('onPlaybackStart');
}

function onPlaybackFinish(id, override) {
	dbg('onPlaybackFinish');

	playlistMove(false, override);

	dbg('onPlaybackFinish');
}

function playlistRefresh(load) {
	dbg('playlistRefresh');

	if ($$('#more-playlist').size()) {
		pllc = playlistArray();
		pl = $('more-playlist');

		if (pllc == '') {
			pl.down('#ajax-playlist').hide();
			pl.down('#ajax-playbutton').hide();
			pl.down('.none').show();
			if ($$('.b-square-playlist').size()) $$('.b-square-playlist').first().show();

			tb = Control.Tabs.findByTabId('main-playlist');

			if (load) {
				if (tb.activeContainer == $('main-playlist')) {
					tb.setActiveTab('main-video');
				}
			}
		} else {
			pl.down('#ajax-playbutton').show();
			pl.down('#ajax-playlist').show();
			pl.down('.none').hide();
			if (!$$('.b-square-playlist').empty()) $$('.b-square-playlist').first().hide();

			new Ajax.Request(pu, {
				method: 'post',
				parameters: {
					content: pllc
				},
				onCreate: function() { pl.addClassName('i-playlist-spell'); },
				onFailure: function() { pl.removeClassName('i-playlist-spell'); alert(msgAjaxError); },
				onSuccess: function (rq) {
					pl.removeClassName('i-playlist-spell');
					pl.down('#ajax-playlist').update(rq.responseText);

					if($$('#j-player').size()) {
						onPlaybackStart(0);
					}

					pn = pl.up('.b-body');
					
					if ($('main-playlist').getStyle('display') == 'none') {
						$('main-playlist').addClassName('hideout').show();
						CSBfleXcroll('ajax-scroll');
						$('main-playlist').removeClassName('hideout').hide();
					} else {
						CSBfleXcroll('ajax-scroll');
					}

					playlistHover('#more-playlist .j-playlist .i');

					$$('.j-playlist-remove').each(function(el){
						el.observe('click', function(ev){
							it = ev.element().up().up();
							ev.stop();
							id = $$('#more-playlist .i-playlist .i').indexOf(it);
							pllc = playlistArray();
							pllc.splice(id, 1);
							pllc = pllc.join(';') + ';';
							setCookie('pllc', pllc, 365);
							playlistManage();
							playlistRefresh();
						});
					});
				}
			});
		}
	}

	dbg('playlistRefresh');
}

function playlistManage() {
	dbg('playlistManage');

	ad = $$('.j-playlist-add');
	pllc = playlistArray();

	ad.invoke('removeClassName', 'j-playlist-add-disabled');

	pllc.each(function(it){
		if (it) {
			ad.each(function(al){
				st = al.identify().split('-').last();
				id = Number(st);

				if (it == id) al.addClassName('j-playlist-add-disabled');
			});
		}
	});

	dbg('playlistManage');
}

function playlistAdd(vi) {
	pllc = getCookie('pllc');
	pllc = pllc+vi+';';
	setCookie('pllc', pllc, 365);
	playlistManage();
}

function playlistMode(mode) {
	dbg('playlistMode');
	
	if ($$('#ajax-playbutton').size()) {
		plap = getCookie('plap');
		
		if (mode == 'auto') playlistChangeMode('auto');
		else if (mode == 'manual') playlistChangeMode('manual');
		else if (mode == 'change') {
			if (plap == 'manual') playlistChangeMode('auto');
			else if (plap == 'auto') playlistChangeMode('manual');
		}
		else {
			if (plap == '') playlistChangeMode('manual');
			else  playlistChangeMode(plap);
		}
	}
	
	dbg('playlistMode');
}

function playlistChangeMode(mode) {
	dbg('playlistChangeMode');

	setCookie('plap', mode, 365);

	if (mode == 'auto') $('ajax-playbutton').update('Automatické prehrávanie: <em>zapnuté</em>').addClassName('auto').removeClassName('manual');
	else if (mode == 'manual') $('ajax-playbutton').update('Automatické prehrávanie: <em>vypnuté</em>').addClassName('manual').removeClassName('auto');
		
	dbg('playlistChangeMode');
}

function playlistAuto() {
	dbg('playlistAuto');

	if ($$('#ajax-playbutton').size()) {
		playlistMode();

		$('ajax-playbutton').observe('click', function(ev){
			if (ev.element() == $('ajax-playbutton').down('em')) playlistMode('change');
		});
	}

	dbg('playlistAuto');
}

function playlistInit() {
	dbg('playlistInit');

	$$('.j-playlist-add').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();

			if (!el.hasClassName('j-playlist-add-disabled')) {
				var videoId = el.identify().split('-').last();
				var vi = Number(videoId);
				ev.stop();

				playlistAdd(vi);

				if ($$('#more-playlist').size()) {
					playlistRefresh();
					Control.Tabs.findByTabId('main-playlist').setActiveTab('main-playlist');
				}
				
			}
		});
	});

	dbg('playlistInit');
}

function tabInit() {
	dbg('tabInit');

	$$('.j-tab').each(function(el){
		if (el.down('.active') != undefined) {
			cn = el.down('.active').down('a').readAttribute('href').split('=').last();
			ok = true;
		} else ok = false;

		new Control.Tabs(el);

		if (ok) Control.Tabs.findByTabId(cn).setActiveTab(cn);
	});

	dbg('tabInit');
}

function scrollInit() {
	dbg('scrollInit');

	bd = $$('.b-main .b-body, .b-square-playlist');
	bd.each(function(el){
		if (bd.indexOf(el) != 0) {
			if (el.down('.j-scroll') != undefined) {
				CSBfleXcroll(el.down('.j-scroll').identify());
			}

			el.removeClassName('hideout');
			el.hide();
		}
	});

	dbg('scrollInit');
}

function profileSwitch() {
	dbg('profileSwitch');

	$$('.b-user-profile-edit .edit').each(function(el){
		el.hide();
	});

	$$('.b-user-profile-edit .view h4').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();
			ev.stop();
			el.up('.view').hide();
			el.up('.view').next('.edit').show();
		});
	});

	$$('.b-user-profile-edit .i-submit').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();
			ev.stop();

			// form ajax goes here

			el.up('.edit').hide();
			el.up('.edit').previous('.view').show();
		});
	});

	$$('.b-user-profile-edit .i-reset').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();
			ev.stop();

			el.up('.edit').hide();
			el.up('.edit').previous('.view').show();
		});
	});

	dbg('profileSwitch');
}


function onSnapshotCancel(reply) {
	$('video-image-change').show();
	$('video-flash-change').hide();
}

function onShanpshotError(reply) {
	alert('Na serveri nastala chyba. Skúste to znovu');
	$('video-image-change').show();
	$('video-flash-change').hide();
}

function onSnapshotSuccess(reply) {
	$('video-image-change').show();
	$('video-flash-change').hide();

	// rozparsovat xmlko a updatnut urlku pre obrazok
	$$('#video-image-change img').each(function(e) {
		e.src = e.src + "?update=1";
	});
}


function openPopup(url,name,height,width,opt_show_scrollbars){
	var scrollbar_param=opt_show_scrollbars?",scrollbars=1":"";
	var newwindow=window.open(url,name,'height='+height+',width='+width+scrollbar_param);
	if(newwindow&&!newwindow.opener){newwindow.opener=window;}
	if(window.focus){newwindow.focus()}
	return false;
}

