/* $(function(){ */

// tooltip
	$(document.body).delegate('.uiTooltip', 'hover', function(e){
		var $this = $(this),
				$tooltip = $this.find('.uiTooltipWrap');
		
		if( $tooltip.hasClass('hidden') ){
			$tooltip.removeClass('hidden');
		} else {
			$tooltip.addClass('hidden');			
		}
	});

// cancel & accept user
	$(document.body).delegate('.userCancel, .userAccept', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				url = $this.attr('data-url'),
				id_user = $this.attr('data-id-user');
				
		$.ajax({
			url: url,
			type: 'POST',
			data: ({ id_user : id_user }),
			dataType: 'json',
			beforeSend: function(){
				$this.text('Czekaj...').attr('disabled', true);
			},
			success: function(data){
				if( data.status == 1 ){
				
					if( $this.parents('ul').find('li').length <= 1 ){
						$('#content').load(window.location.href + ' #content > *');
					} else {
						$this.parents('li:eq(0)').slideUp('fast', function(){ $(this).remove(); });
					}

				} else {
					alert('Wystąpił błąd. '+ data);
				}
			},
			error: function(err){
				alert('Wystąpił nieoczekiwany błąd ' + err +'.\n Prosimy spróbować później.');
			},
			complete: function(){
				$this.attr('disabled', false);
			}
		});			
	});

// follow & unfollow
	$(document.body).delegate('.btn-follow-big, .btn-follow-small', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				url = '',
				id_user = $this.attr('data-id-user'),
				title = '',
				currentClass = $this.attr('class').split(' ')[1],
				newClass = '';

		
		if( $this.hasClass('doFollow') ){
			url = '/obserwuj-uzytkownika/';
			title = 'Nie obserwuj';
			newClass = 'doUnfollow';
		} else if( $this.hasClass('doUnfollow') ){
			url = '/nie-obserwuj-uzytkownika/';
			title = 'Obserwuj';
			newClass = 'doFollow';			
		}
		
		$.ajax({
			url: url,
			type: 'POST',
			data: ({ id_user : id_user }),
			dataType: 'json',
			beforeSend: function(){
				$this.text('Czekaj...').attr('disabled', true);
			},
			success: function(data){
				if( data.status == 1 ){
					$this.text(title).removeClass(currentClass).addClass(newClass);
				} else if( data.status == 0 ){
					$this.text('Prośba wysłana').attr('class','').addClass('requestSend');
				} else {
					alert('Wystąpił błąd. ' + data);
				}
			},
			error: function(err){
				alert('Wystąpił nieoczekiwany błąd ' + err + '.\n Prosimy spróbować później.');
			},
			complete: function(){
				$this.attr('disabled', false);
			}
		});
		
	});

// check login availability
	$('input#userName').live('blur', function(e){
		var $this = $(this),
				url = $this.attr('data-url'),
				username = $this.val();
		
		$.ajax({
			cache: false,
			url: url,
			data: ({ key:username }),
			type: 'POST',	
			dataType: 'json',
			beforeSend: function(){
				$this.attr('disabled', true);
			},
			success: function(data){
				$this.siblings('span').remove();
				
				if( data.status == 'err' ){
					$this.parent().append('<span class="invalid">'+ data.message +'</span>');
				} else if( data.status == 'ok' ){
					$this.parent().append('<span class="valid">'+ data.message +'</span>');
				}
			},
			error: function(error){
				alert('Wystąpił nieoczekiwany błąd ' + error +'.\n Prosimy spróbować później.');
			},
			complete: function(){
				$this.attr('disabled', false);
			}		
		});			
			
	});

// show user info @ userThumbList
	$('.userThumbList').live('mouseover mouseout', function(e){
		var $this = $(this),
				$infoBox = $this.find('div.userInfoBox'),
				infoboxWidth = $infoBox.width();
		
		$this.find('a').attr('title', '');
		
		if( $infoBox.hasClass('hidden') ){
			$infoBox.removeClass('hidden');
			$infoBox.css({ 'margin-left' : -((infoboxWidth/2)+12) })
		} else {
			$infoBox.addClass('hidden');
		}
		
	});

