var Lib = {
	_allowed_image_types : '.jpg.gif.png.jpeg.',
	
	_create_cookie : function( name, value, days )
    {    
        var expires = "";
        
        if ( days )
        {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toGMTString();
        }
        		
        document.cookie = name + "=" + value + expires + "; path=/" ;
		
        if ( !document.cookie )    
            return false ;
	
        return true ;

    },
	
    _read_cookie : function( name )
    {
        var nameEQ = name + "=";
        var ca = document.cookie.split( ';' );
        for ( var i=0; i < ca.length; i++ )
        {
            var c = ca[i] ;
            while ( c.charAt( 0 ) == ' ' ) 
                c = c.substring( 1, c.length ) ;

            if ( c.indexOf(nameEQ) == 0 ) 
                return c.substring( nameEQ.length, c.length );
        }
        return true;
    },

	_check_user_exists : function(field)
	{
		var value = escape($F(field));
		$('check_button').hide();
		$('loadingUsername').show();
		
		new Ajax.Updater('msg', 'ajax/_check_user_exists', {
						 parameters : {'userName' : value},
						 onSuccess : function(){$('check_button').show();$('loadingUsername').hide();}
						 }
		);
		
	},
	
	_is_enter : function(e)
	{
		  return Lib._get_key(e) == 13 ? true : false;
	},	
	
	_get_key : function(e)
	{
		var characterCode = '';
		if ( e && e.which )
		{           
			e = e;
			characterCode = e.which;
		}
		else 
		{
			e = event;
			characterCode = e.keyCode;
		}
	return characterCode;
	},
	
	_error : function(text, id, stop_hide)
	{
		var name = (typeof id == 'undefined' ? '' : id.name) || '';
		if ( typeof id != 'undefined' && typeof id == 'string' )
		{
			name = id;
			id = $(id);
		}
		
		if ( typeof stop_hide == 'undefined' )
			stop_hide = false;
			
		if ( !$('Error' + name) )
		{
			var div = new Element('div', {'class': 'Error', 'id' : 'Error' + name});
			new Insertion.After((id || 'header'), div);
		}

		$('Error' + name).update(text).show();
			
		if ( typeof _e_t != 'undefined' )
			clearTimeout(_e_t);
			
		if ( typeof _el != 'undefined' )
			$('Success').setStyle({'left' : (_el[0]-200) + 'px', 'top' : _el[1] + 'px', 'position' : 'absolute', 'border' : '1px solid #FF9000'});
		
		if ( stop_hide == false )
			_e_t = setTimeout(function(){$('Error' + name).update('').hide();}, 4000);
	},	
	_success : function(text, id)
	{
		var name = (typeof id == 'undefined' ? '' : id.name) || '';
		if ( typeof id != 'undefined' && typeof id == 'string' )
		{
			name = id;
			id = $(id);
		}
		
		if ( typeof stop_hide == 'undefined' )
			stop_hide = false;
		
		if ( !$('Success' + name) )
		{
			var div = new Element('div', {'class': 'Success', 'id' : 'Success' + name});
			new Insertion.After((id || 'header'), div);
		}
		
		if ( typeof _s_t != 'undefined' )
			clearTimeout(_s_t);
			
		if ( typeof _el != 'undefined' )
			$('Success').setStyle({'left' : (_el[0]-200) + 'px', 'top' : _el[1] + 'px', 'position' : 'absolute', 'border' : '1px solid #008FEC'});
		
		$('Success' + name).update(text).show();
		
		if ( stop_hide == false )
			_s_t = setTimeout(function(){$('Success' + name).update('').hide();}, 4000);		
	},
	
	_scroll_to : function(last_message, form_element)
	{
		if( !last_message || !form_element )
			return false;
		
		var _begin_top = form_element.cumulativeScrollOffset()[1];
		var _duration = 600;
		var _start_time = (new Date()).getTime();
		var _last_top = null;
		var _interval_scroll = '';
		
		_interval_scroll = window.setInterval(function(){			
			var _window_height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
			var _last_msg_height = form_element.cumulativeOffset()[1] + form_element.offsetHeight;			
			var _form_height = last_message.cumulativeOffset()[1] - 100;
	
				if ( _last_msg_height-_form_height < _window_height )
				{
					_form_height -= (_window_height+_form_height)-_last_msg_height;
				}
				if ( _last_msg_height < _window_height+100 )
				{
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}
			var _time = (new Date()).getTime();
			var _scroll = null;
			var _current_top = form_element.cumulativeScrollOffset()[1];
			
			var _p = (_time-_start_time)/_duration;
			
				if ( _p > 1 )	
				{		
					_scroll = _form_height;
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}			
				else
				{
					if ( _p <= 0.5 )
						_fp = (_p * _p) * 2;
					else
					{
						_p -= 1; 
						_fp = (_p * _p) * - 2 + 1;
					}
					_scroll = parseInt((_form_height-_begin_top) * _fp + _begin_top);
				}
				if ( _last_top && _current_top != _last_top && _current_top != 0 )
				{
					window.clearInterval(_interval_scroll);
					_interval_scroll = '';
				}
				else
				{
					window.scrollBy(0, (_scroll-_current_top));
					_last_top = _scroll;
				}
		}, 25);
	return false;
	},
	
	_emo_observe : function(el_c, el)
	{
		Event.observe(el_c, 'click', function(){Lib._show_emo_container(el);});
	},
	_hide_emo_container : function(el)
	{
		$(el).hide();
		$('smiley_container').setStyle({'width' : '100px'});
	},
	_show_emo_container : function(el)
	{
		$('smiley_container').setStyle({'width' : '100%'});
		$(el).show();
	},
	_show_emo_text : function(el, hide)
	{
		emo_id = el.id;
		if ( typeof hide != 'undefined' && hide == true )
			$(el.id + '_tooltip').hide();
		else
			$(el.id + '_tooltip').show();
	},
	_set_smiley : function(form, smile)
	{
		$(form).value += smile + ' ';

		$('smiley').hide();
		$('emo_text').hide();
		
		if ( typeof emo_id != 'undefined' )
			$(emo_id + '_tooltip').hide();
	}
	
}

