/* Image Roll-over Javascript -> */
var CURRENT_NEWS=0;
var TOTAL_NEWS;
var ROLLOVER_TIMEOUT=15000;
var autoRollover;
var FADE_SPEED="fast";
$(function(){
	var ct=0;
	$(".rollovertarget").each(function(){
		$(this).attr("id","rollovertarget"+ct++);
		$(this).mouseover(function(){ rollOver(this); });
		$(this).focus(function(){ rollOver(this); });
	});
	TOTAL_NEWS=ct;
	autoRollover=setTimeout(newsRollover,ROLLOVER_TIMEOUT);
		
	var i=0;
	ticker();	
});
function rollOver(atag)
{
	clearTimeout(autoRollover);
	autoRollover=0;
	var src="";
	var ndes="";
	var id=$(atag).attr("id");
	CURRENT_NEWS=parseInt(id.substring(14));
	src=$(atag).attr("imgsrc");
	ndes=$(atag).attr("newsdes");
	if(src!=$("#rolloverimage").attr("src"))
	{
		$(".rollovertarget").each(function(){
			$($(this).parent().parent()).removeClass("selected");
		});
		$($(atag).parent().parent()).addClass("selected");
		//$($(atag).parent()).addClass("curved-corner-right"); 
		$("#rolloverimage").fadeOut(FADE_SPEED, function(){
			$("#rolloverimage").attr("src",src);	
			$("#rolloverimage").fadeIn(FADE_SPEED);
		});
		$(".news_description").html(ndes);
	}
	autoRollover=setTimeout(newsRollover,ROLLOVER_TIMEOUT);
}
function newsRollover()
{
	try{
	CURRENT_NEWS=(CURRENT_NEWS+1)%TOTAL_NEWS;
	var t=$("#rollovertarget"+CURRENT_NEWS);
	if(t) rollOver(t);
	}catch(e){}
}

/* Ticker Javascript -> */
var ticker=function()
{
	var RELOAD_TIMEOUT=300000;//in ms -> 5 minutes
	try{
		var wid=$(".ticker_text").width();
		$(".ticker_text").jStockTicker({
			interval: 30,
			speed: 2
		});
		$(".jStockTicker_container").css("width", wid);
	}catch(e){}
	
	var tickerDataFile=$("#ticker_update_file").val();
	var realoadTimer;
	realoadTimer=setTimeout(realoadTickerData,RELOAD_TIMEOUT);

	function realoadTickerData()
	{
		$(".ticker_text").load(tickerDataFile,function(){
			realoadTimer=setTimeout(realoadTickerData,RELOAD_TIMEOUT);
		});
	}
};