// show infobox
	var timer;
	$(document.body).delegate('.voteWrap .notAllowVote', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$infobox = $('#infobox'),
				x = e.pageX,
				y = e.pageY,
				point = $this.attr('data-point');
		
		if( $infobox.is(':hidden') ){
			$infobox.fadeIn('fast');
		} else {
			window.clearTimeout(timer);
		}
		
		$infobox.find('p').html('Aby głosować musisz zdobyć jeszcze' + ' ' +point+' punktów. <a href="http://www.alepytanie.pl/AlePytanie/Co-zrobic--by-moc-oddawac-glosy-na-pytania-i-odpowiedzi-_129868,0,0.html">Sprawdź jak zdobyć punkty</a>.');
		$infobox.css({
			'top' : y+16,
			'left' : x-16
		});
		
		timer = window.setTimeout(hideInfobox, 5000);
	});
	
	function hideInfobox(){
		var $infobox = $('#infobox');
		
		if( $infobox.is(':visible') ){
			$infobox.fadeOut('fast');
		}		
	
	}

// plceholder	support
	$.support.placeholder = false;
	test = document.createElement('input');
	if('placeholder' in test) $.support.placeholder = true;
	
	if(!$.support.placeholder) { 
	
		$('textarea[placeholder], input[placeholder]')
		.each(function(){
			var $this = $(this);
					
			if( $this.val() == '' ){
				var placeholderText = $this.attr('placeholder');			
				$this.val(placeholderText).addClass('hasPlaceholder');
			}		
			
		})
		.live('focusin focusout', function(e){
			var $this = $(this);
				
			if( e.type === 'focusin' ){
				if( $this.val() == $this.attr('placeholder') ){
					$this.val('').removeClass('hasPlaceholder');
				}			
			} else {
				if( $this.val() == '' || $this.val() == $this.attr('placeholder') ){
					$this.val( $this.attr('placeholder') ).addClass('hasPlaceholder');
				}			
			}
			
		});
		
		$('form').submit(function () {
			$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
		});
	}
	
// show stats details
	$(document.body).delegate('#showStats a', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$stats = $('#statsList');
		
		if( $stats.hasClass('hidden') ){
			$stats.stop().slideDown('fast').removeClass('hidden');
		} else {
			$stats.stop().slideUp('fast').addClass('hidden');
		}
	});

// show/hide attachments when answer exist - direct question
	$(document.body).delegate('.showAttachments', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$list = $this.parent().next('ul');
		
		if( $list.hasClass('hidden') ){
			$list.removeClass('hidden');
			$this.addClass('hideAttachments').removeClass('showAttachments').text('X');
		} else {
			$list.addClass('hidden');		
			$this.removeClass('hideAttachments').addClass('showAttachments');
		}
	});

// remove direct question
	$(document.body).delegate('.removeDirectQuestion', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$questionWrap = $this.parents('li:eq(0)'),
				q = confirm('Czy na pewno chcesz usunąć to pytanie?'),
				url = $this.attr('href');
		
		if(q){
			$.ajax({
				url: url,
				type: 'POST',	
				beforeSend: function(){
					$this.text('Usuwam...').attr('class','');
				},
				success: function(){
					$questionWrap.slideUp('fast', function(){
						 $questionWrap.remove();
					});				
				},
				error: function(error){
					alert('Wystąpił nieoczekiwany błąd' + error)
				}		
			});			
		}
	});

// resizable textarea
	resizeTextarea = {
		resize: function(ta){
			var $this = ta,
					lines = $this.val().split('\n').length,
					textLine = $this.val().split('\n'),
					lineHeight = parseInt( $this.css('lineHeight') ),
					thisWidth = parseInt( $this.width() ),
					cols = Math.floor( $this.width()/( parseInt($this.css('fontSize')) / 2 ) ) - 4;

			for( i=0; i<textLine.length; i++ ){
				if( textLine[i].length >= cols ){
					lines += Math.floor( textLine[i].length / cols );					
				}
			}
			$this.css('height', lineHeight*lines);
		}
	};
	
	$(document.body).delegate('textarea.resizable', 'keyup', function(e){ 
		resizeTextarea.resize($(e.target)) 
	});
	
	var $textarea = $('textarea.resizable');
	if( $textarea.length != 0 ){
		resizeTextarea.resize( $('textarea.resizable') );	
	}
	
	
