function mpm_trim (v) {
	return v.replace(/^\s+|\s+$/g,"");
}

(function($){
	$.fn.tvbhomempm = function (opts) {
		frame = $(this);
		
		var element_arr = [];
		
		var rotate_interval = null;

		var default_opts = {
			xml : "xml/text.xml",
    		itemPerPage : 4,
    		currentPage : 1,
    		withPagingBar : false,
    		selectedItem : -1,
    		tabLeftMargin : 0,
    		showDesc : true,
    		addHTML : false,
    		withRotate : true,
    		rotateInterval : 5000
		}
		var opt = $.extend(default_opts, opts);
		if($.browser.opera)
		{
			opt.tabLeftMargin = 10;
		}	
		
		if(frame.html() == "")
			opt.addHTML = true;
		
		if(opt.addHTML)
		{
			var layout = "<div class='tvbc_content' style='position:relative; left:0px; top:0px;'>"
			+"<a href='' class='tvbc_link'><img class='tvbc_image' src='http://img.tvb.com/p/blank.gif' style='position:absolute; left:0px; top:0px;'></a><div class='tvbc_right_nav' style='position:absolute;top:0px;right:0px;width:205px; z-index:10;'>"
			+"	<div class='tvbc_top' style='width:100%; height:15px; position:absolute; top:0px;'></div>"
			+"	<div class='tvbc_middle' style='width:190px; position:absolute; top:15px;'><div class='tvbc_tab_container' style='width:100%; position:absolute; top:0px; right:10px;'></div></div>"
			+"	<div class='tvbc_bottom' style='width:100%; height:15px; position:absolute; bottom:0px;'></div>"
			+"	<div class='tvbc_paging' style='position:absolute; display:none; left:0px; top:0px; width:5px; background-color:#000; font-size:0px;'>&nbsp;</div>"
			+"</div><div class='tvbc_description_background' style='z-index:5; position:absolute; display:none; height:50px;'></div><div class='tvbc_description_content' style='z-index:5; position:absolute; display:none; height:50px;'><table style='height:50px;'><tr><td id='tvbc_descript_content_td' style='color:#fff; padding-left:10px;'></td></tr></table></div>"
			+"</div>";
			
			frame.append(layout);
		}
		
		var tabs = [];
		if(opt.withRotate)
		{
			$(frame).mouseout(function(){
				startRotate();
			});
			$(frame).mouseover(function(){
				endRotate();
			});
		}
		var desc_content_panel = frame.find(".tvbc_description_content")[0];
		if(opt.addHTML)
		{
		$(desc_content_panel).css("width", (450)+"px");
		$(desc_content_panel).css("left", "0px");
		$(desc_content_panel).css("top", (frame.height()-50)+"px");
		$(desc_content_panel).css("color", "#FFF");
		$(desc_content_panel).css("fontSize", "15px");
		$(desc_content_panel).css("fontWeight", "bold");
		$(desc_content_panel).css("marginLeft", "0px");
		$(desc_content_panel).css("marginTop", "0px");
		$("#tvbc_descript_content_td").css("fontWeight", "bold");
		$("#tvbc_descript_content_td").css("fontSize", "15px");
		}
		
		var description_background = frame.find(".tvbc_description_background")[0];
		//if(opt.addHTML)
		//{
		$(description_background).css("width", (645)+"px");
		$(description_background).css("left", "0px");
		$(description_background).css("top", (frame.height()-50)+"px");
		
		//$(description_background).css("opacity", "0.0");
		//$("#tvbc_descript_content_td").css("opacity", "0.0");
		if($.browser.msie)
		{
			$(description_background).css("background-color", "#000");
		}
		else
		{
			$(description_background).css("background-image", "url(http://img.tvb.com/p/www/img/mpm_black.png)");
			$(description_background).css("background-position", "0px 0px"); 
			$(description_background).css("background-repeat", "repeat-y");
		} 
		//}
		
		if(opt.showDesc)
		{
			$(description_background).css("display", "block");
			$(desc_content_panel).css("display", "block");
		}
		
		var content_paging = frame.find(".tvbc_paging")[0];
		var content_a = frame.find(".tvbc_link")[0];
		var content_img = frame.find(".tvbc_image")[0];
		if(opt.addHTML)
		{
		$(content_img).css("width", (645)+"px");
		$(content_img).css("height", (250)+"px");
		$(content_img).css("border", "0");
		}
		
		var content = frame.find(".tvbc_content")[0];
		if(opt.addHTML)
		{
		$(content).css("width", (frame.width())+"px");
		$(content).css("height", (frame.height())+"px");
		}
		
		var right_nav = frame.find(".tvbc_right_nav")[0];
		//if(opt.addHTML)
		//{
		$(right_nav).css("height", "0px");
		//}
		
		var middle_nav = frame.find(".tvbc_middle")[0];
		//if(opt.addHTML)
		//{
		if($.browser.msie)
		{
			$(middle_nav).css("height", (frame.height()-20)+"px");
			$(middle_nav).css("top", "5px");
		}
		else
			$(middle_nav).css("height", (frame.height()-30)+"px");
		$(middle_nav).css("overflow", "hidden");
		$(middle_nav).attr("align", "right");
		$(middle_nav).css("right", "8px");
		//}
		
		var tab_container = $(middle_nav).find(".tvbc_tab_container")[0];
		//if(opt.addHTML)
		//{
		$(tab_container).css("overflow", "visible");
		//}
		
		var top_nav_button = frame.find(".tvbc_top")[0];
		var bottom_nav_button = frame.find(".tvbc_bottom")[0];
		//if(opt.addHTML)
		//{
		$(top_nav_button).css("cursor", "pointer");
		$(top_nav_button).css("display", "none");
		$(bottom_nav_button).css("cursor", "pointer");
		$(bottom_nav_button).css("display", "none");
		//}
		var rotate_index = null;
		var rotate_interval = null;
		var rotate_data = null;
		function autoRotateAction ()
		{
			//alert("rotate1");
			endRotate();
			//if(rotate_index == null)
			rotate_index = opt.selectedItem+1;
			//else
			//rotate_index++;
				
			if(rotate_index >= rotate_data.length || rotate_index < 0)
			{
				rotate_index = 0;
			}
			//alert(rotate_index);	
			//selectItem(1, rotate_index);
			//alert("rotate2");
			
			//if(rotate_index >= 0 && rotate_index < c.length)
			$(rotate_data[rotate_index]).trigger("mouseover");
				
			startRotate(); 
		}
		
		function startRotate ()
		{
			//alert("start");
			rotate_interval = setTimeout(autoRotateAction, opt.rotateInterval);
		}
		
		function endRotate ()
		{
			//alert("end");
			if(rotate_interval != null)
				clearTimeout(rotate_interval);
		}
		
		function postAnim () {}
		function getNumberOfPage ()
		{
			return (Math.ceil(tabs.length/opt.itemPerPage));
		}
		function setPagingUI ()
		{
			if(opt.currentPage == getNumberOfPage())
				$(bottom_nav_button).css("visibility", "hidden");
			else
				$(bottom_nav_button).css("visibility", "visible");
				
			if(opt.currentPage == 1)
				$(top_nav_button).css("visibility", "hidden");
			else
				$(top_nav_button).css("visibility", "visible");
		}
		function setPage (p)
		{
			if(p == null || isNaN(p))
				p = opt.currentPage;
				
			if(p < 1)
			{
				p = 1;
				opt.currentPage = p;
			}
			
			if(p > getNumberOfPage())
			{
				p = getNumberOfPage();
				opt.currentPage = p;
			}
				
			var item_idx = ((opt.currentPage-1)*opt.itemPerPage);
			var tab_xy = $(tabs[item_idx].div).position();
			var container_xy = $(tab_container).position();
    		$(tab_container).stop();
    		$(tab_container).animate({ 
    			top : (tab_xy.top*(-1))+"px"
    		}, 200);
    		
    		setPagingUI();
		}
		function pervPage ()
		{
			if(opt.currentPage <= 1)
				return false;
			
			opt.currentPage--;
			setPage();
		}
		function nextPage ()
		{
			if(opt.currentPage >= getNumberOfPage())
				return false;
				
			opt.currentPage++;
			setPage();
		}
    	function selectItem (idx, item_idx)
    	{
    		if(item_idx == opt.selectedItem)
    		{
    			//alert("cc");
    			return false;
    		}
    			
    		var divs = $(tab_container).find("div");
    		
    		if(idx <= 0 || idx > divs.length || isNaN(idx))
    			return false;
    			
    		var cur_idx = 1;
    		
     		divs.each(function(){
	    			if(cur_idx == idx)
	    			{
	    				opt.selectedItem = item_idx;
						$(this).stop();
		    			$(this).animate({ 
		    				left : (0+opt.tabLeftMargin)+"px", opacity:1
		    			}, 200);    			
	    				$(this).attr("class", "active");

	    				var obj = tabs[item_idx];
	    				$(content_img).attr("src", obj.photo_obj.src);

	    				$(content_img).attr("title", obj.title);
	    				$(content_img).attr("alt", obj.title);
	    				$(content_a).attr("href", mpm_trim(obj.link).replace(/\&amp;/g,'&'));
	    				$(content_a).attr("target", obj.target);
	    				
						if(opt.showDesc)
						{	
							$("#tvbc_descript_content_td").html(obj.desc);
							//$("#tvbc_descript_content_td").stop();

							//$(description_background).stop();
							if(obj.desc.length == 0)
							{
								/*if($("#tvbc_descript_content_td").css("opacity") != 0)
				    				$("#tvbc_descript_content_td").fadeTo(10, 0);	
				    			if($(description_background).css("opacity") != 0)	
				    				$(description_background).fadeTo(10, 0);	*/
								$(description_background).css("display", "none");
								$(desc_content_panel).css("display", "none");					    				
							}
							else
							{
								/*if($("#tvbc_descript_content_td").css("opacity") != 1)
				    				$("#tvbc_descript_content_td").fadeTo(150, 1);	
				    			if($(description_background).css("opacity") != 0.7)
				    				$(description_background).fadeTo(150, 0.7);	*/
								$(description_background).css("display", "block");
								$(desc_content_panel).css("display", "block");					    				
							}
						}
						else
						{
							$(description_background).css("display", "none");
							$(desc_content_panel).css("display", "none");						
						}
					}
					else
					{
						$(this).stop();
		    			$(this).animate({ 
		    				left : (10+opt.tabLeftMargin)+"px", opacity:0.7
		    			}, 100);					
						$(this).attr("class", "inactive");
					}
					cur_idx++;
    		});   		
    	}
		function itemClick ()
		{
			//alert("1");
			//if(opt.withRotate)
			//endRotate();
    		var target = this;
    		var idx = 1;
    		$(tab_container).find("div").each(function(){
    			
    			if(this == target && $(this).attr("index") != null)
    			{
    				//alert($(this).attr("index"));
    				selectItem(idx, parseInt($(this).attr("index")));
    			}

				idx++;
    		});		
		}
    	function itemMouseOver ()
    	{
    		if(this.tagName == "DIV" && $(this).attr("class") == "inactive")
    		{
    			$(this).attr("anim", "1");
    			$(this).stop();
    			$(this).animate({ 
    				left : (0+opt.tabLeftMargin)+"px"
    			}, 100, "linear", postAnim);
    		}
    	}
    	function itemMouseOut ()
    	{
    		//if(opt.withRotate)
    		//startRotate();
    		if(this.tagName == "DIV" && $(this).attr("class") == "inactive")
    		{
    			$(this).attr("anim", "1");
    			$(this).stop();
    			$(this).animate({ 
    				left : (10+opt.tabLeftMargin)+"px"
    			}, 50, "linear", postAnim);
    		}
    	}
    	
		function shuffle (arr) 
		{
		    for(var j, x, i = arr.length; i; 
		      j = parseInt(Math.random() * i),
		      x = arr[--i], arr[i] = arr[j], arr[j] = x
			);
			return arr;
		}
		function shuffleLogic ( obj_arr )
		{
		try{
			var tmp_arr = [];
			
			for(var i=0; i < obj_arr.length; i++)
			{
				if(obj_arr[i].sort != null && !isNaN(obj_arr[i].sort))
				{
					if(typeof(tmp_arr[obj_arr[i].sort]) == "undefined")
					{
						tmp_arr[obj_arr[i].sort] = [];
					}
					tmp_arr[obj_arr[i].sort].push(obj_arr[i]);
				}
			}
			var append_arr = [];
			for(var i=0; i < tmp_arr.length; i++)
			{
				if(append_arr.length > 3)
					break;
				if(i != 0)
				{
					tmp_arr[i] = shuffle(tmp_arr[i]);

					if(tmp_arr[i].length > 0)
					{
						append_arr.push(tmp_arr[i][0]);
					}
					else
					{
						if(tmp_arr.length > 0 && tmp_arr[0].length > 0)
							append_arr.push(tmp_arr[0].pop());
					}
				}
			}
			for(var i=0; i < append_arr.length; i++)
			{
				appendObjectDiv(append_arr[i]);
				if(i == 0)
				{
					selectItem(1, $(append_arr[i].div).attr("index"));
				}
			}
		}
		catch(e)
		{
			//alert("haha : "+e.message);
		}
		}
		function appendObjectDiv ( obj )
		{
			if(obj != null && obj.div != null)
				$(tab_container).append(obj.div);
		}
		
		if(opt.addHTML)
		{
    	$.ajax({
    		type : "GET",
    		url : opt.xml,
    		datatype : "xml",
    		success : function (xml) {
    			$(xml).find('item').each(function(){
    				var obj = {};
					obj.sort = parseInt($(this).attr("sort"));
    				obj.title = $(this).text();
    				obj.desc = $(this).attr("cast");
    				obj.thumb = $(this).attr("thumbnail");
    				obj.thumb_obj = new Image();
    				$(obj.thumb_obj).load(function(){
    				}).attr("src", obj.thumb);
    				obj.photo = $(this).attr("fullsize");
    				obj.photo_obj = new Image();
    				$(obj.photo_obj).load(function(){
    				}).attr("src", obj.photo);					
    				obj.link = $(this).attr('url');
    				obj.target = "_self";   				
    				
    				var tmp = document.createElement("DIV");
    				var tmp_a = document.createElement("A");

    				$(tmp_a).attr("href", mpm_trim(obj.link).replace(/\&amp;/g,'&'));
    				$(tmp_a).attr("target", obj.target);
    				
    				$(tmp_a).css("text-decoration", "none");
    				tmp.appendChild(tmp_a);
    				
    				$(tmp).attr("class", "inactive");
    				$(tmp).attr("index", tabs.length);
    				$(tmp).mouseover(itemClick);
    				$(tmp).mouseout(itemMouseOut);
    				$(tmp).css("cursor", "pointer");
    				$(tmp).css("position", "relative");
    				$(tmp).css("left", "10px");
    				$(tmp).css("opacity", "0.8");
    				$(tmp).attr("align", "left");
    				$(tmp).css("margin-top", "5px");
    				$(tmp).css("margin-bottom", "5px");
    				if($.browser.msie)
    					$(tmp).css("padding-right", "3px");
    				tmp.style.display = "block";
    				tmp.style.backgroundColor = "#000";
    				tmp.style.width = "170px";
    				tmp.style.height = "50px";
    				var thumb_div = document.createElement("IMG");
    				thumb_div.src = obj.thumb_obj.src; 
    				thumb_div.style.width = "40px";
    				thumb_div.style.height = "40px";
    				$(thumb_div).css("float", "left");
    				$(thumb_div).css("marginTop", "5px");
    				$(thumb_div).attr("title", obj.title);
    				$(thumb_div).attr("alt", obj.title);
    				if($.browser.msie)
    					$(thumb_div).css("marginLeft", "3px");
    				else
    					$(thumb_div).css("marginLeft", "5px");
    				$(thumb_div).css("marginRight", "10px");
    				
					var title_div = document.createElement("SPAN");

    				$(title_div).css("margin", "0px");
    				$(title_div).css("padding", "0px");
    				if($.browser.msie)
    					$(title_div).css("width", "105px");
    				else
    					$(title_div).css("width", "115px");
    				$(title_div).css("height", "50px");
    				if($.browser.msie)
						$(title_div).html("<table vAlign='center' border='0' style='margin:0px; padding:0px;' width='105px' height='100%'><tr><td style='height: 45px; font-size: 15px; font-weight: bold; color: rgb(255, 255, 255); cursor:pointer;' vAlign='center'><a href='"+mpm_trim(obj.link).replace(/\&amp;/g,'&')+"' target='_self' style='text-decoration:none; height: 45px; font-size: 15px; font-weight: bold; color: rgb(255, 255, 255); cursor:pointer;'>"+obj.title+"</a></td></tr></table>");    				
    				else
    					$(title_div).html("<table vAlign='center' border='0' style='margin:0px; padding:0px;' width='115px' height='100%'><tr><td style='height: 45px; font-size: 15px; font-weight: bold; color: rgb(255, 255, 255); cursor:pointer;' vAlign='center'>"+obj.title+"</td></tr></table>");

    			
    				tmp_a.appendChild(thumb_div);
    				tmp_a.appendChild(title_div);

    				obj.div = tmp;
    				tabs.push(obj);
    			});

    			shuffleLogic(tabs);
    		},
    		error : function () {
    			//alert("fail");
    		}
    	});
    	}
		else
		{
			var c = $(tab_container).children("div");
			//alert(c.length);
			var cnt = 0;
			//$(tab_container).css("opacity", 0);
			//$(tab_container).fadeOut();			
			c.each(function(){
					var img = $(this).find("img")[0];
					var dataset = $(this).find(".tvbc_data")[0];
					var dataarr = $(dataset).html().split("##");
					//alert(dataarr.length);
					//if(dataarr.length < 6)
					//	continue;
					if(	dataarr.length >= 6 ) 
					{
					//$(this).css("width", "170px");
					//$(this).css("overflow", "hidden");
					$(this).css("opacity", 0.7);
   					if(cnt == 0 && !$.browser.msie)
   						$(this).css("margin-top", "0px");
    				/*if($.browser.msie)
    				{	

    					$(this).css("padding-right", "3px");
    					$(img).css("marginLeft", "3px");
    				}
    				else
    				{
    					$(img).css("marginLeft", "5px");
    				}		*/		
    				$(this).mouseover(itemClick);
    				if(cnt == 0)
    					cnt = $(this);
    				$(this).mouseout(itemMouseOut);
    				
    				var obj = {};
					obj.sort = parseInt(dataarr[0]);
    				obj.title = dataarr[1];
    				obj.desc = dataarr[2];
    				obj.thumb = dataarr[3];
    				obj.thumb_obj = new Image();
    				$(obj.thumb_obj).load(function(){
    				}).attr("src", obj.thumb);
    				obj.photo = dataarr[4];
    				obj.photo_obj = new Image();
    				$(obj.photo_obj).load(function(){
    				}).attr("src", obj.photo);					
    				obj.link = dataarr[5];
    				obj.target = "_self"; 
    				
    				obj.div = this;
    				
    				tabs.push(obj);
    				//alert(cnt);
    				//if(cnt == 0)
    				//	selectItem(1, $(this).attr("index"));
    				//cnt++;
    				}
			});
			//cnt.trigger('mouseover');
			rotate_data = c;

			//selectItem(1, 0);
			//selectItem(0, 0);
			
			$(tab_container).css("visibility", "visible");
			$(tab_container).css("left", "300px");
			//$(tab_container).css("opacity", 1);
			//$(tab_container).css("opacity", 0);
			//$(tab_container).css("opacity", 1);
			//$(tab_container).css("opacity", 0);
		  	$(tab_container).animate({ 
		   	left:(-10-(opt.tabLeftMargin))
		   	}, 1000, "swing", postInitFunc);
		   	//postInitFunc();
		   	//$(tab_container).fadeIn();   
			//(tab_container).fadeIn();
			
			if(tabs.length <= 1)
				$(right_nav).css("display", "none");
		}
		
		function postInitFunc ()
		{
			if(rotate_data.length > 0)
			{
				$(rotate_data[0]).trigger('mouseover');
				if(opt.withRotate && tabs.length > 0)
					startRotate();
			}
		}
		//alert("yyy");
		$(top_nav_button).click(function (){
			pervPage();
		});
		$(bottom_nav_button).click(function () {
			nextPage();
		});
	}
})(jQuery);