function rateFile( mediaId, rate, callback)
{
	var data = { media_id: mediaId, rate: rate};
	_call( '/comment/rate_file', data, {
		message:'Twoja ocena została zarejestrowana.',
		confirmation: 'Czy chcesz temu plikowi dać ocenę ' + rate + '?',
		success: callback
	});
}

function CheckActivation( userId, callback )
{
    var data = { user_id: userId };

    $.getJSON( '/message/recipient_is_active', data,
        function( data, statusText )
        {
            if( data['status'] != 'ok' )
            {
                displayMessage('Wiadomości można wysyłać tylko do aktywowanych użytkowników.');
                $('#send_button').attr('value', 'Wyślij wiadomość »');
                $('#send_button').removeAttr('disabled');

;
            }
            else
                callback();
//                return true;
        }
    );
}

function rateUser( userId, rate, callback)
{
	var data = { user_id: userId, rate: rate};
	_call( '/comment/rate_user', data, {
		message:'Twoja ocena została zarejestrowana.',
		confirmation: 'Czy chcesz użytkownikowi ' + userId + ' dać ocenę ' + rate + '?',
		success: callback
	});
}

function sendMessage( to, subject, message)
{
	var data = { to: to, subject: subject, text: message};
	_call( '/message/send', data, {
		message:'Twója wiadomość została wysłana.'
	});
}

function messageDialog( to, subject, replyTo)
{
	window.location = '/message/dialog?to=' + to;
}

function selectSmiley( to, replyTo)
{
	window.location = '/smiley/select?to=' + to;
}

function sendSmiley( to, smiley, replyTo)
{
	var data = { to: to, smiley: smiley, reply_to: replyTo};
	$.getJSON( '/smiley/send', data, 
			function( data, statusText) 
			{ 
				if( data['status'] != 'ok')
				{
					displayMessage( data['message']);
				}
				else
				{
					$('#comment').val('');
					displayMessage( 'Twój uśmiech został wysłany.');
				}
			}
		);
	return true;
}

function sendMediaComment( mediaId, comment, callback)
{
	if( comment == '')
	{
		displayMessage( 'Nie wprowadziłeś tekstu komentarza.');
		return;
	}
	if( comment.length < 5)
	{
		displayMessage( 'Tekst komentarza musi liczyć conajmniej 5 znaków.');
		return;
	}
	var data = { comment: comment, media_id: mediaId};
	_call( '/comment/file', data, {
		confirmation: 'Czy chcesz dodać komentarz?',
		message: 'Twój komentarz został dodany.',
		success: callback
	});
}

function sendUserComment( userId, comment, callback)
{
	if( comment == '')
	{
		displayMessage( 'Nie wprowadziłeś tekstu komentarza.');
		return;
	}
	if( comment.length < 5)
	{
		displayMessage( 'Tekst komentarza musi liczyć conajmniej 5 znaków.');
		return;
	}
	var data = { comment: comment, user_id: userId};
	_call( '/comment/user', data, {
		confirmation: 'Czy chcesz dodać komentarz?',
		message: 'Twój komentarz został dodany.',
		success: callback
	});
}

function addMediaTag( media_id, callback)
{
	jPrompt( "Podaj nazwę taga:", '', 'Tag', function(tag) { 
		if( !$.trim(tag)) return false;
		var data = { media_id: media_id, tag: tag};
		_call( '/tags/media_add', data, {
			message: 'Tag <b>' + strip_tags(tag, '') + '</b> został dodany.',
			success: function() { $('#media_tags').load( '/tags/media', data);}
		});
	});
	return false;
}

function removeMediaTag( media_id, tag, callback)
{
	var data = { media_id: media_id, tag: tag};
	_call( '/tags/media_remove', data, {
		confirmation: 'Czy jesteś pewien, że chcesz usunąć tag ' + tag + '?',
		message: 'Tag <b>' + strip_tags(tag, '') + '</b> został usunięty.',
		success:  function() { $('#media_tags').load( '/tags/media', data); if( typeof callback == 'function') { callback();} }
	});
}