// send answers	
	$('.contentAnswerWrap').delegate('button', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$textarea = $this.siblings('div.textareaWrap').find('textarea'),
				$target = $this.parents('li:eq(0)').find('h2'),
				url = $this.attr('data-url'),
				label = $this.attr('title'),
				$formWrap = $this.parents('div.contentAnswerWrap:eq(0)');
		
		if( url != '' ){
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'json',
				data: ({ content : $textarea.val() }),
				beforeSend: function(){
					$this.text('Wysyłam...').attr('disabled','disabled'); 
				},
				success: function(data){
					error = data['error'];
					comment = data['data'];	
					
					if( $textarea.parent().find('span.error').length != 0 ){
						$textarea.parent().find('span.error').remove();							
					}							
					
					if( error == ''){
						//$target.after(comment);
						//$textarea.val('');
						window.location.reload();					
					} else {
						$textarea.parent().append(error);
					}						
					
					$this.text(label).attr('disabled','');
				},
				error: function(error){
					alert('Wystąpił nieoczekiwany błąd. '+ error);
				}
			});
		} else {
			alert('Wystąpił nieoczekiwany błąd: Url = ' + url);
		}
	});
	
// Drop'n'down menu
	$(document.body).delegate('.subnaviTrigger > a', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				$subNav = $this.siblings('ul'),
				$openMenus  = $('.subnaviTrigger');
			
		if( $subNav.hasClass('hidden') ){
			$openMenus.removeClass('active').find('ul').addClass('hidden');
			$subNav.removeClass('hidden');
			$this.parent().addClass('active');
		} else {
			$subNav.addClass('hidden');		
			$this.parent().removeClass('active');			
		}
	});
	
		
// Set email notify by dfault
	if( $('#notify').length != 0 ){
		$('#notify').attr('checked','checked');
	}

// show comment list
	$(document.body).delegate('.addComment', 'click', function(e){
		e.preventDefault();
		e.stopPropagation();
		
		var $this = $(e.target),
				url = $this.attr('data-url'),
				$wrap = $this.parents('li:eq(0)');
		
		if( url != '' && !$this.hasClass('active') ){
			$.ajax({
				url: url,
				beforeSend: showSpinner($this),
				success: function(data){
					$this.addClass('active');
					$wrap.append(data);
					hideSpinner($this);
				}
			});	
		}
	});
	
// send comment
	$(document.body).delegate('.sendComment', 'click', function(e){
		var $this = $(e.target),
				url = $this.attr('data-url'),
				$textarea = $this.siblings('.textareaWrap').find('textarea'),
				$list = $this.parents('.commentsList:eq(0)').find('ul'),
				error, 
				comment;
		
			$.ajax({
				url: url,
				type: 'POST',
				data: ({ content : $textarea.val() }),
				dataType: 'json',
				beforeSend: function(){ 
					$this.text('Wysyłam...').attr('disabled','disabled'); 
					
				},
				success: function(data){
					error = data['error'];
					comment = data['data'];
					
					if( $textarea.parent().find('span.error').length != 0 ){
						$textarea.parent().find('span.error').remove();							
					}
					if( error == ''){
						$list.append(comment);
						$textarea.val('');					
					} else {
						$textarea.parent().append(error);
					}
					 
					$this.text('Skomentuj').attr('disabled','');
				}
			});			

	});		

// lightbox
	$('.lightbox').lightBox({
		overlayBgColor: '#000',
		overlayOpacity: 0.6,
		imageLoading: '/design/img/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: '/design/img/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '/design/img/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/design/img/lightbox/lightbox-btn-next.gif',
		containerResizeSpeed: 350,
		txtImage: 'Zdjęcie',
		txtOf: 'z'	
	});
	
