google.load("feeds", "1");

function InterneteExplorer() {
	this.addFunction = function(element, event, code) {
		element.setAttribute(event, new Function(code));
	}
	this.setStyleClass = function(element, className) {
		element.setAttribute("className", className);
	}
	this.setStyleFloat = function(element, value) {
		element.style.styleFloat = value;
	}
}

function Firefox() {
	this.addFunction = function(element, event, code) {
		element.setAttribute(event, code);
	}
	this.setStyleClass = function(element, className) {
		element.setAttribute("class", className);
	}
	this.setStyleFloat = function(element, value) {
		element.style.cssFloat = value;
	}
}

function CrossBrowser() {
	var isMSIE = /*@cc_on!@*/false;
	
	var delegate = null;
	if (isMSIE) {
		delegate = new InterneteExplorer();
	} else {
		delegate = new Firefox();
	}
	
	this.addFunction = function(element, event, code) {
		delegate.addFunction(element, event, code);
	}
	this.setStyleClass = function(element, className) {
		delegate.setStyleClass(element, className);
	}
	this.setStyleFloat = function(element, value) {
		delegate.setStyleFloat(element, value);
	}
}


function setClass(element, className) {
	var cross = new CrossBrowser();
	cross.setStyleClass(element, className);
}

function Video(title, url) {
	this.title = title;
	this.url = url;
}

function Search(playerName, wordInput, pagenationDiv, resultDiv) {

    this.word = wordInput
    this.pagenation = pagenationDiv;
    this.result = resultDiv;
    this.page = 0;
    this.playerName = playerName;
    this.cross = new CrossBrowser();
    
    var COUNT_PER_PAGE = 24;
    var LOADING_IMAGE = "loadinfo.net.gif";
    
	this.search = function() {
		if (this.getWord() == "") return;
		this.visiblePagenate();
		this.page = 0;
		this.query();
	}
	
	this.previous = function() {
		if (this.page <= 0) return;
 		this.page--;
 		this.query();
	}
	
    this.next = function() {
		this.page++;
		this.query();
    }
    
    this.getWord = function() {
		return encodeURIComponent(this.word.value);
    }

    this.visiblePagenate = function() {
		this.pagenation.style.display = "block";
    }

    this.getStartIndex = function() {
		return this.page * COUNT_PER_PAGE + 1;
    }
    
    this.query = function() {
		var container = this.result;
		container.innerHTML = "";
		var img = document.createElement("img");
		img.setAttribute("src", LOADING_IMAGE);
		container.appendChild(img);
		
		var feed = new google.feeds.Feed("http://gdata.youtube.com/feeds/api/videos?alt=rss&format=1&start-index=" + this.getStartIndex() + "&max-results=24&orderby=viewCount&vq=" + this.getWord());
		feed.setNumEntries(COUNT_PER_PAGE);
		var playerName = this.playerName;
		var cross = this.cross;
		feed.load(function(result) {
			if (!result.error) {
				container.innerHTML = "";
				for (var i = 0; i < result.feed.entries.length; i++) {
					var entry = result.feed.entries[i];
					var div = document.createElement("div");
					cross.addFunction(div, "onclick", playerName + ".play('" + entry.title + "', '" + entry.link + "');");
					cross.addFunction(div, "onmouseover", "setClass(this, 'videoMouseOn');");
					cross.addFunction(div, "onmouseout", "setClass(this, 'video');");
					cross.setStyleClass(div, "video");
					div.appendChild(document.createTextNode(entry.title));
					container.appendChild(div);
				}
			}
		});
	}
}