function addUserTag( user_id, callback)
{
	jPrompt( "Podaj nazwę taga:", '', 'Tag', function(tag) { 
		if( !$.trim(tag)) return false;
		var data = { user: user_id, tag: tag};
		_call(  '/tags/user_add', data, {
			message: 'Tag <b>' + strip_tags(tag, '') + '</b> został dodany.',
			success: function() { $('#user_tags').load( '/tags/reload', { id: user_id, type: 'user'});}
		});
	});
	
	return false;
}


function removeUserTag( userId, tag)
{
	var data = { user: userId, tag: tag};
	_call('/tags/user_remove', data, {
		confirmation: 'Czy jesteś pewien, że chcesz usunąć tag ' + tag + '?',
		message: 'Tag <b>' + strip_tags(tag, '') + '</b> został usunięty.',
		success:  function() { $('#user_tags').load( '/tags/reload', { id: userId, type: 'user'}); }
	});
	
	return false;
}


function displayMessage( message)
{
	$('#system_message').find('.ui-dialog-content').html( message);
	$('#system_message').show();
//	window.setTimeout( function() { $('#system_message:visible').fadeOut('slow');}, 3000);
}


function closeMessage()
{
	$('#system_message:visible').fadeOut('fast');
}

function loginCheck()
{
	if( $.trim( $('#top_login').val()) == '' || $.trim( $('#top_pass').val()) == '')
	{
		displayMessage( 'Musisz podać nazwę użytkownika i hasło.');
		return false;
	}
	return true;
}

function loginDialogCheck()
{
	if( $.trim( $('#dlogin').val()) == '' || $.trim( $('#dpass').val()) == '')
	{
		displayMessage( 'Musisz podać nazwę użytkownika i hasło.');
		return false;
	}
	return true;
}

function addToFriends( user_id, callback)
{
	var data = {user_id: user_id};
	_call( '/contacts/add_friend', data, {
		confirmation: 'Czy na pewno chcesz dodać użytkownika do obserwowanych?',
		message: 'Od teraz użytkownik <b>' + user_id + '</b> jest przez Ciebie obserwowany.',
		success: callback
	});
}

function addToFoes( user_id, callback)
{
	_call( '/contacts/add_foe', {user_id: user_id}, {
		confirmation: 'Czy na pewno chcesz zablokować użytkownika?',
		message: 'Użytkownik <b>' + user_id + '</b> jest zablokowany.',
		success: callback
	});
}

function addToLocker(media_id, media_type, callback)
{
	_call( '/locker/add', {media_id: media_id, media_type:media_type}, {
		message: 'Pomyślnie dodano użytkownika lub plik do schowka',
		success: callback
	});
}

function removeFromLocker(media_id, callback)
{
	_call( '/locker/remove', {media_id: media_id}, {
		confirmation: 'Czy jesteś pewien, że chcesz usunąć ten element ze schowka?',
		message: 'Element został usunięty ze schowka.',
		success: callback
	});
}

function _bindTooltip( sourceId, contentId, position)
{
	position = typeof(position) != 'undefined' ? position : 'rightStatic';
	$( '#' + sourceId).ezpz_tooltip( {contentId: contentId, contentPosition: position,
		showContent: function(content) {
			content.fadeIn( 'slow');
		},
		hideContent: function(content) {
	        $("#" + sourceId + ", #" + contentId)
	        .mouseover(function(){
	        	content.active = true;
	        	content.fadeIn( 'slow');
	        })
	        .mouseout(function(){
	        	content.active = false;
	        	content.timer = window.setTimeout( function() { 
		        		if( !content.active)
		        		{
		        			content.fadeOut('slow');
		        		}
		        	}, 1000);
	        });
		}
	});
}

