var uu = 'ajax-upload.html'; // upload service url
var pu = 'ajax-playlist.html'; // playlist service url
var vu = 'ajax-vote.html'; // vote service url 
var ru = 'ajax-rate.html'; // rate service url 
var su = 'ajax-stat.html'; // stat service url 

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 = false; // magic debugging

document.observe('dom:loaded', function(){ // one and only domload observer, order is important!
	scrollInit(); 										// featured custom scrollers start
	analyticsInit(); 									// observing ajax links and events
	selectorInit(); 									// selects embed & url in video detail
	playlistHover(); 									// 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
	uploadInit(); 										// upload initialisation
	tabInit(); 												// all tabs start here
	playlistRefresh(true);						// ajax refresh of playlist
	playlistManage();									// disabling links of videos
	similarInit();										// animations for similair videos
	rateInit(); 											// video rating
	voteInit(); 											// comment voting
	statObserver(); 									// ajax for statistics
	submitInit(); 										// events for submit link buttons
	deleteInit(); 										// delete confirmation observer
	setInterval("timeInit()", 1000); 	// timery na header
});

function dbg(output) {
	if (dbgFlag) if (console) console.log(output);
}

function crossDomainReq(el, source) {
	if (el != undefined) {
		script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'cdr.js';
		script.addClassName('cdr');
		$$('.cdr').invoke('remove');
		$$('body').first().insert({ bottom: script });
		script.onload = function() { cdr(el); }
		script.onreadystatechange = function() { if (this.readyState == 'complete') cdr(el); }
	}
}

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 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 timeInit () {
	var curtime = new Date();
	var curhour = curtime.getHours();
	var curmin = curtime.getMinutes();
	var cursec = curtime.getSeconds();
	var time = "";

	time = (curhour == 0 ? "00" : curhour) + ":" +
	(curmin < 10 ? "0" : "") + curmin + ":" +
	(cursec < 10 ? "0" : "") + cursec;

	if ($('jstime')) $('jstime').innerHTML = time;
}


function statObserver() {
	dbg('statObserver');

	$$('#main-stat .m-move a').each(function(el){
		el.observe('click', function(ev){
			el = ev.element();
			ev.stop();

			if (!el.up('li').hasClassName('disabled')) {
				statAjax(el.identify());
			}
		});
	});

	dbg('statObserver');
}

function statAjax(time) {
	dbg('statAjax');

	if ($$('#main-stat').size()) {
		el = $('main-stat');

		new Ajax.Request(su, {
			method: 'post',
			parameters: {
				stat: time,
				video: $$('.videodetail').first().identify()
			},
			onCreate: function() { el.addClassName('i-stat-spell'); },
			onFailure: function() { el.removeClassName('i-stat-spell'); alert(msgAjaxError); },
			onSuccess: function (rq) {
				el.removeClassName('i-stat-spell'); 
				el.update(rq.responseText);

				statObserver();
			}
		});
	}

	dbg('statAjax');
}

function similarInit() {
	dbg('similarInit');
	
	if ($$('#similar-wrap').size()) { 
		ss = new UI.Carousel('similar-wrap');
	}

	dbg('similarInit');
}

function onUploadError(flashID, reply) {
	//alert(reply);
	alert(msgUploadError);
}

function onUploadComplete(flashID, reply) {
	if (window.DOMParser) {
		parser = new DOMParser();
		xmlDoc = parser.parseFromString(reply, "text/xml");
	} else { // Internet Explorer
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(reply);
	} 

	var path = xmlDoc.getElementsByTagName("result")[0].attributes.getNamedItem("url").value;

	// extract video extension from url
	var videoExt = path.split('.');
	videoExt = videoExt[videoExt.length-1];

	path = path.split('/');
	var dir = path[path.length-2]; 

	var originalFilename = xmlDoc.getElementsByTagName("result")[0].attributes.getNamedItem("originalFilename").value;

	if ( $('videoTitle').getValue() == "" ) {
		$('videoTitle').setValue(originalFilename);
	}
	//document.getElementById('videoTitle').value = originalFilename;
	document.getElementById('uploadUrl').value = dir;
	document.getElementById('videoExt').value = videoExt;
	
	uploadSwitch(dir);
}

function onUploadStart(flashID) {
	$('form-content').show();
}