// block fb login button and show spinner
	$('#fbLoginBtn').live('click', function(e){
		var $this = $(this);
		
		showSpinner($this);
		$this.next('small').remove();
		
	});

// hide "share with" when addAnonymously is checked
	$(document.body).delegate('#addAnonymously', 'click', function(e){
		var $shareWith = ( $('#sharewithfbCheckbox').length == 1 ) ? $('#sharewithfbCheckbox') : false,
				$this = $(this);
		
		if( $shareWith != false ){
			if( $this.attr('checked') == true ){
				$shareWith.attr('checked', false).attr('disabled', true);
			} else {
				$shareWith.attr('disabled', false).attr('checked', true);
			}
		}
	});

// show login & register popup
	var submitAction = '';
	var submitLink = '';
	
	$(document.body).delegate('.showRegister, .showLogin', 'click', function(e){
		e.preventDefault();
	
		var $this = $(this),
				url = $this.attr('data-login-url');
				
				submitAction = ( typeof($this.attr('data-action')) !== 'undefined' ) ? $this.attr('data-action') : '';
				submitLink = ( typeof($this.attr('data-link')) !== 'undefined' ) ? $this.attr('data-link') : '';		

		$.ajax({
			url: url,
			beforeSend: function(){
				$('#uiPopup').html('<h2 class="loading box">Ładowanie...</h2>').show();
			},
			success: function(data){
				$('#uiPopup').html(data);
			}
		});
	});		

// close popup login & register	
	$(document.body).delegate('.closePopup', 'click', function(e){
		e.preventDefault();
		
		$(this).parents('#uiPopup').hide().children('div:eq(0)').remove();
	});
	
// login
	$(document.body).delegate('#submitLogin', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				action = $this.parents('form').attr('action'),
				dataForm = $('#formLogin').serialize(),
				currentUrl;
		
		//window.location.reload(true);
		$.ajax({
			url : action,
			type : 'POST',
			data : dataForm,
			beforeSend : function(){
				$('#formLogin').find('input').attr('disabled', true);
				$this.attr('disabled', true).text('Loguję...');
			},
			success : function(data){
				var data = $.trim(data);

				if( data != ''){
					$('#uiPopup').html(data);
					updateInlineInputs();						
				} else {
					if( submitAction != '' ){
						currentUrl = window.location.href;
						$('body').load(currentUrl + ' #body > *');					
						var run = new Function(submitAction);
						run();						
					} else if( submitLink != '' ) {
						window.location.href = submitLink;
					} else {
						window.location.reload(true);
					}
				}					
			}
		});
	});	

// register
	$(document.body).delegate('#submitRegister', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				action = '/zaloz-konto',
				dataForm = $('#formRegister').serialize();
		
		var startPage = false;
		if( $('body').hasClass('startPage') ){
			startPage = true;
			action = action + '/1';
		}
		
		$.ajax({
			url : action,
			type : 'POST',
			data : dataForm,
			beforeSend : function(){
				$('#formRegister').find('input').attr('disabled', true);
				$this.attr('disabled', 'disabled').text('Rejestruję...');
			},
			success : function(data){
				var data = $.trim(data);

				if( data != ''){
					if( startPage == true ){
						$('#startRegisterFormWrap').html(data);
					} else {
						$('#uiPopup').html(data);
					}
					updateInlineInputs();						
				} else {
					window.location.reload(true);
				}	
			}
		});
	});	
	
// send logout	
	$(document.body).delegate('.logout', 'click', function(e){
		e.preventDefault();
		var link = this.href;
		
		$.get(link, function(data){
			window.location.reload();
		});
	});
	