var Quiz = {
	
	_add_more_questions : function()
	{
		var _total_questions = $$('li.question').length;
		var _next_question = _total_questions + 1;
		var _answers = ['А', 'Б', 'В', 'Г'];
		
		var _question_text = '<li id="question' + _next_question + '" class="question"><label for="question' + _next_question + '">Въпрос ' + _next_question + ':</label><input type="text" name="question[' + _next_question + '][]" id="question' + _next_question + '" value="" style="width: 300px;" maxlength="200" /> <a href="javascript:void(0)" onclick="Quiz._remove_quiz_question(' + _next_question + ')">премахни</a></li><li id="question' + _next_question + 'answers"><label>Отговори:</label><br style="clear: both;" />';
	
		for ( var i = 0; i < _answers.length; i++)
		{	
		  _temp_answer = 'answer[' + _next_question + '][' + _answers[i] + ']';
		  
		  _question_text += '<label for="' + _temp_answer + '">' + _answers[i] + ':</label><input type="text" name="' + _temp_answer + '" id="' + _temp_answer + '" value="" style="width: 300px;" maxlength="200" /> <input type="radio" name="correctAnswer' + _next_question + '" value="' + _answers[i] + '" /> Верент отговор<br style="clear: both;" />';
		}
		
		_question_text += '</li>';
		
	new Insertion.Before('submit', _question_text);
	
	},
	
	_remove_quiz_question : function(questionNumber)
	{
	
		if ( questionNumber > 4 )
		{
			$R(questionNumber, $$('li.question').length + 1, true).each(function(value) {
				$('question' + value).remove();
				$('question' + value + 'answers').remove();
			});
			
		}
		
	},
	
	_toggle_title : function()
	{
	
		$('quizTitleLink').toggle();
		$('quizTitleForm').toggle();

		if( $('quizTitle') && $('quizTitleLink') && $('quizTitleLink').hasChildNodes() == true && $('quizTitleLink').firstChild.nodeType == 3 )
			$('quizTitle').value = $('quizTitleLink').firstChild.nodeValue;
		
	},
	
	_update_title : function()
	{
	
		var quizTitle = this._trim($F('quizTitle'));
		
		if ( quizTitle.length == 0 )
			return this._error('Напишете име на теста');
				
			$('quizTitleLink').update(quizTitle);
			this._toggle_title();
	
	},
	
	_toggle_question : function(questionId)
	{
		
		$$('div.questions' + questionId).each(function(element){element.toggle();});
		$$('div.answers' + questionId).each(function(element){element.toggle();});
		
		$('editQuestion' + questionId).toggle();
		$$('div.editAnswers' + questionId).each(function(element){element.toggle();});
		$('buttons' + questionId).toggle();
		
		if( $('question' + questionId) && $('questionText' + questionId) && $('questionText' + questionId).hasChildNodes() == true && $('questionText' + questionId).firstChild.nodeType == 3 )		
			$('question' + questionId).value = $('questionText' + questionId).firstChild.nodeValue;
			
		var j = 0;
		$$('input.answerClass' + questionId).each(function(element)
		{			
				element.value = $$('span.answerText' + questionId)[j].firstChild.nodeValue;			 
		j++;
		});
		
	},
	
	_update_question : function(questionId)
	{
		
		var questionTitle = this._trim($('question' + questionId).value);
		
		if ( questionTitle.length == 0 )
			return this._error('Напишете заглавието на въпрос номер ' + questionId);
		
		$('questionText' + questionId).update(questionTitle);
		var i = 1;
		$$('input.answerClass' + questionId).each(function(element){$('answerText' + questionId + i).update(element.value); i++;});
		
		var buttons = $('quiz').getInputs('radio', 'correctAnswer' + questionId);
		buttons.each(function(element)
		{ 
			if ( element.checked ) 
			{ 
				_checked_value = element.value;				
			}
			
		});
		
		var buttons2 = $('quiz').getInputs('radio', 'editcorrectAnswer' + questionId);
		buttons2.each(function(element)
		{ 
			if ( !element.checked && element.value == _checked_value )
			{ 
				element.checked = true;
			}
			else if ( element.checked && element.value == _checked_value )
			{}				
			else
				element.checked = false;
			
		});
				
		this._toggle_question(questionId);
		
	},
	
	_toggle_score : function(score)
	{
		
		$('quiz' + score + 'container').toggle();
		$('quiz' + score + 'form').toggle();
		
		if( $('quiz' + score + 'correct') && $('quiz' + score + 'correctText') && $('quiz' + score + 'correctText').hasChildNodes() == true && $('quiz' + score + 'correctText').firstChild.nodeType == 3 )
			$('quiz' + score + 'correct').value = $('quiz' + score + 'correctText').firstChild.nodeValue;
		
	},
	
	_update_score : function(score)
	{
		
		var quizScore = this._trim($F('quiz' + score + 'correct'));
		
		if ( quizScore.length == 0 )
			return this._error('Моля изберете оценка');
				
			$('quiz' + score + 'correctText').update(quizScore);
			this._toggle_score(score);
		
	},
	
	_set_privacy : function(name, el, id)
	{
		
		new Ajax.Request('ajax/_update_privacy', {						 
						 parameters : {'resultId' : id, 'privacy' : name},
						 onSuccess : function()
						 {
							 $$('div#menu_' + id + ' a').each(function(el){$(el).setStyle({fontWeight : 'normal'});});
							 el.setStyle({fontWeight : 'bold'});
						 }
		});
				
	},
	
	_delete_results : function(id)
	{
		if ( !confirm('Да изтрия този резултат?') )
			return;
			
		$('loading').show();
			
		new Ajax.Request('ajax/_delete_results', {
						 parameters : {'resultId' : id},
						 onSuccess : function()
						 {
							$('results_' + id).remove();
							var _current_quizzes = parseInt($('_stat_quiz_taken').firstChild.nodeValue);
							$('_stat_quiz_taken').update(_current_quizzes-1);
							$('_taken_quizzes').update(_current_quizzes-1);
							$('loading').hide();
						 }						 
		});
	},
	
	_taken_quizzes : function(userId, show, hide)
	{
		new Ajax.Updater('quizzes', 'ajax/_taken_quizzes', {
						 parameters : {'userId' : userId},
						 onSuccess : function()
						 {
							$(hide).setStyle({fontWeight : 'normal'});
							$(show).setStyle({fontWeight : 'bold'});
						 }
		});
		
		return false;
		
	},
	
	_next_taken_quiz : function(offset, userId)
	{
		$('quiz_loading').show();

		new Ajax.Updater('quizzes', 'ajax/_taken_quizzes', {
						 parameters : {'userId' : userId, 'position' : offset},
						 onSuccess : function()
						 {
							$('quiz_loading').hide();
						 }						 
		});
		
		return false;
	},
	
	_your_quizzes : function(userId, show, hide)
	{
		new Ajax.Updater('quizzes', 'ajax/_your_quizzes', {
						 parameters : {'userId' : userId},
						 onSuccess : function()
						 {
							$(hide).setStyle({fontWeight : 'normal'});
							$(show).setStyle({fontWeight : 'bold'});
						 }
		});
		
		return false;
		
	},
	
	_next_your_quiz : function(offset, userId)
	{
		$('quiz_loading').show();
		
		new Ajax.Updater('quizzes', 'ajax/_your_quizzes', {
						 parameters : {'userId' : userId, 'position' : offset},
						 onSuccess : function()
						 {
							$('quiz_loading').hide();
						 }
		});
		
		return false;
	},
	
	_delete_quiz : function(quizId)
	{
		if ( !confirm('Да изтрия този тест?') )
			return;
			
		$('loading').show();
		
		new Ajax.Updater('_taken_quizzes', 'ajax/_delete_quiz', {
						 parameters : {'quizId' : quizId},
						 onSuccess : function()
						 {								
							var _taken_quizzes = parseInt($('_taken_quizzes').firstChild.nodeValue);
							$('_stat_quiz_taken').update(_taken_quizzes);
							
							var _your_quizzes = parseInt($('_your_quizzes').firstChild.nodeValue);
							$('_your_quizzes').update(_your_quizzes-1);
							
							$('quiz_' + quizId).remove();
							$('loading').hide();
						 }
		});
	},
	
	_slide_bar : function(pollId, currentPercent)
    {

	var divIdWidth = pollId.split(':');
	$(pollId).show();
			
		if ( this._trim(divIdWidth[1]) == 0 )
			return;
			 
	currentPercent = ((currentPercent/1) + 1) ;	
	var obj = $( pollId ) ;						 
	var calc = Math.round( currentPercent / 100*divIdWidth[1] );
	
	obj.setStyle({width : calc + 'px'});
	
	if ( calc <= 40 )
		obj.style.backgroundColor = '#F5364D';
	else if ( calc <= 80 )
		obj.style.backgroundColor = '#ED7464';
	else if ( calc <= 120 )
		obj.style.backgroundColor = '#EDE1AF';
	else if ( calc <= 160 )
		obj.style.backgroundColor = '#D5DBC4';
	else if ( calc <= 200 )
		obj.style.backgroundColor = '#08A767';

		if ( currentPercent < 100 ) 
		{
			t = setTimeout( 'Quiz._slide_bar("' + pollId + '", ' + currentPercent + ')', 50) ;			
		}
		else
		{
			clearTimeout(t);
			$('procents').show();
		}

    },
	
	_report : function(quizId)
	{
		var reason = document.quizzez.reason.selectedIndex;
		
		if ( reason <= 0 || quizId <= 0 )
			return;
			
		new Ajax.Request('ajax/_report', {
						 parameters : {'quizId' : quizId, 'reason' : reason},
						 onSuccess : function()
						 {
							 document.quizzez.reason.selectedIndex = 0;
							 $('reportResponse').update('Благодаря!').show();
							 setTimeout(function(){$('reportResponse').hide()}, 5000);
						 }
		});
	},
	
	_rate : function(rate, quizId)
	{
		new Ajax.Updater('new_rate', 'ajax/_rate', {
						 parameters : {'quizId' : quizId, 'rate' : rate}
		});
	},
	
	_delete_comment : function(commentId)
	{
		if ( !confirm('Да изтрия този коментар?') )
			return;
		
		$('loading').show();
		
		new Ajax.Request('ajax/_delete_comment', {
						 parameters : {'commentId' : commentId},
						 onComplete : function()
						 {
							$('comment_' + commentId).remove();
							$('loading').hide();
						 }
		});
		
	},
	
	_anonymous_login : function()
	{
		$('login_username', 'anonymous_name', 'login_email', 'anonymous_email', 'login_submit', 'anonymous_submit').invoke('toggle');		
	},
	
	_anonymous_login_proccess : function()
	{
		if ( !$('login_email') || $('login_email').style.display == 'none' )
			return true;
		
		$('loading').show();
		
		var useremail = this._trim($('userEmail').getValue());
		var password = this._trim($('userPassword').getValue());
		var rememberme = ($('userRememberMe').checked ? 1 : 0);
		
		new Ajax.Request('ajax/_login', {
						 parameters : {'userEmail' : useremail, 'userPassword' : password, 'rememberMe' : rememberme},
						 onComplete : function(r)
						 {
							if ( r.responseText != '' )
							{
								$('Error').update(r.responseText).show();
								setTimeout(function(){$('Error').update('').hide();}, 5000);
							}
							else
							{
								$('fill_quiz_form_name', 'fill_quiz_form_email', 'anonymous_submit_href', 'login_submit').invoke('remove');								
								$('anonymous_submit').show();
								
								new Ajax.Updater('headerProfile', 'ajax/_get_user_menu', {
												parameters : {'menu' : 1}
								});
							}
							
							$('loading').hide();
							
						 }
		});
		return false;
	},
	
	_add_more_friends : function()
	{
		var _total_friends = $$('li.friends').length;
		
		if ( _total_friends >= 10 )
		{
			$('Error').update('Максимум 10 приятели').show();
			setTimeout(function(){$('Error').update('').hide();}, 5000);
			return;
		}
		
		var _next_friend = _total_friends + 1;
		
		var _friends_text = '<li class="friends" id="more_friends_' + _next_friend + '"><label for="friendsEmail_' + _next_friend + '">' + _next_friend + '.</label> <input type="text" name="friendsEmail[]" id="friendsEmail_' + _next_friend + '" value="" style="width: 330px;" /> - <a href="javascript:void(0)" onclick="Quiz._remove_more_friends(' + _next_friend + ');">премахни</a></li>';		
				
	new Insertion.Before('submit', _friends_text);
		
	},
	
	_remove_more_friends : function(id)
	{
		if ( id > 1 )
		{		
			$R(id, $$('li.friends').length + 1, true).each(function(value) {
					$('more_friends_' + value).remove();				
			});			
		}
	},
	
	_enable_timer : function()
	{
		var timer = $('quizTimer');
		timer[timer.disabled ? 'enable' : 'disable']();
	},
		
	_trim : function(string)
	{ 	
		return string.replace(/^\s+|\s+$/g, ''); 		
	},
	
	_error : function(string)
	{	
		$('msg').show();
		$('msg_text').update(string);		
	},
	
	_clear_msg : function()
	{	
		$('msg').hide();		
	}
	
}

