//On Hover Over
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width

    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
  });
}
//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};

pagerange = 4;
$(document).ready(function(){
	
	$.get('ei.php', function (data) {
		$("#episode-index").html(utf8to16(decode64(data)));
		$("ul#episode-index li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
		$("ul#episode-index li").hoverIntent(config); //Trigger Hover intent with custom configurations
	});
	$('#search-submit').click(Search);

	_initSearchData();
	_initUserData();
	$('#Login').submit(Login);
	$('#Register').click(Register);
	
});

function _initSearchData()
{
	if(location.hash.length > 1)
		initdata = location.hash.slice(1);
	else
		initdata = '1';
	initdata = initdata.split('|');
	if(initdata.length == 1)
	{
		searchword = '';
		initpage = initdata[0];
	}
	else
	{
		searchword = decodeURIComponent(initdata[0]);
		$('#search-input').val(searchword);
		initpage = initdata[1];
	}
	cpage = 0;
	Pagi(searchword, Number(initpage));
}

function Pagi(word, page)
{
	var url;
	var eword = encodeURIComponent(word);
	var eeword = encode64(eword);
	if(word.length == 0)
		url = 'ajax.php?page=' + page;
	else
		url = 'ajax.php?page=' + page + '&word=' + eeword;
	$('.mi_progress').show();
	$.get(url, null, function(data) {
		$("#main-index").html(utf8to16(decode64(data)));
		var pcount = $('tbody[count]').attr('count');
		$('.main-pagination li[id]').remove();
		if(pcount > 0)
		{
			var arr = [];
			var i = 1;
			if(eword.length > 0)
				eword += '|';
			if(page != i)
				arr.push('<li id="p' + i + '"><a href="#' + eword + i + '" onclick="return PrePage(' + i + ')">' + i + '</a></li>');
			var st = Math.max(page - pagerange, 2);
			if(st > i + 1)
				arr.push('<li id="sp">...</li>');
			for(i = st; i < page; i++)
				arr.push('<li id="p' + i + '"><a href="#' + eword + i + '" onclick="return PrePage(' + i + ')">' + i + '</a></li>');
			i = page;
			arr.push('<li id="p' + i + '"><a href="#' + eword + i + '" onclick="return PrePage(' + i + ')"><strong>' + i + '</strong></a></li>');
			i++;
			var ed = Math.min(page + pagerange, pcount);
			for(; i < ed; i++)
				arr.push('<li id="p' + i + '"><a href="#' + eword + i + '" onclick="return PrePage(' + i + ')">' + i + '</a></li>');
			if(pcount > ed)
				arr.push('<li id="sp">...</li>');
			i = pcount;
			if(page != i)
				arr.push('<li id="p' + i + '"><a href="#' + eword + i + '" onclick="return PrePage(' + i + ')">' + i + '</a></li>');
			$('.main-pagination').append(arr.join(''));
		}
		cpage = page;
		if(word.length > 0)
		{
			pageTracker._trackPageview("/Search:" + eeword);
		}
		else
		{
			pageTracker._trackPageview("/Pagi");
		}
		$('.magnet-link').click(function (){pageTracker._trackPageview('/Magnet');});
		$('.torrent-link').click(function (){pageTracker._trackPageview('/Torrent');});

		$('#feedurl').attr('href', 'feed.php' + (word ? ('?word=' + eeword) : ''));

		$('.mi_progress').hide();
		window.scrollTo(0, 0);
	});
	return false;
}

function PrePage(i)
{
	if(typeof i == 'undefined')
		i = 1;
	if(searchword.length > 0)
		location.hash = '#' + encodeURIComponent(searchword) + '|' + i;
	else
		location.hash = '#' + i;
	return Pagi(searchword, i);
}

function Search()
{
	searchword = $('#search-input').val();
	PrePage();
}

function PreSearch(word)
{
	searchword = word;
	$('#search-input').val(word);
	return PrePage();
}

function _initUserData()
{
	var cusername = $.cookie('username');
	if(cusername)
		$('#UserAction').click(MemberPanelShow);
	else
	{
		$('#UserGuestPanel').dialog({autoOpen: false});
		$('#UserAction').click(GuestPanelShow);
	}
	var username = cusername || '游客';
	$('#Username').html(username);
	//$('#UserAction').click(function (){$('#UserPanel').toggle();return false;});
}

function GuestPanelShow()
{
	if($('#UserGuestPanel').is(':visible'))
		$('#UserGuestPanel').dialog('close');
	else
		$('#UserGuestPanel').dialog('open');
	return false;
}

function MemberPanelShow()
{
	//$('#UserPanel').dialog();
	return false;
}

function Register()
{
	var old = $('#submit-table #Action').val();
	$('#submit-table #Action').val('Register');
	Login();
	$('#submit-table #Action').val(old);
}

function Login()
{
	var mail = $('#Login #eMail').val();
	var pass = $('#Login #Password').val();
	if(mail.length == 0 || !mail.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,5})+$/))
	{
		$("#Login #eMail").effect('highlight', {color:'#ff99ff'}, 500);
		return false;
	}
	if(pass.length < 6)
	{
		$("#Login #Password").effect('highlight', {color:'#ff99ff'}, 500);
		return false;
	}
	var formdata = $('form#Login').serializeArray();
	var postdata = encode64(JSON.stringify(formdata));
	$('#Message').hide();
	$('#LoginLoading').show();
	$.post('user.php', {post: postdata}, function(data) {
		$('#LoginLoading').hide();
		if(data == 'SUCC')
			location.reload();
		else
			$('#Message').html(data).show();
	});
	return false;
}

window.onhashchange = _initSearchData;