// resize images while resizeing window
	function changeImageSize(){
		var $wrap =  $('#categoryThumbList');

		if( $wrap.length != 0 ){
			var count = 8,
					wrap_width = $wrap.find('ul').width(),
					new_width = Math.floor( (wrap_width / count) - 12 ),
					new_height = Math.floor( (100*new_width)/170 );
			
			$wrap.find('.topicImgWrap').width( new_width ).height( new_height ).find('img').width( new_width );		
		}
	}

	$(window).resize(function(e){
		changeImageSize();
	});
	
	changeImageSize();
	
// close & show box	
	$(document.body).delegate('.close', 'click', function(e){
		e.preventDefault();
		$(this).parents('div.box:eq(0)').hide();
	});
	
// inline labels	
	
	var updateInlineInputs = function(){
		$('.smart-form-list').find('input.input-txt').each(function(){
			var $this = $(this),
					$label = $(this).siblings('label').find('span');
			
			if( $this.val() !== '' ){	
				$label.attr('class','').addClass('notEmpty')
			}		
		});		
	}
	
	$('.smart-form-list').find('input.input-txt').live('focusin focusout keydown', function(e){
		var $label = $(this).siblings('label').find('span'),
				$this = $(this);
		
		if( $this.val() !== '' ){
			$label.addClass('notEmpty');
		}
		
		if( e.type === 'focusin' ){
			if( $this.val() ===  '' ) { 
				$label.attr('class','').addClass('hasFocus');
			}		
		} else if( e.type === 'focusout' ){
			if( $this.val() !== '' ) {
				$label.attr('class','').addClass('notEmpty');
			} else {
				$label.attr('class','').addClass('default');
			}		
		} else if( e.type === 'keydown' ){
			$label.attr('class','').addClass('notEmpty');		
		}
		
	});

// show additional input fields for video, images, maps, etc
/* 	$('.addons, .answerAddons').delegate('a', 'click', function(e){ */
	$(document.body).delegate('.addons a, .answerAddons a', 'click', function(e){
		e.preventDefault();
		var $this = $(this),
				rel = $this.attr('rel');
		
		$('.addonsInputWrap').addClass('hidden');
		$this.parents('ul:eq(0)').find('li').removeClass('active');
		
		if( $(rel).hasClass('hidden') ){
			$(rel).removeClass('hidden');
			$this.parent().addClass('active');
		} else {
			$(rel).addClass('hidden');
			$this.parent().removeClass('active');
		}
	});
	
// show added content - description
	$('#attachAddedContent').delegate('a', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				rel = $this.attr('rel');
		
		if( $(rel).hasClass('hidden') ){
			$(rel).removeClass('hidden');
		} else {
			$(rel).addClass('hidden');
		}
	});
	

// char counter	
	function charCouting(){
		var $textarea,
				limit,
				$counterWrap = $('#char-counter').find('strong'),
				charLenght,
				leftChars = limit,
				addedLength = 0,
				textareaValue = '',
				newValue = '';
		
		return {
			count: function(t){
					$textarea = t;
					limit = parseInt( $textarea.attr('maxlength') );
					
					charLenght = $textarea.val().length;
					textareaValue = $textarea.val();
					
					addedLength = (textareaValue.match(/[ąęćńłóśżź]/g) == null ) ? 0 : textareaValue.match(/[ąęćńłóśżź]/g).length;
					leftChars = limit - (charLenght + addedLength);

					if( leftChars <= 0 ){
						leftChars = 0;
						newValue = textareaValue.substr(0, limit - addedLength);
						$textarea.val(newValue);					
					}	
					$counterWrap.text(leftChars);
					
					if( leftChars <= 20 ){
						$counterWrap.addClass('att');
					} else {
						$counterWrap.removeClass('att');
					}
			}
			
		}
	}
	
	var counting = new charCouting();
		
	$(document.body).delegate('#qcontent', 'keyup', function(e){
		counting.count($(this));
	});
	
// set focus
	if( $('#qcontent').length ){
		$('#qcontent').focus();
	}	