function bindTooltip( sourceId, contentId, position)
{
	$('body').append( $('#' + contentId));
    var distance = 10;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    var beingShown = false;
    var shown = false;
    var trigger = $('#' + sourceId);
    var info = $('#' + contentId).css('opacity', 0).css( 'position', 'absolute').css( 'z-index', '9999');
    $([trigger.get(0), info.get(0)]).mouseover(function () {
    	var offset = trigger.offset();
    	var offsetParent = (getScreenDimension().width - $('body').width()) / 2;
        if( hideDelayTimer) clearTimeout( hideDelayTimer);
        if( beingShown || shown) 
        {
            // don't trigger the animation again
            return;
        } 
        else 
        {
            // reset position of info box
            beingShown = true;
            info.css({
                top: offset.top + trigger.height(),
                left: offset.left + trigger.outerWidth() ,
                display: 'block'
            }).animate({
                top: '-=' + distance + 'px',
                opacity: 1
            }, time, 'swing', function() {
                beingShown = false;
                shown = true;
            });
        }
        return false;
    }).mouseout(function () {
        if (hideDelayTimer) clearTimeout(hideDelayTimer);
        hideDelayTimer = setTimeout(function () {
            hideDelayTimer = null;
            info.animate({
                top: '-=' + distance + 'px',
                opacity: 0
            }, time, 'swing', function () {
                shown = false;
                info.css('display', 'none');
            });

        }, hideDelay);

        return false;
    });
}

function readMessage( message)
{
	$('#message_read').load( '/message/read/' + message);
}

function setMainPhoto( photo_id, callback, type)
{
	if( typeof type == 'undefined')
	{
		type = 'photo';
	}
	
	var data = { photo_id: photo_id};
	_call( '/user/main_photo', data, {
		confirmation:'Czy na pewno chcesz ustawić ' + (type == 'photo' ? 'to zdjęcie' : 'ten film') + ' jako miniaturę?',
		message: (type == 'photo' ? 'Zdjęcie' : 'Film') + ' jest teraz twoja miniaturą.',
		success: callback
	});
}

function deleteMedia( media_id, parentSelector, caller)
{
	if( !confirm('Czy na pewno chcesz usunąć ten plik?'))
	{
		return false;
	}
	var data = { media_id: media_id};
	$.getJSON( '/gallery/remove', data, 
		function( data, statusText) 
		{ 
			if( data['status'] != 'ok')
			{
				displayMessage( data['message']);
			}
			else
			{
				displayMessage( 'Obraz został usunięty.');
				if( parentSelector != null && caller != null)
				{
					$( caller).parents(parentSelector).remove();
				}
			}
		}
	);	
}


function removeMessage( box, messageId, subject, callback, smiley)
{
	_call( '/message/remove', {box: box, id: messageId}, {
		confirmation:'Czy na pewno chcesz usunąć ' + (smiley ? 'uśmiech' : 'wiadomość') + ' ' + subject + '?',
		message: 'Wiadomość została usunięta.',
		success: callback
	});
}

function removeMessages( box, ids, callback, smiley)
{
	_call( '/message/remove', {box: box, smiley: smiley, ids: ids.join(',')}, {
		confirmation:'Czy na pewno chcesz usunąć wybrane ' + (smiley ? 'uśmiechy' : 'wiadomości') + ' ?',
		message: (smiley ? 'Uśmiechy' : 'Wiadomości') + ' zostały usunięte.',
		success: callback
	});
}


function deleteSearchPreset( presetId, callback)
{
	_call( '/search/delete_preset', {id: presetId}, {
		confirmation:'Czy na pewno chcesz usunąć zapisane kryteria?',
		message: 'Kryteria zostały usunięte.',
		success: callback
	});
}

function checkUpload( logged)
{
	if( !logged)
	{
		displayMessage( 'Dodawanie plików jest możliwe po <a href="/login.html"><b>zalogowaniu się</b></a>. Jeśli nie posiadasz jeszcze konta <a href="/register"><b>zarejestruj się<b/></a>.');
		return false;
	}
	return true;
}

function saveQuery()
{
	jPrompt( "Podaj nazwę dla zestawu wyników::", '', 'Nazwa zestawu', function( name) { 
		if( !$.trim(name)) return false;
		$('#preset').val( name);
		$('#search_form').ajaxSubmit( {
			url:'/search/save',
			dataType: 'json',
			success:
				function( data, statusText) 
				{ 
					if( data['status'] == 'ok')
					{
						displayMessage( 'Zestaw został zapisany.');
						$('#search_presets').append( name);
					}
					else
					{
						displayMessage( data['message']);
					}
				}
		});
	});
	return false;
}