/* Star Rating javascript->*/
function star_Id(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
function star_Style(o) { return((typeof(o)=='object'?o:star_Id(o)).style); }
function star_agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function star_abPos(o) { var o=(typeof(o)=='object'?o:star_Id(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function star_XY(e,v) { var o=star_agent('msie')?{'X':event.clientX+document.body.scrollLeft,'Y':event.clientY+document.body.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }
star={};
star.num=0;
star.mouse=function(e,o) 
{
	if(star.stop || isNaN(star.stop)) {
	star.stop=0;
	document.onmousemove=function(e)
	{
    	var n=star.num;
		var p=star_abPos(star_Id('star_'+n)), x=star_XY(e), oX=x.X-p.X, oY=x.Y-p.Y;			star.num=o.id.substr(5);
		if(oX<1 || oX>84 || oY<0 || oY>19) { star.stop=1; star.revert(); }
		else {
		var t=$('#star_rating_'+n).attr("enabled");
		if(t!="0")
		{
			star_Style('star_curr_'+n).width=oX+'px';
			star_Style('star_user_'+n).color='#111';
			star_Id('star_user_'+n).innerHTML=Math.round(oX/84*100)+'%';
		}
		}
	};
}
};
star.update=function(e,o)
{
	var n=star.num, v=parseInt(star_Id('star_user_'+n).innerHTML);
    var t=$('#star_rating_'+n).attr("enabled");
	if(t!="0")
	{
	n=o.id.substr(5); star_Id('star_curr_'+n).title=v;
	$("#star_rating_loading_"+n).ajaxStart(function(){ $(this).show(); });
	$("#star_rating_"+n).load( $("#loadarticlereviews").val() ,{type : "ratearticle", rating : v, articleid : n},
		function(data){
			$(this).attr("enabled",0);
	});
	$('#star_rating_'+n).attr("title","done");
	}
};
star.revert=function()
{
    var n=star.num, v=parseInt(star_Id('star_curr_'+n).title);
	star_Style('star_curr_'+n).width=Math.round(v*84/100)+'px';
	star_Id('star_curr_'+n).innerHTML=(v>0?Math.round(v)+'%':'');
	star_Id('star_curr_'+n).style.color='#888';
	document.onmousemove='';
};

function showLoginBox()
{
	$.fx.speeds._default = 1000;
	$("#dialogbox").dialog('destroy');
	$("#pwdreset").dialog('destroy');
	$("#dialogbox").dialog({
		autoOpen: true,
		closeOnEscape: true,
		modal: true,
		position: 'center',
		resizable: false,
		draggable: false,
		height: 200,
		width: 550,
		show: "drop",
		hide: "drop"
	});
}
function showPwdresetBox()
{
	$("#dialogbox").dialog('destroy');
	$("#pwdreset").dialog('destroy');
	$("#pwdreset").dialog({
		autoOpen: true,
		closeOnEscape: true,
		modal: true,
		position: 'center',
		resizable: false,
		draggable: false,
		height: 250,
		width: 600
	});
}

$(function(){
	
	var id=0;
	$(".star_rating").each(function(){
		var ratingid=$(this).attr("ratingid");
		$(this).attr("id","star_rating_"+ratingid);
		
		$(this).find(".star").mousemove(function(event){
			$(this).attr("id","star_"+ratingid);
			star.mouse(event,document.getElementById("star_"+ratingid));
		});
		$(this).find(".star").mousedown(function(event){
			star.update(event,document.getElementById("star_"+ratingid));
		});
		$(this).find(".star_curr").attr("id","star_curr_"+ratingid);
		$(this).find(".star_user").attr("id","star_user_"+ratingid);
		$(this).find(".star_rating_loading").attr("id","star_rating_loading_"+ratingid);
	});
	
	$(".dob").each(function(){
		$(this).datepicker({
			dateFormat: 'yy-mm-dd',
			changeMonth: true,
			changeYear: true,
			yearRange: "c-60:c+20"
		});
	});
	
	var sid;
	var tabid;
	/* ADD -> TABS -*/
	$(".tabs:not(.tab-style-2)").each(function(){
		tabid="tab_"+id;
		$(this).attr("id",tabid);
		sid=1;
		$(this).find(".tab-content").each(function(){
			$(this).attr("id",tabid+"_tc_"+sid);
			$(this).attr("tabno",sid);
			sid++;
		});
		sid=1;
		$(this).find(".tab-header").each(function(){
			$(this).attr("id",tabid+"_th_"+sid);
			$(this).attr("tabno",sid);
			$(this).attr("tabid",tabid);
			$(this).click(function(){
				$("#"+$(this).attr("tabid")).find(".tab-header").removeClass("selected-tab");
				$(this).addClass("selected-tab");
				$("#"+$(this).attr("tabid")).find(".tab-content").addClass("tab-closed");
				$("#"+$(this).attr("tabid")+"_tc_"+$(this).attr("tabno")).removeClass("tab-closed");
				$("#"+$(this).attr("tabid")+"_tc_"+$(this).attr("tabno")).addClass("tab-open");
			});
			sid++;
		});
		id++;
	});
	id=1;
	var parent,tid;
	$(".tab-style-2").each(function(){
			$(this).find(".tab-header").click(function(){
				tid=$(this).attr("tid");
				parent=this;
				while(!$(parent).hasClass("tab-style-2"))
				{
					parent=$(parent).parent();
				}
				$(parent).find(".tab-header").removeClass("selected-tab");
				$(this).addClass("selected-tab");
				$(parent).find(".tab-content").load($("#newsbyserieslink").val(), 
						{newstype: 1, tournamentid: tid}, function(){ } );
			});
	});
	
	/* ADD -> Accordion -*/
	id=1;
	$(".accordion").each(function(){
		$(this).attr("accno",id)
		$(this).attr("id","acc_"+id);
		sid=1
		$(this).find(".acc-header").each(function(){
			$(this).attr("accid","acc_"+id);
			$(this).attr("saccno",sid);
			$(this).attr("id","acc_"+id+"_ah_"+sid);
			$(this).click(function(){
				$(this).toggleClass("acc-open");
				$(this).toggleClass("acc-closed");
				$("#"+$(this).attr("accid")+"_ac_"+$(this).attr("saccno")).slideToggle(500);
			});
			sid++;
		});
		sid=1;
		$(this).find(".acc-content").each(function(){
			$(this).attr("accid","acc_"+id);
			$(this).attr("saccno",sid);
			$(this).attr("id","acc_"+id+"_ac_"+sid);
			sid++;
		});
		
		$("#acc_"+id).find(".acc-closed").each(function(){
			$("#"+$(this).attr("accid")+"_ac_"+$(this).attr("saccno")).hide();
		});
		id++;
	});
	
	/** Add Tiny MCE Editors **/
	var elect=0;
	$(".simpletexteditor").each(function(){
		eleid="editor_"+elect++;
		$(this).attr("id",eleid);
		tinyMCE.init({
			// General options
			/*
			skin : "o2k7",
			skin_variant : "silver",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",
	 
			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
	 */
			mode : "exact",
			elements : eleid,
			theme : "advanced",
			skin : "o2k7",
			skin_variant : "silver",
			plugins : "emotions",
			valid_elements : "strong,b,span[style],br,p,script[charset|defer|language|src|type],img[src|title|alt]",
		        invalid_elements : "a,style,script,xml,div",
			theme_advanced_buttons1 : "bold,italic,underline,|,emotions",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			theme_advanced_buttons4 : "",
			//theme_advanced_disable : "table,layer",
			theme_advanced_toolbar_location : "bottom",
			theme_advanced_toolbar_align : "center",
			theme_advanced_statusbar_location : "none",
			theme_advanced_resizing : false,
			relative_urls : false,
			paste_use_dialog : false,
			paste_auto_cleanup_on_paste : true,
			paste_block_drop : true
		});
	});
	function ajaxfilemanager(field_name, url, type, win)
	{
		var ajaxfilemanagerurl = "/js/tinymce/plugins/ajaxfilemanager/ajaxfilemanager/ajaxfilemanager.php?editor=tinymce";
		switch (type) {
			case "image":
				break;
			case "media":
				break;
			case "flash": 
				break;
			case "file":
				break;
			default:
				return false;
		}

		tinyMCE.activeEditor.windowManager.open({
            url: ajaxfilemanagerurl,
            width: 782,
            height: 440,
            inline : "no",
            close_previous : "no"
        },{
            window : win,
            input : field_name
        });
		
		return false;
	}
	
	/**bg adjust**/
	var pwwt=$(".page_wrapper").width();
	var pgwt=$(window).width();
	$("body").css("background-position",""+((pgwt-pwwt)/2-247)+"px top");
	
});
var maxchars=500;
function stripTags_TinyMCE(content)
{
    var re = /(<([^>]+)>)/ig ; //strip all tags
    var plaintext = content.replace(re, "");
    return plaintext;
}
function validateTextLimit(c)
{
	c=stripTags_TinyMCE(c);
	c=$.trim(c);
	if(c.length>maxchars)
	{
		alert("You have exceeded the Maximum Character Limit of "+maxchars+" characters. Please reduce the text");
		return false;
	}
	else if(c.length<2)
	{
		alert("Please write something to comment.");
		return false;
	}
	return true;
}

function loadNews(container, type, page)
{
	var tid;
	if(type==1)
	{
		tid=$("#loadnewstid").val();
		$(container).html("Loading....");
		$(container).load($("#newsbyserieslink").val(), 
				{newstype: type, tournamentid: tid, _pageno: page}, function(){} );
	}
	else
		if(type==2)
		{
			$(container).html("Loading....");
			$(container).load($("#recentnewslink").val(), 
					{newstype: type, _pageno: page}, function(){} );
		}
		else
			if(type==3)
			{
				$(container).html("Loading....");
				$(container).load($("#loadnewsreviews").val(), 
						{type : 'viewnewscomments', newsid : $("#loadnewsid").val(), _pageno: page });
			}
}

function loadArticles(container, type, page)
{
	var tid;
	if(type==1)
	{
		tid=page;
		if(!tid) tid=-1;
		$(container).html("Loading....");
		$(container).load($("#articleslink").val(), 
				{ cc: container , writtenby : tid,  type : "authordetails",  _pageno: page}, function(){
					loadArticles('.authors_lounge_recent_articles', 2, 1);
					loadArticles('.authors_lounge_other_authors', 3, 1);
				});
	}
	else if(type==2)
		{
			tid=$("#recent_article_writtenby").val();
			$(container).html("Loading....");
			$(container).load($("#articleslink").val(), 
					{ cc: container ,  type : "recentarticles", writtenby: tid, _pageno: page}, function(){} );
		}
		else
			if(type==3)
			{
				tid=$("#recent_article_writtenby").val();
				$(container).html("Loading....");
				$(container).load($("#articleslink").val(), 
						{cc: container ,  type : "otherauthors", writtenby: tid, _pageno: page}, function(){} );
			}
			else
				if(type==4)
				{
					tid=$("#loadarticleid").val();
					$(container).html("Loading....");
					$(container).load($("#loadarticlereviews").val(), 
							{cc: container , type : 'viewarticlecomments', articleid : tid, _pageno: page });
				}
}
	
function rateNews(nid, val)
{
	var cns=Array();
	cns[1]='.news_ratingct_like';
	cns[2]='.news_ratingct_dislike'; 
	cns[3]='.news_ratingct_rotten';
	$.getJSON($("#loadnewsreviews").val(), {type : 'ratenews', newsid: nid, rating : val},
			function(json){
				for(var i=1; i<=3; i++)
				if(json[i])
					$(cns[i]).html(json[i]);
				else
					$(cns[i]).html(0);
	});
}
	
function postComment(ctype, stec)
{
	var id=$(stec).attr("id");
	var ctext=tinyMCE.get(id).getContent();
	if(validateTextLimit(ctext))
	{	
		tinyMCE.getInstanceById(id).getBody().innerHTML=' ';
		if(ctype==1)
		{
			$.post($("#loadnewsreviews").val(), 
				{type : 'newscomment', newsid : $("#loadnewsid").val(), commenttext: ctext },
				function(data){ loadNews('.news_comments', 3, 1); });
		}
		else if(ctype==2)
			{
				$.post($("#loadarticlereviews").val(), 
					{type : 'articlecomment', articleid : $("#loadarticleid").val(), commenttext: ctext },
					function(data){ loadArticles('.article_comments', 4, 1); });
			}
	}
}

function refreshNews(nid, tout) {
	$(".news_wrapper").load($("#refreshnews").val(), {newsid : nid},
		function() {
			loadNews('.news_comments', 3, 1);
		});
	setTimeout("refreshNews("+nid+", "+tout+")", tout);
}