function Player(videoDiv, controlDiv, playListDiv) {

	this.current = 0;
	this.video = videoDiv;
	this.player = null;
	this.playListContainer = playListDiv;
	this.control = controlDiv;
	this.cross = new CrossBrowser();
	this.playList = new Array();
	this.playListServer = new DefaultPlayListServer();
	this.playerName = null;
	this.isRandom = false;
	
	this.attach = function(playerName, playListServer) {
		this.playerName = playerName;
		this.playListServer = playListServer;
		var videos = this.playListServer.getPlayList();
		for (var i = 0; i < videos.length; i++) {
			this.play(videos[i].title, videos[i].url);
		}
	}
	
	this.randomPlay = function(b) {
		this.isRandom = b;
	}
	
	this.play = function(title, url) {
		var video = new Video(title, url);
		if (this.playList.length == 0) {
			this.playVideo(video);
		}
		this.addPlayList(video);
	}

	this.playVideo = function(video) {
		var tag = video.url.split("=")[1];
		this.video.innerHTML = "";
		var div = document.createElement("div");
		div.id = "youtubeplayer_inner";
		this.video.appendChild(div);
	
		var params = { allowScriptAccess: "always" };
		var atts = { id: "youtubeplayer_player" };
		swfobject.embedSWF("http://www.youtube.com/v/" + tag + "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer", 
							"youtubeplayer_inner", "425", "356", "8", null, null, params, atts);	
	}
	
	this.callback = function(playerName) {
		this.playerName = playerName;
		this.player = document.getElementById("youtubeplayer_player");
		setTimeout(this.playerName + ".player.playVideo();", 2000);
	
		this.player.addEventListener("onStateChange", this.playerName + ".changeStatus");
		this.player.addEventListener("onError", this.playerName  + ".onError");
	}

	this.changeStatus = function(state) {
		if (0 == state) {
			this.next();
		}
	}
	this.onError = function(errorCode){};


	this.next = function() {
		if (this.isRandom) {
			this.current = Math.floor(Math.random()*this.playList.length);
		} else {
			this.current++;
			if (this.playList.length <= this.current) {
				this.current = 0;
			}
		}
		this.seek(this.current);
	}

	this.previous = function() {
		this.current--;
		if (0 > this.current) {
			this.current = this.playList.length - 1;
		}
		this.seek(this.current);
	}

	this.seek = function(index) {
		this.current = index;
		this.playVideo(this.playList[this.current]);
		this.createPlayList();
	}

	this.addPlayList = function(video) {
		this.playList.push(video);
		this.createPlayList();
		this.control.style.display = "inline";
	}
	
	this.addUrl = function (title, url) {
		if (title == "") {
			title = url.split("=")[1];
		}
		this.play(title, url);
	}

	this.nowPlay = function(e, i) {
		if (this.current != i) {
			setClass(e, 'video');
		} else {
			setClass(e, 'videoNowPlay');
		}
	}

	this.createPlayList = function() {
		var container = this.playListContainer;
		container.innerHTML = "";
		for (var i = 0; i < this.playList.length; i++) {
			var div = document.createElement("div");
			this.cross.addFunction(div, "onclick", this.playerName + ".seek('" + i + "');");
			this.cross.addFunction(div, "onmouseover", "setClass(this, 'videoMouseOn');");
			this.cross.addFunction(div, "onmouseout", this.playerName + ".nowPlay(this, " + i + ");");
			this.cross.setStyleClass(div, "video");
			
			this.nowPlay(div, i);

	    	div.appendChild(document.createTextNode(this.playList[i].title));
	    
		    var line = document.createElement("div");

			var input = document.createElement("input");
			input.id = "del" + i;
			input.type = "checkbox";
			this.cross.setStyleFloat(input, "left");
		    line.appendChild(input);
		    line.appendChild(div);
		    container.appendChild(line);
		}
		this.playListServer.changePlayList(this.playList);
	}

	this.clear = function() {
		this.playList = new Array();
		this.createPlayList();
	}

	this.remove = function() {
		var list = new Array();
		var reflesh = false;
		for (var i = 0; i < this.playList.length; i++) {
			var check = document.getElementById("del" + i);
			if (!check.checked) {
				list.push(this.playList[i]);
				continue;
			}
			if (i == this.current) {
				reflesh = true;
			}
		}
		this.playList = list;
		this.createPlayList();
		if (reflesh) {
			this.seek(0);
		}
	}
}

function DefaultPlayListServer() {
	this.getPlayList = function() {
		return new Array();
	}
	this.changePlayList = function(playList) {
	}
}

function CookiePlayListServer() {

	var SEPARATOR = "!#$%&'[";

	this.getPlayList = function() {
		var result = new Array();
		var value = document.cookie;
		var pos = value.indexOf("YOUTUBE_PLAYER_PLAYLIST=");
		if (-1 == pos) {
			return result;
		}
		value = unescape(value.substring(pos + 24));
		
		var videos = value.split(SEPARATOR);
		videos.pop();
		
		for (var i = 0; i < videos.length; i += 2) {
			result.push(new Video(videos[i], videos[i + 1]));
		}
		return result;
	}
	
	this.changePlayList = function(playList) {
		var expires = new Date();
		expires.setTime(expires.getTime() + 365*24*60*60*1000);
		var value = "";
		for (var i = 0; i < playList.length; i++) {
			value += playList[i].title + SEPARATOR + playList[i].url + SEPARATOR;
		}
		value = escape(value);
		document.cookie = "YOUTUBE_PLAYER_PLAYLIST=" + value + "; expires=" + expires.toGMTString();
	}
}

function onYouTubePlayerReady(playerId) {
	callback();
}