function violationDialog( $mediaId)
{
	window.location = '/message/violation';
}

function violationRegister( message)
{
	var data = { text: message};
	$.getJSON( '/media/violation', data, 
			function( data, statusText) 
			{ 
				if( data['status'] != 'ok')
				{
					displayMessage( data['message']);
				}
				else
				{
					$('#comment').val('');
					displayMessage( 'Twója zgłoszenie zostało zarejestrowane.');
				}
			}
		);
	return true;
	
}

function stopEventBubble()
{
	var e = window.event;
	if( e)
	{
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
}


function login()
{
//	$('#login_box').effect("pulsate", { times:3 }, 2000);
	loadPage( '/user/login_dialog');
}

function removeFOF( userId, callback)
{
	var data = { user_id: userId};
	_call( '/contacts/remove', data, {
		confirmation: 'Czy jesteś pewien, że chcesz usunąć użytkownika "' + userId + '" z listy?',
		message: 'Użytkownik <b>' + userId + '</b> został usunięty z listy.',
		success: callback
	});
}

function _call( url, data, options)
{
	if( options && options['confirmation'])
	{
		if( !window.confirm( options['confirmation']))
		{
			return false;
		}
	}
	var result = false;
	$('#ajax_indicator').show();
	$.getJSON( url, data, 
			function( data, statusText) 
			{
				$('#ajax_indicator').hide();
				if( data['status'] == 'ok')
				{
					var message = 'Operacja wykonana poprawnie.';
					if( options && options['message'])
					{
						message = options['message'];
					}
					displayMessage( message);
					if( options && options['success'])
					{
						if( options['success'] == 'reload')
                                                {
                                                    window.location.reload();
                                                }
						else
                                                {
                                                    options['success']();
                                                }
					}
					result = true;
				}
				else
				{
					displayMessage( data['message']);
					if( options && options['error'])
					{
						options['error']();
					}
					result = false;
				}
			}
		);
	return result;
	
}

function addFavourite( id, callback)
{
	return _call( '/favourite/add', { id: id}, {
		confirmation: 'Czy chcesz dodać plik do ulubionych?',
		message: 'Plik został dodany do ulubionych',
		success: callback
	});
}

function removeFavourite( id, callback)
{
	return _call( '/favourite/remove', { id: id}, {
		confirmation: 'Czy chcesz usunąć plik z ulubionych?',
		message: 'Plik został usunięty z twoich ulubionych.',
		success: callback
	});
}


function mediaEdit( id)
{
	window.open('/media/edit/?media_id=' + id,'media_edit','width=350,height=400,scrollbars=yes');
	return false;
}


function mediaRemove( id, callback)
{
	var data = { media_id: id};
	_call( '/media/remove', data, {
		confirmation: 'Czy na pewno chcesz usunąć plik ' + id + '?',
		message: 'Plik został usunięty',
		success: callback
	});
}

function mediaHide( id, callback)
{
	var data = { media_id: id, hidden: true};
	_call( '/media/mark_private', data, {
		confirmation: 'Czy na pewno chcesz ukryć plik ' + id + '?',
		message: 'Plik został ukryty',
		success: callback
	});
}

function mediaShow( id, callback)
{
	var data = { media_id: id, hidden: false};
	_call( '/media/mark_private', data, {
		confirmation: 'Czy na pewno chcesz upublicznić plik ' + id + '?',
		message: 'Plik został upubliczniony',
		success: callback
	});
}

function removeUser( userId)
{
	_call( '/user/remove', {user_id:userId}, {
		confirmation: 'Czy na pewno chcesz usunąć konto?',
		message: 'Konto zostało usunięte.',
		success: reload
	});
	return true;
}


function removeComment( id, type, callback)
{
	var data = { id: id, type: type};
	_call( '/comment/remove_comment', data, {
		confirmation: 'Czy na pewno chcesz usunąć komenarz?',
		message:  'Komentarz został usunięty.',
		success: callback
	});
}

function FilesCarousel( url, data, containerSelector, total, limit, prevSelector, nextSelector)
{
	this.first = 0;
	this.last = limit - 1;
	this.data = data;
	this.count = total;
	this.container = $(containerSelector);
	this.limit =limit;
	this.data = data;
	this.url = url;
	var carousel = this;
	this.prevSelector = prevSelector;
	this.nextSelector = nextSelector;
	$(prevSelector).bind( 'click', function() { carousel.previous();});
	$(nextSelector).bind( 'click', function() { carousel.next();});
	this.load();
}

FilesCarousel.prototype.updateActions = function()
{
	if( this.count <= this.limit) 
	{
		$(this.prevSelector).hide();
		$(this.nextSelector).hide();
	}
	else
	{
		if( this.first == 0) $(this.prevSelector).hide();
		else $(this.prevSelector).show();
		if( this.first + this.limit >= this.count) $(this.nextSelector).hide();
		else $(this.nextSelector).show();
	}
};

FilesCarousel.prototype.load = function()
{
	this.container.html( '<img src="/images/ajax-loader.gif"/>');
	var data = new Array();
	data = this.data;
	data['first'] = this.first;
	data['last'] = this.last;
	this.container.load( this.url, data);
	this.updateActions();
};

FilesCarousel.prototype.previous = function()
{
	var first = Math.max( 0, this.first - this.limit);
	if( first == this.first) return;
	this.first = first;
	this.last = Math.min( this.first + this.limit - 1, this.count - 1);
	this.load();
};

FilesCarousel.prototype.next = function ()
{
	var first = Math.min( this.first + this.limit, Math.floor((this.count - 1) / this.limit) * this.limit);
	if( first == this.first) return;
	this.first = first;
	this.last = Math.min( this.first + this.limit - 1, this.count - 1);
	this.load();
};


function embedPlayer( thePlaceholder, thePlayerId, theFile, theImage, width, height)
{
	var playerWidth = typeof width == 'undefined' ? 580 : width;
	var playerHeight = typeof height == 'undefined' ? 465: height;
	var flashvars = {
		file:theFile, 
		image:theImage,
		streamer: '/xmoov.php',
		skin: '/swf/skins/snel/snel.swf'
	};
	var params = {
		allowfullscreen:"true", 
		allowscriptaccess:"always",
		wmode: 'opaque'
	};
	var attributes = {
		id:thePlayerId, 
		name:thePlayerId
	};
	swfobject.embedSWF("/swf/player-licensed-viral.swf", thePlaceholder, playerWidth, playerHeight, "9.0.115", false, flashvars, params, attributes);
}

function reload()
{
	var loc = window.location;
	window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
}

function loadPage( page)
{
	window.location = page;
}

function getScreenDimension() 
{
    var dimensions = {width: 0, height: 0};
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
    return dimensions;
}


/*
author: Rob Eberhardt
desc: fix MinWidth for IE6 & IE7
params: none
returns: nothing
notes: cannot yet fix childless elements like INPUT or SELECT
history:
   2006-11-20 revised for standards-mode compatibility
   2006-11-17 first version
*/
function fixMinWidthForIE(){
	
	if (!window.all)
		return;
   try{
      if(!document.body.currentStyle){return} //IE only
   }catch(e){return}
   var elems=document.getElementsByTagName("*");
   
   
   for(e=0; e<elems.length; e++){
      var eCurStyle = elems[e].currentStyle;
      var l_minWidth = (eCurStyle.minWidth) ? eCurStyle.minWidth : eCurStyle.getAttribute("min-width"); //IE7 : IE6
      if(l_minWidth && l_minWidth != 'auto'){
         var shim = document.createElement("DIV");
         shim.style.cssText = 'margin:0 !important; padding:0 !important; border:0 !important; line-height:0 !important; height:0 !important; BACKGROUND:RED;';
         shim.style.width = l_minWidth;
         
         shim.appendChild(document.createTextNode());
         
         if(elems[e].canHaveChildren){
            elems[e].appendChild(shim);
         }else{
            //??
         }
      }
   }
}





function strip_tags (str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'

    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';

    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }

    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}