var Profile = {
	fieldName : '',
	
	_change_profile_image : function()
	{
		//$('profile_image_button').toggle();	
		$('profile_image_form').toggle();
	},
	
	_upload_profile_image : function()
	{
		$('profile_image_form').toggle();
		$('profile_image_loading').toggle();
		document.profile.submit();		
	},
	
	_edit : function(name)
	{	
		$(name + '_edit_button').toggle();
		$(name + '_close_button').toggle();		
		$(name + '_form').toggle();		
	},
	
	_save : function(name)
	{
	
		var string = Quiz._trim($(name).getValue());
				
			new Ajax.Updater(name + '_text', 'ajax/_update_profile', {parameters: {'_profile_section' : name, 'string' : string}});
			this._edit(name);
						
	},
			
	_error : function(string)
	{	
		$('error_msg').show();
		$('msg_text').update(string);		
	},
	
	_clear_msg : function()
	{	
		$('error_msg').hide();		
	},
	
	_profile_image_delete_button : function()
	{
		if ( $('profile_image_delete') )
			$('profile_image_delete').toggle();		
	},
	
	_delete_profile_image : function()
	{
		if ( !confirm('Да изтрия снимката ти?') )
			return;
			
		$('loading').show();
		
		new Ajax.Request('ajax/_delete_profile_image', {
						 				parameters : {'profile' : 1},
										onComplete : function()
										{
											$('profile_image_id').src = 'i/g/noprofileimage.gif';
											$('profile_image_header').src = 'i/g/noprofileimage_thumb_50.gif';
											
											$('loading').hide();
											
											if ( $('profile_image') )
											{
												$('profile_image_delete').hide();
												$('profile_image').stopObserving('mouseover', Profile._profile_image_delete_button);
												$('profile_image').stopObserving('mouseout', Profile._profile_image_delete_button);
											}
											
										}
		});		
	},
	
	_invite : function(id)
	{
		new Ajax.Request('ajax/_invite_friend', {
						 parameters : {'id' : id},
						 onComplete : function()
						 {
							 $('invite_friends_link').remove();
							 $('invite_friends_container').update('Поканата ти е изпратена');
							 
						 }
		});	
	},
	
	_accept_invitation : function(id)
	{
		new Ajax.Request('ajax/_accept_invitation', {
						 parameters : {'id' : id},
						 onComplete : function()
						 {
							$('container_' + id).remove();							 							 
						 }
		});
		
		return false;
	},
	
	_deny_invitation : function(id)
	{
		new Ajax.Request('ajax/_deny_invitation', {
						 parameters : {'id' : id},
						 onComplete : function()
						 {
							 $('container_' + id).remove();							 							 
						 }
		});		
		
		return false;
	},
	
	_remove_friend : function(id)
	{
		new Ajax.Request('ajax/_remove_friend', {
						 parameters : {'id' : id},
						 onComplete : function()
						 {
							 $('container_' + id).remove();							 							 
						 }
		});		
		
		return false;
	}
		
}