// drop down menu @ menu-profile-notyfication
	$.fn.toggleMenu = function() {
			return this.each(function(){
				var $this = $(this),
						$menu = $this.next();
					
				$(this).click(function(){
					openMenu( $menu, $this);
					return false;
				});			
			});	
	}
	function openMenu( menu, wrap){
		wrap.siblings().removeClass('toggle').children('ul.uiDropDown').hide();
		if( menu.is(':hidden') ){
			menu.removeClass('hidden');
			wrap.parent().addClass('toggle');
		} else {
			menu.addClass('hidden');
			wrap.parent().removeClass('toggle');
		}		
	}
	$('#menuNotify .menuIcon, #menuMsg .menuIcon').toggleMenu();
	
// li as link @ dropdown
	$('#notifyMenu').delegate('li', 'click', function(e){
		var $this = $(this),
				link = $this.find('a.liveContent').attr('href');
		
		window.location.replace(link);
	});	
		
// show action @ list
	var action;
	$(document.body).delegate('#answersList li, .questionsList li', 'mouseover mouseout', function(e){	
		var $this = $(this),
				$action_link = $(this).find('.actionLinks');
				
		if( e.type == 'mouseover' ){
			$this.addClass('hover');
		} else {
			$this.removeClass('hover');
		}
	});	
	
// list (li) as link
	$.fn.beClickable = function() {
		var $this, 
				link;
				
		return this.each(function(){
			$(this).click(function(){
				$this = $(this);
				link = $this.find('a:eq(0)').attr('href'); // get first a.href			
				if( $this.hasClass('inactive') ){
					//xajax_login('Aby zobaczyć profil użytkownika, musisz się zalogować');
				} else {
					window.location.replace(link);  // cross browser redirect
				}
			});
		});
	}	
	
	$('#activeUsers li').beClickable();

	$('#quickbox-content').keypress(function(e){
		if (e.keyCode == 13) {
			$('#toggleActionForm').submit();
		}
	});
		
// comments 
	$(document.body).delegate('.addComment', 'click', function(){
		$(this).parents('li:eq(0)').find('textarea').focus();
	});
	
// hover table 
	$('#activeUserList').delegate('tr', 'mouseover mouseout', function(e){
		e.preventDefault();
		e.stopPropagation();
		
		if( e.type === 'mouseover' ){
			$(this).addClass('hover');
		} else {
			$(this).removeClass('hover');
		}
	});	
	
// uiSelect
	$('.uiSelect').delegate('span', 'click', function(){
		var $this = $(this),
				$list = $this.next();
				
		if( $list.hasClass('hidden') ){
			$list.removeClass('hidden');
		} else {
			$list.addClass('hidden');
		}
		
	});	
	
	
// smooth scroll to top		
	$(window).scroll(function(){
		var offset = window.pageYOffset;
		
		if( offset > 30 ){
			$('#gotoTop').stop().animate({
				'bottom' : 0
			}, 250);				
		} else if( offset <= 30 ){
			$('#gotoTop').stop().animate({
				'bottom' : '-40px'
			}, 250);		
		}
	});	
	
	$('#gotoTop').delegate('a', 'click', function(e){
		e.preventDefault();
		$('html,body').stop().animate({scrollTop: 0 }, 250);
	});		

	
