var videoCache = Array();
var curId = 0;

function markVideo(vid) {
	jQuery('.video-list .item').removeClass('item-selected');
	jQuery('.video-list .item[rel='+vid+']').addClass('item-selected');
}

function selectVideo(vid) {
	markVideo(vid);
	jQuery('.one-video').html(videoCache[vid]);
	window.location.hash = '#video-'+vid;
	curId = vid;
	// increasing video views
}

function loadVideo(vid) {
	jQuery('.one-video').html('');
	jQuery.loadWait({
		elem: jQuery('.one-video'),
		rotateCenter: true,
		url: '/ajax/',
		type: 'GET',
		params: { action: 'video', id: vid },
		onDone : function(data) {
			if(data.status == 'ok' && data.content.length > 0 && data.id == vid) {
				videoCache[vid] = data.content;
				selectVideo(vid);
			}
		},
		onError : function(data) {
			videoCache[vid] = -1;
		}
	});
}
	
function initVideoWatching(curTmp) {

	curId = curTmp;

	if(curId) markVideo(curId);
	
	jQuery(document).ready(function() {
		// parsing hash 
		if(window.location.hash != '') {
			var tmp = window.location.hash.substr(1).split('-');
			if(tmp[0] == 'video' && parseInt(tmp[1])) {
				if(jQuery('.item[rel='+tmp[1]+']') != undefined) {
					loadVideo(tmp[1]);
				}
			}
		}
	
		// observing clicking
		jQuery('.video-list .item').click(function(e) {
			var self = jQuery(this);
			var vid = parseInt(self.attr('rel'));
			if(vid && vid != curId) {
				e.preventDefault();
				if(videoCache[vid] != undefined) {
					if(videoCache[vid] != -1)
						selectVideo(vid);
				} else {
					loadVideo(vid);
				}
			}
		});
	});
	
}