var Gallery = {	
	_show_profile_image : function()
	{		
		Gallery._hide();
		var img = $('img');
		img.src = 'i/g/noprofileimage.gif';
		
		$('gloading').show();
		var name = $('profile_image_id').getAttribute('src');
		name = name.replace(/_thumb_100/, '_thumb_600');
		
		$('gallery').show();
		img.src = name;
		img.setStyle({'visibility' : 'hidden'});
		
		img.onload = function(){
			$('gloading').hide();
			
			window.setTimeout(function(){								
						$('gallery').setStyle({
											  width : img.getWidth() + 'px'
						});
					img.setStyle({'visibility' : 'visible'});
			}, 50);
		}
		
		return false;
	},
	
	_upload_gallery_image : function(form)
	{
		var cats = form.getInputs('checkbox', 'catId[]');
		
		var c = 0;
		cats.each(function(el){if ( el.checked ) c++;});
		
		if ( c == 0 )
			return Profile._error('Изберете поне една категория');
		
		$('loading').show();
		document.gallery.submit();
	},
	
	_hide : function()
	{
		var browserWidth = document.documentElement.clientWidth;
		var browserHeight = document.documentElement.clientHeight;
		
		$('hidden').setStyle({'width' : browserWidth + 'px', 'height' : document.documentElement.scrollHeight + 'px'}).show();
	},
	
	_show : function()
	{
		$('hidden').hide();
	},
	
	_close : function()
	{
		$('gallery').hide();	
		Gallery._show();
	},
	
	_delete : function(id)
	{	
		new Ajax.Request('ajax/_delete_gallery', {
						 parameters : {'id' : id}, 
						 onComplete : function()
						 {
							 $('container_' + id).remove();
						 }
		});		
	}
	
}

var Timer = {
	timerID : null,
	timerRunning : false,
	delay : 1000,
	
	InitializeTimer : function()
	{
		Timer.secs = parseInt($('seconds').firstChild.nodeValue);
		Timer.StopTheClock();
		Timer.StartTheTimer();
	},
	
	StopTheClock : function()
	{
		if ( Timer.timerRunning )
			clearTimeout(Timer.timerID);
			
		Timer.timerRunning = false;
	},
	
	StartTheTimer : function()
	{				
		if ( Timer.secs == 0 )
		{
			Timer.StopTheClock();
			var minutes = parseInt($('minutes').firstChild.nodeValue);
			
			if ( minutes == 2 )
				$('minute_text').update('минута');
			else
				$('minute_text').update('минути');
						
			if ( minutes > 0 )
			{		
				Timer.secs = 60;
				$('minutes').update(minutes-1);
				Timer.StartTheTimer();					
			}
			else
				$('timer').update('<div class="Error">Времето ти изтече!</div>');
		}
		else
		{
			self.status = Timer.secs;
			Timer.secs -= 1;
			$('seconds').update(Timer.secs);
			Timer.timerRunning = true;
			Timer.timerID = self.setTimeout('Timer.StartTheTimer()', Timer.delay);
		}
	}

}


/* Inbox */

