var videoPlayed = false;

function onYouTubePlayerReady(playerId) {
    ytplayer = $$("#video_container object")[0];
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	if (videoPlayed) {
		return;
	}
	if (newState === 1) { // Playing
		videoPlayed = true;
		if (mainVideoId) {
			var ajax = new Ajax.Request('/plugins/ajax/update_video_views.php', {
				method: 'post',
				parameters: {
					video_id: mainVideoId
				}
			});
		}
	}
}

function sendUserRating(item, rating) {
	var type = 'video';
	var url = document.location.href;
	if (url.indexOf('/photo/') != -1) {
		type = 'images';
	}
	var ajax = new Ajax.Request('/plugins/ajax/upload_rating.php', {
		method: 'post',
		parameters: {
			item: item,
			rating: rating,
			type: type
		}
	});
}

document.observe("dom:loaded", function() {
	$$('div.star').each(function (item) {
		item.observe('mouseout', function() {
			$$('.initial-full').each(function (item) {
				item.addClassName('ico-starFull');
				item.removeClassName('ico-starHalfPast');
				item.removeClassName('ico-starClear');
			});
			$$('.initial-half').each(function (item) {
				item.removeClassName('ico-starFull');
				item.addClassName('ico-starHalfPast');
				item.removeClassName('ico-starClear');
			});
			$$('.initial-clear').each(function (item) {
				item.removeClassName('ico-starFull');
				item.removeClassName('ico-starHalfPast');
				item.addClassName('ico-starClear');
			});
		});
	});
	var handler = function (item) {
		var star = item.id.replace('stararea-', '');
		item.observe('mouseover', function() {
			for (var i = 1; i < 10; i = i + 2) {
				var div = $('star-' + i);
				if (i < star) {
					div.addClassName('ico-starFull');
					div.removeClassName('ico-starHalfPast');
					div.removeClassName('ico-starClear');
				} else if (i == star) {
					div.removeClassName('ico-starFull');
					div.addClassName('ico-starHalfPast');
					div.removeClassName('ico-starClear');
				} else {
					div.removeClassName('ico-starFull');
					div.removeClassName('ico-starHalfPast');
					div.addClassName('ico-starClear');
				}
			}
		});
		item.observe('click', function() {
			sendUserRating(item.readAttribute('itemid'), star);
			return false;
		});
	};
	$$('div.star div > span > a').each(handler);
	$$('div.star div > a').each(handler);
});