jQuery.fn.highlight=function(b){function a(e,j){var l=0;if(e.nodeType==3){var k=e.data.toUpperCase().indexOf(j);if(k>=0){var h=document.createElement("span");h.className="highlight";var f=e.splitText(k);var c=f.splitText(j.length);var d=f.cloneNode(true);h.appendChild(d);f.parentNode.replaceChild(h,f);l=1}}else{if(e.nodeType==1&&e.childNodes&&!/(script|style)/i.test(e.tagName)){for(var g=0;g<e.childNodes.length;++g){g+=a(e.childNodes[g],j)}}}return l}return this.each(function(){a(this,b.toUpperCase())})};jQuery.fn.removeHighlight=function(){return this.find("span.highlight").each(function(){this.parentNode.firstChild.nodeName;with(this.parentNode){replaceChild(this.firstChild,this);normalize()}}).end()};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


$.ajaxSetup({
	type:	"POST"
});

function setProgressBar()
{
	var doFrames = [ document ];
	if ( parent.frames.length > 1 )
	{
		if ( parent.frames[1].document == document ) doFrames[doFrames.length] = parent.frames[2].document;
			else doFrames[doFrames.length] = parent.frames[1].document;
	}

	for (i in doFrames)
	{
		if ($('div#progressBar', doFrames[i]).length > 0)
		{
			var filmsSeen = $('.Films li.seen', doFrames[i]).length;
			var filmsTotal = $('.Films li', doFrames[i]).length;
			var filmsLeft = filmsTotal - filmsSeen;

			var procent = (filmsSeen == 0) ? 0 : Math.round( (filmsSeen*1000) / filmsTotal ) / 10;
			
			if (procent == 100) $('div#progressBar div.info', doFrames[i]).html('100% &mdash; Cleared!');
				else $('div#progressBar div.info', doFrames[i]).html( procent + '% seen &mdash; ' + filmsLeft + ' ' + ( filmsLeft > 1 ? 'titles' : 'title' ) + ' left' );
			
			$('div#progressBar div.info', doFrames[i]).width( $('body', doFrames[i]).width() * 0.95 );
			
			$('div#progressBar div.bar', doFrames[i]).animate( { width: procent+"%" }, 650 );
		}
	}
}

function checkFilm(id, checkbox)
{
	if ($.cookie('askedToLogIn') == null && $.cookie('profileId') == null) if (confirm('You have to be logged in to save checked movies. Log in now?')) document.location = 'login.php';
		else $.cookie('askedToLogIn', 'yes', { expires: 0.003 });
	
	var doFrames = [ document ];
	if ( parent.frames.length > 1 )
	{
		if ( parent.frames[1].document == document ) doFrames[doFrames.length] = parent.frames[2].document;
			else doFrames[doFrames.length] = parent.frames[1].document;
	}

	$.ajax({
		url:	'ajax/items.edit.php',
		data:	{	type: 'seen',
					filmId:	id, 
					action: $(checkbox).attr('checked') ? 'add' : 'remove'
				},

		beforeSend: function () {
			for (i in doFrames) $('input#film'+id, doFrames[i]).attr('disabled', 'disabled');
			},

		success: function(response) {
			for (i in doFrames)
			{
				$('input#film'+id, doFrames[i]).attr('checked', $(checkbox).attr('checked') ).attr('disabled', '').parent().toggleClass('seen');
			}
			setProgressBar();
			}
	});
}

function friendRequest(friend_name, button)
{
	$.ajax({
		url:		'ajax/friendrequest.php',
		data:		{ friend_name: friend_name },
		beforeSend:	function() { },
		success:	function (response) { $(button).replaceWith(response); }
	});					
}

function addFriend(friend, chatId, button)
{
	$.ajax({
		url:		'ajax/addfriend.php',
		data:		{ friend: friend, chatId: chatId },
		beforeSend:	function() { },
		success:	function(response) { $(button).replaceWith(response); }
	});
}

function removeFriend(name)
{
	if (confirm("Do you really want to remove "+name+" from Friends?\n"+name+" won't get any notification but might be sad.")) document.location = "friends.php?remove="+name;
}

function editMustwatchFavourites(type, action, filmId)
{	
	if ($.cookie('profileId') == null) if (confirm('You have to be logged in to make that happen. Log in now?')) document.location = 'login.php';
		else return;
		
	$.ajax({
		url:	'ajax/items.edit.php',
		data:	{ type: type, action: action, filmId: filmId },
		beforeSend:	function() {
			$('li#'+type+'-add, li#'+type+'-remove').fadeTo('fast', 0.5);
			},
		success: function() {
			$('li#'+type+'-add, li#'+type+'-remove').fadeTo('fast', 1);
			switch (action)
			{
				case 'add':
					$('li#'+type+'-remove').show();
					$('li#'+type+'-add').hide();
					break;
				case 'remove':
					$('li#'+type+'-remove').hide();
					$('li#'+type+'-add').show();
					$('li#film'+filmId).remove();
					break;
			}
			}
		});
}


function recommendLoadFriends()
{
	if ($('li#recommend ul').length > 0)
	{
		$('li#recommend ul').toggle();
		return;
	}
	
	$.ajax({
		url:	'ajax/recommend.load.friends.php',
		beforeSend:	function() { $('li#recommend').append( '<ul><li>Loading...</li></ul>' ); },
		success:	function(response) {
			$('li#recommend ul').remove();
			$('li#recommend').append( response );
			}
		});
}

function recommendSend(friend, button)
{
	if ($(button).parent().find('p').length > 0) return;

	$.ajax({
		url:	'ajax/recommend.send.php',
		data:	{ friend: friend, filmId: $('input#filmId').val() },
		beforeSend:	function() { $(button).after('<p>Sending...</p>'); },
		success:	function(response) { $(button).parent().find('p').html( response ); }
		});
}


function deleteChat(chatId, button)
{
	var tr = $(button).parent().parent();

	$.ajax({
		url:		'ajax/deletechat.php',
		data:		{ chatId: chatId },
		beforeSend:	function() { $(tr).find('td').fadeTo(0.5, 'fast'); },
		success:	function(response) { if (response == 'delete') $(tr).remove(); }
	});
}


function editSimilar(id, button)
{
	if ($(button).parent().parent().attr('id') == 'foundTitles')
	{
		$.ajax({
			url:		'ajax/similar.edit.php',
			type:		'POST',
			data:		{ action: 'add', filmId1: $('input#filmId').val(), filmId2: id },
			beforeSend:	function() { $(button).parent().fadeTo('fast', 0.5); },
			success:	function() { 
				$(button).parent().clone().appendTo('ul#similarTitle').find('button').html('Remove').fadeTo('fast', 1);
				$(button).parent().remove();
				}
		});
		$('input#filmTitle').focus().select();

	} else {

		$.ajax({
			url:		'ajax/similar.edit.php',
			type:		'POST',
			data:		{ action: 'remove', filmId1: $('input#filmId').val(), filmId2: id },
			beforeSend:	function() { $(button).parent().fadeTo('fast', 0.5); },
			success:	function() { $(button).parent().remove(); }
		});
	}
}