var Inbox = {
	_friends : [],
	_found_friends : [],
	_stop_submit : false,
	_p : 0,
	_i : 0,
	_disableSounds : 0,
	_gen_inputs : function()
	{
		$('inbox_input').show().focus();
	},
	_get_friends : function(include_me)
	{
		if ( typeof include_me == 'undefined' )
			include_me = 1;	
		else
			include_me = 0;
		
		new Ajax.Request('inbox/_get_friends', {
							parameters : {'me' : include_me},
							onComplete : function(response)
							{
								Inbox._friends = (response.responseText).evalJSON();
							}
			});
	},
	_suggestion : function(el, e)
	{
		var value = (el.value).stripTags();
		Inbox._found_friends = [];
		var ol = new Element('ol',{ 'id' : 'suggestions_list'});
		$('suggestions').update(ol);
		var _t = 0;

			if ( value.length >= 2 )
			{
				for ( var j = 0; j < Inbox._friends.length; j++ )
				{
					if ( ((Inbox._friends[j].username).toLowerCase()).lastIndexOf(value.toLowerCase()) != -1 )
					{
						var userName = Inbox._friends[j].username;
						
						var user = userName;						
						var userId = Inbox._friends[j].userId;
							
						if ( typeof Inbox._found_friends[0] == 'undefined' )
							Inbox._found_friends = [{'userId' : userId, 'user' : user}];												
						
						userName = userName.replace(new RegExp(value, 'gi'), function(found){return '<em style="font-size: 11px !important; background-color: #ECF2F9;">' + found + '</em>'});

						var li = new Element('li', {'id' : 'inbox_user_' + userId});
						var a_href = new Element('a', {'href' : 'javascript:void(0)', 'id' : 'inputuser_' + userId, 'class' : 'inbox_found_href'}).update(userName).observe('click', function(e){Inbox._set_user(e)});
						var input = new Element('input', {'type' : 'hidden', 'name' : 'inboxinputuser_' + userId, 'value' : user});
						
						li.appendChild(a_href);
						li.appendChild(input);
						
						_t += 1;
						
						if ( _t > 5 )
						{
							$('suggestions').setStyle({'height' : '185px', 'overflow' : 'auto'});
							$('suggestions_list').setStyle({'width' : '355px'});
						}
						else
						{
							$('suggestions').setStyle({'height' : 'auto', 'overflow' : 'hidden'});
							$('suggestions_list').setStyle({'width' : 'auto'});
						}
						
						new Insertion.Bottom('suggestions_list', li);						
						$('suggestions', 'suggestions_li').invoke('show');
					}
				}	
			}
			
		if ( Inbox._found_friends.length == 0 )
			$('suggestions', 'suggestions_li').invoke('hide');
		
		if ( Lib._is_enter(e) == true )
		{
			Inbox._stop_submit = true;
			if ( typeof Inbox._found_friends[0] != 'undefined' && value.length >= 2 )
				$('inbox_input').blur();
		}
	},
	_list_set_user : function(id, user, userId)
	{
		this._set_user(id, user, userId);
		
		$('inbox_user_' + userId).hide();
	},
	_set_user : function(e, id, user, userId)
	{
		if ( typeof Inbox._i == 'undefined' )
			Inbox._i = 0;

		if ( typeof userId == 'undefined' && typeof user == 'undefined' )
		{
			var el = Event.element(e).id;
			var _id = el.split('_');
			var userId = _id[1];
			
			Event.stopObserving('inbox_user_' + userId, 'click', function(e){Inbox._set_user(e)});
		}
		else
			var userId = (( typeof userId == 'undefined' && typeof Inbox._found_friends[0] != 'undefined' ) ? Inbox._found_friends[0].userId : userId);
		
		if ( typeof userId == 'undefined' )
			return;
		
		for ( var i = 0; i < Inbox._friends.length; i++ )
		{
			if ( Inbox._friends[i].userId == userId )
			{
				var username = Inbox._friends[i].username;
			}
		}
		
		if ( typeof _from_pic_tags != 'undefined' )
		{
			Inbox._found_friends = [];
			$('suggestions').update('').hide();
			$('suggestions_li').hide();

		return;
		}
		
		$('inbox_input').value = '';		
		$('suggestions').update('').hide();
		$('suggestions_li').hide();
		$('inbox_input').hide();
		
		Inbox._found_friends = [];
					
		var current_users = $$('input.inbox_inputs');
		var stop = false;

		current_users.each(function(el){
						if ( el.value == userId )
						{
							stop = true;
							return false;
						}
									});
		if ( stop == true )
			return;
		
		Inbox._i++;
		var div = new Element('div', {'id' : 'inbox_input_' + Inbox._i, 'style' : 'display: none'});
		var input = new Element('input', {'type' : 'text', 'name' : '_id[]', 'class' : 'inbox_inputs', 'value' : userId});
		div.appendChild(input);
		
		var x = new Element('a', {'href' : 'javascript:void(0)', 'class' : 'input_x', 'id' : 'close_' + Inbox._i}).update('x');
		var span = new Element('span', {'id' : 'span_' + Inbox._i, 'class' : 'inbox_users_span'}).update(username);
		
		new Insertion.Before('inbox_input', span);
		new Insertion.Bottom('span_' + Inbox._i, x);		
		new Insertion.Before('inbox_input', div);
		
		var current = Inbox._i;
			
		Event.observe($('close_' + current), 'click', function(){Inbox._remove_user(current, userId)});
	},
	_remove_user : function(id, userId)
	{
		Event.stopObserving($('close_' + id), 'click', function(){Inbox._remove_user(id, userId )});
		if ( $('span_' + id) )
			$('span_' + id).remove();
		
		if ( $('inbox_input_' + id) )
			$('inbox_input_' + id).remove();
	},
	_check_form : function(form)
	{
		if ( Inbox._stop_submit == true )
		{
			Inbox._stop_submit = false;
			return false;
		}
		
		if ( $$('input.inbox_inputs').length == 0 )
		{
			Lib._error('Напиши до кого е съобщението', 'inbox_sender_container');
			Inbox._gen_inputs();
			return false;
		}
		
		if ( (form.inbox_message.value).blank() )
		{
			Lib._error('Напиши текст на съобщението', 'inbox_text_container');
			form.inbox_message.focus();
			return false;
		}
		
		return true;
	},
	_delete : function(inboxId, isOutbox)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( typeof isOutbox == 'undefined' )
			isOutbox = 0;
			
		$('loading').show();
		new Ajax.Updater('inbox_list', 'inbox/_inbox_delete', {
					parameters : {'inboxId' : inboxId, 'p' : Inbox._p, 'o' : isOutbox},					
					onComplete : function()
					{
						Lib._success('Съобщението е изтрито');
						$('loading').hide();
					}
			});
	return false;
	},
	_reply : function(form, inboxId)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( (form.inbox_reply.value).blank() )
		{
			Lib._error('Напиши текст на съобщението', 'inbox_reply_container');
			form.inbox_reply.focus();
			return false;
		}
			
		$('loading').show();
		form.inbox_reply.disabled = true;
		new Ajax.Updater('reply_container', 'inbox/_inbox_reply', {
					parameters : {'inboxId' : inboxId, 'message' : form.inbox_reply.value, 'attach_url' : form.attach_url.value},
					insertion: Insertion.Bottom,
					onComplete : function()
					{
						form.inbox_reply.value = '';
						form.attach_url.value = '';
						form.inbox_reply.disabled = false;	
						$('attach_preview').hide().update('');
						$('loading').hide();
						total_images = 0;
					}
			});
	return false;
	},
	_change_status : function(el)
	{
		if ( typeof el == 'string' )
			el = $(el);
		
		var status = el.value;
		//var inputs = [];
		
		if ( status == "none" )
			return false;
			
		$('loading').show();
		
		var tr = $$('tr.inbox_tr');
		
		if ( status == "" || status == "all" )
		{
			tr.each(function(el)
				{
					el.getElementsByTagName('input')[0].checked = (status == "all") ?  true : false;
				}
			);
		}
		else
		{		
			tr.each(function(el)
					{
						el.getElementsByTagName('input')[0].checked = el.className.indexOf(status) != -1 ?  true : false;
					}
			);
		}
		Inbox._status_buttons();
		
		if ( status == "inbox_new_msg" || status == "" )
			$('inbox_select_action').selectedIndex = 0;
		
		$('loading').hide();
	},
	_inbox_action : function(action, el, isOutbox, p)
	{
		if ( el.indexOf('inbox_menu_disabled') != -1 )
			return false;
		
		if ( typeof isOutbox == 'undefined' )
			isOutbox = 0;
		
		var tr = $$('tr.inbox_tr');
		var json = [];
		$('loading').show();
		tr.each(function(el)
				{
					var input = el.getElementsByTagName('input')[0];
					if ( input.checked == true )
					{
						json.push(input.value);
						
						if ( action == 'unread' )
							el.removeClassName('inbox_readed_msg').addClassName('inbox_new_msg');
						else if ( action == 'read' )
							el.removeClassName('inbox_new_msg').addClassName('inbox_readed_msg');
						else if ( action == 'delete' )
							el.remove();
					}
				}
			);
		
		if ( json.length == 0 )
		{
			$('loading').hide();
			return false;
		}

		new Ajax.Request('inbox/_inbox_action', {
						 	parameters : {'action' : action, '_id[]' : json, 'p' : p, 'o' : isOutbox},
							onComplete : function(response)
							{
								if ( action == 'delete' )
								{
									$('inbox_list').update(response.responseText);
									//var tr = $$('tr.inbox_tr');									
									//if ( tr.length == 0 )
										//Inbox._incoming(p);
								}
								else
									$('inbox_new_mails').update(response.responseText);
								Inbox._status_buttons();
								$('loading').hide();
							}
						 });
		$('inbox_select_action').selectedIndex = 0;
		return false;
	},
	_incoming : function(p)
	{
		Inbox._p = p;
		$('loading').show();
		new Ajax.Updater('inbox_list', 'inbox/_inbox_incomin', {
						 	evalScripts : true,
						 	parameters : {'p' : p},
							onComplete : function()
							{
								$('loading').hide();
							}
						 });
		return false;
	},
	_outcoming : function(p)
	{
		Inbox._p = p;
		$('loading').show();
		new Ajax.Updater('inbox_list', 'inbox/_inbox_outcomin', {
						 	evalScripts : true,
						 	parameters : {'p' : p},
							onComplete : function()
							{
								$('loading').hide();
							}
						 });
		return false;
	},
	_status_buttons : function()
	{
		var tr = $$('tr.inbox_tr');
		var unread_disabled = true;
  		var read_disabled = true;

		tr.each(function(el)
				{
					var input = el.getElementsByTagName('input')[0];
					if ( input.checked == true )
					{						
						var status = (el.className.indexOf('inbox_new_msg') != -1 ? 'unread' : 'read');
						if ( status == 'unread' )
							read_disabled = false;
						else
							unread_disabled = false;						
					}
				}
			);
		
		var delete_disabled = read_disabled && unread_disabled;
		var span = $('inbox_buttons').getElementsByTagName('a');		
		var loop = [{l : span[0], d : unread_disabled}, {l : span[1], d : read_disabled}, {l : span[2], d : delete_disabled}];
		var loop_length = loop.length;
		for ( var i = 0; i < loop_length; i++ ) 
		{
			if ( loop[i].l )
			  loop[i].l.className = (loop[i].l.className.replace('inbox_menu_disabled', '') + (loop[i].d ? ' inbox_menu_disabled' : ''));			
		}
		
	},
	_attach_toggle_button : function(from, button)
	{
		if ( typeof button == 'string' )
			var button = $(button);
		
		if ( typeof from == 'string' )
			var from = $(from);
		
		if ( !(from.value).blank() )		
			button.removeClassName('inbox_menu_disabled');
		else
			button.addClassName('inbox_menu_disabled');
	},
	_attach_to_mail : function(from, to, a)
	{
		var from = $(from);
		var to = $(to);
		
		if ( typeof a == 'string' )
			a = $(a);
		
		if ( typeof uid == 'undefined' )
			uid = 1;
		
		if ( !(from.value).blank() )
			a.removeClassName('inbox_menu_disabled');
			
		if ( a.className.indexOf('inbox_menu_disabled') != -1 )
			return false;

			var ext = from.value.split('.');
			ext = '.' + ext[ext.length-1].toLowerCase().strip() + '.';
									
			if ( Lib._allowed_image_types.lastIndexOf(ext) == -1 )
				to.value += ' ' + from.value + ' ';
			else
			{
				if ( $('attach_url').value.indexOf(from.value) == -1 )
				{
					if ( typeof total_images == 'undefined' )
						total_images = 1;
					else if ( total_images < 3 )
						total_images += 1;
						
					if ( total_images == 3 )
					{
						General._error('Можеш по 2 снимки да прикачаш', 'inbox_attach_container');
						total_images = 2;
						from.value = '';
						a.addClassName('inbox_menu_disabled');
						return false;
					}
					
					var div = new Element('div', {'class' : 'left image', 'id' : 'container_remove_attach_' + uid, 'style' : 'text-align: center;'});
					var a_href = new Element('a', {'href' : from.value, 'target' : '_blank'});
					
					var src = from.value;
					
					if ( from.value.indexOf('d/inbox/') != -1 )
					{
						var ext = from.value.substr(from.value.lastIndexOf('.')+1, from.value.length);
						src = from.value.replace('.' + ext, '_thumb.' + ext);
					}

					var img = new Element('img', {'src' : src, 'alt' : '', 'border' : 'none', 'style' : 'padding: 5px; width: 80px; height: 60px;'});
					var br = new Element('br');
										
					var a_remove = new Element('a', {'href' : 'javascript:void(0);', 'id' : 'remove_attach_' + uid}).update('премахни');
					
					a_href.appendChild(img);
					div.appendChild(a_href);
					div.appendChild(br);
					div.appendChild(a_remove);					
					
					new Insertion.Bottom('attach_preview', div);
					$('attach_url').value += ' ' + from.value + ' ';
					$('attach_preview').show();
										
					Event.observe('remove_attach_' + uid, 'click', function(e){Inbox._remove_attach(e);});
					uid += 1;
				}
			}
										
			to.focus();
			from.value = '';
			a.addClassName('inbox_menu_disabled');
		
	return false;
	},
	_remove_attach : function(e)
	{	
		var el_id = Event.element(e).id;
		var href = $('container_' + el_id).getElementsByTagName('a')[0].href;
		var base = document.getElementsByTagName('base')[0].href;
		href = href.replace(base, '');
		total_images -= 1;
		
		Event.stopObserving(el_id, 'click', function(e){Inbox._remove_attach(e); return false;});
				
		$('attach_url').value = $('attach_url').value.replace(href, '');
		$('container_' + el_id).remove();
		
	return false;
	},
	_check_for_new_mails : function()
	{
		new Ajax.Updater('inbox_new_mails', 'inbox/_check_for_new_mails', {
						 	parameters : {'check' : 1}
						 });
	},
	_synchronyze : function(inboxId, outbox)
	{
		if ( typeof inboxId == 'undefined' || inboxId <= 0 )
			return;
			
		if ( typeof outbox == 'undefined' )
			outbox = 0;
			
		new PeriodicalExecuter(function(){new Ajax.Request('inbox/_synchronyze',{
						 	parameters : {'inboxId' : inboxId, 'o' : outbox},
							onComplete : function(response)
							{
								if ( response.responseText != '' )
								{
									$('reply_container').update(response.responseText);
									
									if ( Inbox._disableSounds == 0 )
									{
										var so = new SWFObject("swf/plim.swf", "newmsg", "1", "1", "8");
   										so.write("new_msg");
									}
								}
								Inbox._check_for_new_mails();
							}
						 })}, 10);
	},
	_disable_inbox_sounds : function(el)
	{
		var checked = el.checked ? 1 : 0;
		
		new Ajax.Request('inbox/_disable_inbox_sounds', {
				parameters : {'checked' : checked},
				onComplete : function()
				{
					Inbox._disableSounds = checked;	
				}
						 });
	}
}