function uploadPrepare() {
	dbg('uploadPrepare'); 

	li = $$('.record-select .i img');
	li.each(function(el){
		to = (110 - el.getHeight()) / 2;
		el.setStyle({ 'top': to+'px' })
		el.setStyle({  })
			
		el.observe('click', function(ev){
			el = ev.element();
			
			$('record-thumbnail').setValue(li.indexOf(el) + 1);
			
			li.each(function(el){
				el.up().removeClassName('active');
			});

			el.up().addClassName('active');
		});
	});
	
	$$('.b-video-record .j-submit').first().removeClassName('j-submit-disabled').removeClassName('i-submit-60-disabled');
	
	CSBfleXcroll('record-scroll'); 

	dbg('uploadPrepare');
}

function uploadInit() {
	dbg('uploadInit');

	if ($$('.record-select-visible').size()) {
		uploadPrepare();
	}

	dbg('uploadInit');
}

function uploadSwitch(id) {
	dbg('uploadSwitch');

	if ($$('.record-wrap').size()) {

		el = $$('.record-wrap').first();
		
		new Ajax.Request(uu, {
			method: 'post',
			parameters: {
				video: id
			},
			onSuccess: function (rq) {
				el.update(rq.responseText);
				
				$$('.record-flash, .record-select').invoke('toggle');
				uploadPrepare();
			}
		});
	}

	dbg('uploadSwitch');
}

function rateInit() {
	dbg('rateInit');

	$$('.i-rating ul').each(function(el){
		dl = el.up().down('div');
		dw = Number(dl.getStyle('width').replace('px', ''));
		xl = el.childElements();

		xl.each(function(li){
			li.observe('mouseover', function(ev){ 
				dx = 14 * (xl.indexOf(ev.element()) + 1); 
				dl.setStyle({
					width: dx+'px'
				});
			});
			
			li.observe('mouseout', function(ev){
				dl.setStyle({ 'width': dw+'px' });
			});
			
			li.observe('click', function(ev){
				new Ajax.Request(ru, {
					method: 'post',
					parameters: {
						video: el.up().identify(),
						vote: xl.indexOf(li)
					},
					onCreate: function() { el.up('div').addClassName('i-rating-spell'); },
					onFailure: function() { el.up('div').removeClassName('i-rating-spell'); alert(msgAjaxError); },
					onSuccess: function (rq) {
						el.up('div').removeClassName('i-rating-spell'); 
						el.up().replace(rq.responseText);
					}
				});
			});
		});
	});

	dbg('rateInit');
}

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 ex = new Date();
	ex.setDate(ex.getDate() + ce);
	document.cookie=cn+'='+escape(cv)+((ce==null) ? '' : ';expires='+ex.toGMTString())+';path=/';
}

function getCookie(cn) {
	if (document.cookie.length > 0) {
		ca = document.cookie.indexOf(cn + '=');

		if (ca != -1) {
			ca = ca + 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);
		else $$('.b-switch').each(function(el){ el.removeClassName('b-video-grid').removeClassName('b-video-list').addClassName('b-video-'+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-video-grid').removeClassName('b-video-list').addClassName('b-video-'+st);
				setCookie('vpgl', st, 365);
				ev.stop();
			});
		});
	}

	dbg('displaySwitch');
}


function playlistHover() {
	dbg('playlistHover');

	ll = $$('#main-more .j-playlist .i');

	ll.each(function(el){
		el.observe('mouseenter', function(ev){
			el = ev.element();
			if(el.hasClassName('i')) {
				el.addClassName('active');
			}
		});
		el.observe('mouseleave', function(ev){
			el = ev.element();
			ll.each(function(el){
				el.removeClassName('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) {
	if (start) { 
		window.location = $$('#ajax-playlist li.i ').first().down('em').down('a').readAttribute('href');
	} else {
		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');
	}
}

function onPlaybackStart(id) {
	dbg('onPlaybackStart'); 
	dbg('onPlaybackStart');
}

function onPlaybackFinish(id) {
	dbg('onPlaybackFinish');

	playlistMove(false);

	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')) $$('.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')) $$('.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 (pn.getStyle('display') == 'none') {
						pn.show();
						CSBfleXcroll('ajax-scroll'); 
						pn.hide();
					} else {
						CSBfleXcroll('ajax-scroll'); 
					}
					
					playlistHover();
					
					$$('.j-playlist-remove').each(function(el){
						el.observe('click', function(ev){
							it = ev.element().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 playlistInit() {
	dbg('playlistInit');

	if ($$('#ajax-playbutton').size()) { 
		$('ajax-playbutton').observe('click', function(ev){
			playlistMove(true);
		});
	}

	$$('.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();
			}
		});
	});

	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;
}