// go to top and open menu ;-)	
	$('#bubble').delegate('a', 'click', function(e){
		e.preventDefault();
		
		var offset = window.pageYOffset;
		$('html,body').animate({ scrollTop: 0 }, 500 );
		
		if( offset !== 0 ){
			$(window).scroll(function(){
				offset = window.pageYOffset;
				if( offset === 0){
					gotoAndOpen();
				}
			});		
		} else {
			gotoAndOpen();
		}
		
	});
	
	function gotoAndOpen(){
		openMenu( $('#notifyMenu'), $('#menuNotify .menuIcon') );
		xajax_notify();
		$('#bubble').fadeOut('250');
	}	

	// set cookie with params
	function setCookie( name, value, exp_y, exp_m, exp_d, path, domain, secure ){
	  var cookie_string = name + "=" + escape( value );
	
	  if( exp_y ){
	    var expires = new Date( exp_y, exp_m, exp_d );
	    cookie_string += "; expires=" + expires.toGMTString();
	  }
	
	  if( path ) cookie_string += "; path=" + escape( path );
	  if( domain ) cookie_string += "; domain=" + escape( domain );
	  if( secure ) cookie_string += "; secure";
	  
	  document.cookie = cookie_string;
	}
	
	// get cookie
	function getCookie( cookie_name ){
	  var results = document.cookie.match( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	  if( results )
	    return ( unescape( results[2] ) );
	  else
	    return null;
	}
	
	// init welcome box
	function initWelcome(){
		var date = new Date();
		var y = date.getFullYear();
		var m = date.getMonth()+1;
					
		var x = getCookie('welcome');
		if( x === null )
			$('#welcome').removeClass('hidden'); 
		
		$('#welcome').delegate('a', 'click', function(){
			setCookie( 'welcome', 'visited', y, m+1, 1 );
		});
	}
	
	//initWelcome();

	// edit timer
	if( $('#myCtrls').lenght !== 0 ){
		window.setInterval(updateTime, 60000);
	}

	function updateTime(){
		var $target = $('#myCtrls em');
		var currentTime = parseInt( $target.text() );
		
		if( currentTime > 0 ){
			$target.text( currentTime-1 );
		} else if( currentTime === 0 ) {
			$('#myCtrls em').parents('li:eq(0)').fadeOut('fast');
		}
	
	}
	
// close dialog window
	function closeDialogWindow(){
		$('#dialog').hide();
	}

	$('#closeDialogWindow').live('click', function(e){
		e.preventDefault();
		
		closeDialogWindow();
	});	
	
	$('.showFlagList:not(.notLoggedIn)').live('click', function(e){
		e.preventDefault(); 
		
		var $this = $(this),
				id = $this.attr('data-id'),
				item = $this.attr('data-item'),
				$dialogWindow = $('#dialog');
		
		if( $dialogWindow.is(':hidden') ){
			$dialogWindow.show();
			
			$dialogWindow.find('#flag_ig').val(id);
			$dialogWindow.find('#flag_item').val(item);			
			
		} else {
			closeDialogWindow();
		}
	});	
	
// focus on auth email
	$('#authEmail').focus();		

// load more user 
	$(document.body).delegate('.loadMoreUsers', 'click', function(e){
		e.preventDefault();
		
		var $this = $(this),
				offset = parseInt( $this.attr('data-offset') ),
				step = parseInt( $this.attr('data-step') ),
				href = $this.attr('href'),
				count = parseInt( $this.attr('data-count') ),
				correct = $this.attr('data-correct'),
				new_offset = offset + step,
				url = (correct === '0') ? href + '/' + offset : href + '/' + offset + '/' + correct,
				current_count = $this.prev().find('li').length;
									
		if( current_count < count ){
			$.ajax({
				url : url,
				beforeSend: showSpinner($this),
				success: function(data){				
					$this.prev().append(data);
					$this.attr('data-offset', new_offset);					
					hideSpinner($this);
				}
			});	
		}	else {
			$this.remove();
		}		
		
	});
	
// load more tags/topics	
	$(document.body).delegate('#showMoreTags', 'click', function(e){
		e.preventDefault();

		var $this = $(this),
				offset = parseInt( $this.attr('data-offset') ),
				step = parseInt( $this.attr('data-step') ),
				href = $this.attr('href'),
				count = parseInt( $this.attr('data-count') ),
				new_offset = offset + step,
				url = href + '/' + offset,
				current_count = $this.prev().find('li').length;
		
		if( current_count < count ){
			$.ajax({
				url : url,
				beforeSend: showSpinner($this),
				success: function(data){				
					$this.prev().append(data);
					$this.attr('data-offset', new_offset);					
					hideSpinner($this);
				}
			});	
		}	else {
			$this.remove();
		}			
	});

// load more posts/questions
	$(document.body).delegate('#loadMorePosts', 'click', function(e){
		e.preventDefault();

		var $this = $(this),
				offset = parseInt( $this.attr('data-offset') ),
				step = parseInt( $this.attr('data-step') ),
				href = $this.attr('href'),
				count = parseInt( $this.attr('data-count') ),
				new_offset = offset + step,
				url = href + '/' + offset,
				current_count = $this.prev().find('li').length,
				data = $this.attr('data-id');

		if( current_count < count ){
			$.ajax({
				url : url,
				type : "POST",
				data : ({ 'data' : data }),
				beforeSend: showSpinner($this),
				success: function(data){				
					$this.prev().append(data);
					$this.attr('data-offset', new_offset);					
					hideSpinner($this);
				}
			});	
		}	else {
			$this.remove();
		}			
	});
	
	
// show ajax spinner
	function showSpinner(obj){
		$(obj).hide().parent().append('<span class="loadMoreSpinner"><img src="/design/css/i/alespinner.gif" /></span>');
	}	
	function hideSpinner(obj){
		$(obj).show().parent().find('span.loadMoreSpinner').remove();
	}

// show quiz/poll wrapper
	$('#questionTypeWrap').delegate('input', 'click', function(e){
		var $this = $(e.target),
				$pollOptions = $('#quizOptions').find('li');
		
		$this.parent().css('opacity', 1);
		if( $this.attr('id') == 'selectQuiz' ){
			if( $('#selectPoll:checked') ) $('#selectPoll').attr('checked', '').parent().css('opacity',0.2);
			$('#correctOptionQuiz').removeClass('hidden');	
			
			if( $pollOptions.length > 1 ){
				$pollOptions.parent().find('li:last').remove();
			}
			
		} else {
			if( $('#selectQuiz:checked') ) $('#selectQuiz').attr('checked', '').parent().css('opacity',0.2);
			$('#correctOptionQuiz').addClass('hidden');

			if( $pollOptions.length == 1 ){
				$pollOptions.clone().appendTo('#quizOptions').find('input').val('').next('a').remove();
			}
			
		}
		
		if( $('#quizOptionsWrap').hasClass('hidden') ){
			$('#quizOptionsWrap').removeClass('hidden');		
		}
		
		if( $this.not(':checked').length == 1 ) {
			$('#quizOptionsWrap').addClass('hidden');	
			$('#questionTypeWrap li').css('opacity', 1);
		}	
	});	

// add options to quiz/poll
	var options_count = 1;

	$(document.body).delegate('#addMoreOptions', 'click', function(e){
		e.preventDefault();
		var $this = $(this);
		var options_limit = $this.attr('data-limit');
		
		$('#quizOptions').find('li:eq(0)').clone().appendTo('#quizOptions').find('input').val('');
		if( options_count >= options_limit-1 ) {
			$this.addClass('hidden');
		}
		options_count++;	
		
	});
	
// remove quiz options
	$('#quizOptions').delegate('.removeQuizOption', 'click', function(e){
		e.preventDefault();
		var $this = $(this),
				$button = $('#addMoreOptions'),
				limit = parseInt( $button.attr('data-limit') );
	
		$this.parent().remove();
		
		if( options_count <= limit ){
			$button.removeClass('hidden');
			options_count--;
		}
	});	

// equal height column
	$.fn.equalHeight = function() {
		var tallest = 0;
		
		this.each(function(){
			thisHeight = $(this).height();
			tallest = (thisHeight > tallest) ? thisHeight : tallest;
		});
		return this.each(function(){
			$(this).css('height', tallest);
		});
	
	}
	
	$('.allTopics').equalHeight();

/* show button on focus */
	$('.contentAnswerWrap').delegate('textarea', 'focusin focusout', function(e){
		var $this = $(e.target),
				$btn = $this.parent().next('button');
		
		if( e.type == 'focusin' ){
			$btn.removeClass('hidden');
		} else if( e.type == 'focusout' && $this.val() == '' ) {
			$btn.addClass('hidden');		
		}
	});	

/* }); // end domready */

	function closeDialogWindow(){
		document.getElementById('dialog').style.display = 'none';
	}