/* End inbox */

function copy(inElement, id) 
{
	var flashcopier = 'flashcopier';
	
	if ( typeof id == 'undefined' )
		id = inElement.id;
	
	if ( !$('flashcopier') )
	{
		var div = new Element('div', {'id' : 'flashcopier'});
		new Insertion.After('body', div);
	}
	
	if ( $('success_' + id) )
		return;
	
	$(flashcopier).update('');
	if ( window.clipboardData ) 
	{
		window.clipboardData.setData('Text', inElement.value);
	}
	else
	{
		var divinfo = '<embed src="swf/_clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(inElement.value) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		$(flashcopier).update(divinfo);		
	}
	new Insertion.After(id, '<div id="success_' + id + '" class="Success" style="font-size: 11px;">Текста е записан в паметта.</div>');
	setTimeout(function(){$('success_' + id).remove();}, 10000);
}

/* Slider */
if (window.Ferdinand == undefined) Ferdinand = {};
Ferdinand.Slider = Class.create({
	REQUIRED_PROTOTYPE: '1.6.0.3',
	REQUIRED_SCRIPTACULOUS: '1.8.2',
	initialize: function(element, options) {

		this.Requirements();

		element = $( element );
		this.element = element;
		
		
		this.options = options;
		this.options = Object.extend({
				effectDuration: 0.6,
				transitionDuration: 0.6,
				timeout:3500, 
				opacity:null, /*null for transparent png or value from 0 to 1 for css opacity*/
				background:'i/background.png', /*if opacity is set to null, please provide transparent background image */
				loader: 'i/ajax-loader.gif',
				next: 'i/next.png',
				previous: 'i/previous.png',
				type: 'json', /*placeholder for future releases*/
				url:"callback.json",
				titleClass: 'title',
				excerptClass: 'tekst',
				wrapbg: '#000000',
				containerClass: 'ferdinand-slider'
			}, options || {});
			
		//this.PNGFix();	
			
		if (this.options.containerClass!=null && this.options.containerClass!=false && this.options.containerClass!='') {
			this.element.setAttribute('class',this.options.containerClass);	
			this.element.setAttribute('className',this.options.containerClass);	
		}
		this.CreateSubElements();
	},
	PNGFix: function () {
		var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
		if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
			document.getElementsByClassName('ie-fix-opacity').each(function(poElement){
				// if IE5.5+ on win32, then display PNGs with AlphaImageLoader
				var cBGImg = poElement.currentStyle.backgroundImage;
				var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));
						
				poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
				poElement.style.backgroundImage = "none";
			});
		}
	},
	Requirements: function ()
	{
		function convertVersionString(versionString) {
	      var v = versionString.replace(/_.*|\./g, '');
	      v = parseInt(v + '0'.times(4-v.length));
	      return versionString.indexOf('_') > -1 ? v-1 : v;
	    }		
	    if ((typeof Scriptaculous == 'undefined') ||
			(typeof Effect == 'undefined') ||
			(convertVersionString(Scriptaculous.Version) <
			convertVersionString(this.REQUIRED_SCRIPTACULOUS))) {
				throw ("nSticker requires the Scriptaculous JavaScript framework >= " +
				this.REQUIRED_SCRIPTACULOUS);
		}
		
	    if ((typeof Prototype == 'undefined') ||
			(typeof Element == 'undefined') ||
			(typeof Element.Methods == 'undefined') ||
			(convertVersionString(Prototype.Version) <
			convertVersionString(this.REQUIRED_PROTOTYPE))) {
				throw ("nSticker requires the Prototype JavaScript framework >= " +
				this.REQUIRED_PROTOTYPE);
		}	
	},
	CreateSubElements: function ()
	{
		
		this.warpcreate();
		this.imagecreate();
		//this.loadercreate();
		this.navcreate();
		this.loader_active = false;
		this.GetData();
	},
	
	imagecreate: function ()
	{
		this.imageUrl = new Element('a');
		this.image = new Element('img');
		this.image.setStyle({cssFloat: 'none'});
		this.imageUrl.appendChild(this.image);
		this.element.appendChild(this.imageUrl);
	},
	
	warpcreate: function () {
		this.warp = new Element('div', {'class': 'ferdinand-content'});
		
		if (this.options.opacity != null) {
			this.warp.setStyle({
				//background: this.options.wrapbg,
				opacity: this.options.opacity,
				position: 'absolute'
			});
		} else {
			this.warp.setStyle({
				//background: "transparent url("+this.options.background+")",
				position: 'absolute'
			});			
		}
				
		this.element.appendChild(this.warp);
		this.warp.hide();
		
		if (this.options.titleClass != undefined &&
		this.options.titleClass != null) {
			this.title = new Element('a', {
				className: this.options.titleClass
			});
		}
		else 
			this.title = new Element('a');
		this.warp.appendChild(this.title);
		
		if (this.options.excerptClass != undefined &&
		this.options.excerptClass != null) {
			this.excerpt = new Element('p', {
				className: this.options.excerptClass
			});
		}
		else 
			this.excerpt = new Element('p');
		this.warp.appendChild(this.excerpt);
	},
	
	warpremove: function () {
		this.title.remove();
		this.excerpt.remove();
		this.warp.remove();
	},
	
	loadercreate: function () {
		this.loader = new Element('img');
		this.loader.hide();
		this.loader.setAttribute('src',this.options.loader);
		this.element.appendChild(this.loader);
	},
	
	navcreate: function () {
			this.nav = new Element('div');
			this.element.appendChild(this.nav);
			
			this.prevlink = new Element('a', {href: '#', 'class' : 'prev'}).setStyle({
				cssFloat: 'left', 
				height:'35px', 
				width:'58px', 
				display:'block'//, 
				//background:'transparent url('+this.options.previous+') no-repeat'
				}).hide();
				
			this.nextlink = new Element('a', {href: '#', 'class' : 'next'}).setStyle({
				cssFloat: 'right', 
				height:'35px', 
				width:'58px', 
				display:'block'//, 
				//background:'transparent url('+this.options.next+') no-repeat'
				}).hide();
				
			this.nav.appendChild(this.prevlink);
			this.nav.appendChild(this.nextlink);
			
			Event.observe(this.nextlink, 'click', function(event) {
				if (this.loader_active==true) {
					return false;
				}
				if (this.timeoutInPlace)
				{
					clearTimeout(this.timeoutInPlace);
				}
				this.ShowWarp(this.current_key+1);
			}.bind(this));
			Event.observe(this.prevlink, 'click', function(event) {
				if (this.loader_active==true) {
					return false;
				}
				if (this.timeoutInPlace)
				{
					clearTimeout(this.timeoutInPlace);
				}
				this.ShowWarp(this.current_key-1);
			}.bind(this));	
	},
	Next: function () {
		this.Go(this.current_key+1);		
	},
	Prev: function () {
		this.Go(this.current_key-1);		
	},
	Go: function (num) {
		if (this.loader_active==true) {
			return false;
		}
		if (this.timeoutInPlace)
		{
			clearTimeout(this.timeoutInPlace);
		}
		this.ShowWarp(num);		
	},	
	Pause: function () {
		clearTimeout(this.timeoutInPlace);
	},
	SlideCount: function () {
		return this.slide_count;
	},
	CurrentSlide: function () {
		return this.current_key;
	},
	navhide: function () {
		this.prevlink.hide();
		this.nextlink.hide();
	},
	navsetevents: function () {

		var containerLeft = Position.page(this.image)[0];
		var containerTop = Position.page(this.image)[1];
		

		var containerDimensions = this.image.getDimensions();
		var height = containerDimensions.height;
		var width = containerDimensions.width;
		
		Event.observe(document.body, 'mousemove', function(event) {
			
			mouseX = Event.pointerX(event);
			mouseY = Event.pointerY(event);	
			horizontalPosition = mouseX - containerLeft;
			verticalPosition = mouseY - containerTop;
			if(horizontalPosition <0 || verticalPosition <0 || mouseX> (width + containerLeft) || mouseY> (height + containerTop) ){
				this.prevlink.hide();
				this.nextlink.hide();
				
			}else{
				val = this.image.getWidth()/2;
				offset = this.image.viewportOffset();
				val = offset.left + val;			
				if (mouseX>val) {
					if (!this.no_next) {
						this.nextlink.show();
					}
					this.prevlink.hide();
				}
				if (mouseX<val) {
					if (!this.no_prev) {
						this.prevlink.show();
					}
					this.nextlink.hide();
				}		
			}
				
		}.bind(this));
	},
	navposition: function () {
		//img = {};
		//img.w = 650;//this.image.getWidth();
		//img.h = 250;//this.image.getHeight();
		this.nav.setStyle({position:'absolute'});//, width:img.w});
		pos = this.image.positionedOffset();
		this.nav.setStyle({
			zIndex: 2, 
			position:'absolute',
			width:'650px',
			left:pos.left+'px',
			top:pos.top+(250/2-30)+'px'
			});
			
		this.navsetevents();
	},
	
	setLoader: function (status) {
				
		if (status=='on') this.loader_active = true;
		else this.loader_active = false;
						
		if (!this.loader) return false;
		
		return;
		
		if (!this.image.src || this.image.src=='undefined') {
			return false;
		}
		pos = this.image.positionedOffset();

		this.loader.setStyle({
			zIndex: 2, 
			position:'absolute',
			left:'5px',
			top:'5px'
			//left:pos.left + this.image.getWidth() -  this.loader.getWidth() - 4+'px',
			//top:pos.top + this.image.getHeight() -  this.loader.getHeight() - 4+'px'
			});
		
		if (status=='on') this.loader.show();
		else  this.loader.hide();
	},
	GetData: function () {
		this.setLoader('on');
		new Ajax.Request(this.options.url, {
			method:'get',
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(t){
				this.setLoader('off');
				this.items = t.responseText.evalJSON(true);
				this.slide_count = this.items.length;
				this.ShowWarp(0);
			}.bind(this)
		});
	},
	ShowWarp: function (key) {
		this.setLoader('on');
		var itemkey = key+1;
		this.current_key = key;
		var item = this.items[key];
		this.no_next = false;
		this.no_prev = false;
		
		if (key==this.items.length) {
			this.no_next = true;
			this.GetData();
			return;
		}
		if (key==0) {
			this.no_prev = true;
		}
		
		this.tempimageUrl = new Element('a');
		this.tempimage = new Element('img');
		this.tempimage.setAttribute('src', item.image);
		this.tempimageUrl.setAttribute('href', item.url);
				
		if (this.tempimage.complete) {
			this.StartTransition(item, itemkey);
		} else {
			this.tempimage.observe('load', function(){
				 this.StartTransition(item, itemkey);
			}.bind(this));				
		}
	},
	StartTransition: function (item, itemkey) {
				new Effect.BlindUp(this.warp, {
					duration: this.options.effectDuration,
					afterFinish: function(){
							this.warpremove();
							this.warpcreate();
							//this.warp.style.width = this.tempimage.width+'px';
							//this.element.style.height = this.tempimage.height+'px';
							this.tempimage.hide();
							this.navhide();
							new Effect.Fade(this.image, {
								from: 1.0, 
								to: 0.0, 
								duration: 
								this.options.effectDuration,
								afterFinish: function(){
									this.imageUrl.remove();
									this.image = this.tempimage;
									this.imageUrl = this.tempimageUrl;
									this.imageUrl.appendChild(this.image);
									this.element.appendChild(this.imageUrl);									
									this.BeginSlide(item, itemkey);
								}.bind(this)});
						
					}.bind(this)});	
	},
	BeginSlide: function (item, itemkey)
	{
		if (item.url!=null) 
		{
			this.title.setAttribute('href',item.url);
			this.imageUrl.setAttribute('href',item.url);
		}
		if (item.title!=null) this.title.update(item.title)
		if (item.body!=null) this.excerpt.update(item.body);	
		this.setLoader('off');						
		new Effect.Appear(this.image,{ 
						from: 0.0, to: 1.0, 
						duration: this.options.effectDuration,
						afterFinish: function(){	
							this.navposition();
							new Effect.BlindDown(this.warp,{
								duration: this.options.effectDuration, 
								afterFinish: function(){
									if (this.timeoutInPlace)
									{
										clearTimeout(this.timeoutInPlace);
									}
									this.timeoutInPlace = setTimeout(function () { 
												this.ShowWarp(itemkey); 
											}.bind(this), this.options.timeout);
									}.bind(this)
							});								
						}.bind(this)
					});
	}
});

/* End slider */

function addToFavorites(quizId)
{
  new Ajax.Request('_add_to_favorites', {
	  parameters : {'quizId' : quizId},
	  onComplete : function()
	  {				
		  var img = new Element('img', {'src' : 'i/add_favorite.gif'}).setStyle({paddingRight : '4px'});
		  
		  var a = new Element('a', {'href' : 'javascript:void(0);'}).update('Премахни от любими');
		  a.observe('click', function(){removeFromFavorites(quizId);});
		  
		  $('favorites').update(img);
		  new Insertion.Bottom('favorites', a);
	  }
  });
}
function removeFromFavorites(quizId)
{
  new Ajax.Request('_remove_from_favorites', {
	  parameters : {'quizId' : quizId},
	  onComplete : function()
	  {
		  var img = new Element('img', {'src' : 'i/add_favorite.gif'}).setStyle({paddingRight : '4px'});
		  
		  var a = new Element('a', {'href' : 'javascript:void(0);'}).update('Добави в любими');
		  a.observe('click', function(){addToFavorites(quizId);});
		  
		  $('favorites').update(img);
		  new Insertion.Bottom('favorites', a);
	  }
  });
}

window.onload = function()
{
	if ( $('profile_image') )
	{
		$('profile_image').observe('mouseover', Profile._profile_image_delete_button);
		$('profile_image').observe('mouseout', Profile._profile_image_delete_button);
	}
}

window.unload = function()
{
	if ( $('profile_image') )
	{
		$('profile_image').stopObserving('mouseover', Profile._profile_image_delete_button);
		$('profile_image').stopObserving('mouseout', Profile._profile_image_delete_button);
	}
}