

(function($) {
	$.fn.toggleFade = function(settings)
	{
		if(settings==undefined) {
			settings={ speedIn : 'slow'};
		}
		
		settings = jQuery.extend(
				{
					speedIn: "normal",
					speedOut: settings.speedIn
				}, settings
		);
		return this.each(function()
				{
			var isHidden = jQuery(this).is(":hidden");
			jQuery(this)[ isHidden ? "fadeIn" : "fadeOut" ]( isHidden ? settings.speedIn : settings.speedOut);
				});
	};
})(jQuery);

(function($) {
	$.fn.toggleSlide = function(settings)
	{
		if(settings==undefined) {
			settings={ speedIn : 'slow'};
		}

		settings = jQuery.extend(
				{
					speedIn: "normal",
					speedOut: settings.speedIn
				}, settings
		);
		return this.each(function()
				{
			var isHidden = jQuery(this).is(":hidden");
			jQuery(this)[ isHidden ? "slideDown" : "slideUp" ]( isHidden ? settings.speedIn : settings.speedOut);
				});
	};
})(jQuery);

$(document).ready(function() {

/* some basic variables and globals */
var t = function(){alert('Teścior')};
var __global_selectedTheme     = "";
var __global_autoScroll        = true;
var __global_autoDeleteDash    = true;
var __global_blockPeriodical = false;
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
var isIE7 = navigator.userAgent.toLowerCase().indexOf('msie 7') != -1;
var __global_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

/* limit chars function */
function limitChars(textid, limit, infodiv)
{
var text = $('#'+textid).val(); 
var textlength = text.length;
if(textlength > limit)
{
$('#' + infodiv).html(l.youCannotChars+limit+l.chars);
 $('#'+textid).val(text.substr(0,limit));
 return false;
 }
 else
 {
 $('#' + infodiv).html((limit - textlength) +l.charsLeft);
 return true;
 }
 }

/* menu */
$("#navBar ul").superfish({
        animation:{opacity:'none', height:'show'},
        delay: 100,
        speed: 'fast'
});

/* photo tooltips */
$('.ajax-hover').live('mouseenter', function() { 
    var me = $(this)

    if(!me.hasClass('decorated')) {
        var t = me.tooltip({
            position: "top right",
            opacity: 1.0,
            effect: 'toggle',
            tip: '#photoTooltip',
            offset: [-15, 5],
            delay: 120,
            predelay: 175,
            lazy: false,
            onBeforeShow: function(e, position) {
                $('#photoTooltip').html("<p class='preloader-tooltipImage'>"+ l.loading +"</p>");

                $.get(conf.cSiteUrl+'/ajax/photo/details/'+ me.attr('rel'), function(data) {
                    $('#photoTooltip').html(data);
                });
            }
        }).dynamic().tooltip().show();

        me.addClass('decorated')
    }

});

//photoTooltip();

$('.ajax-hover-user').live('mouseenter', function() {

    var me = $(this);

if(!me.hasClass('decorated')) {

var t = me.tooltip({
    position: "top right",
    opacity: 1.0,
    effect: 'toggle',
    tip: '#userTooltip',
    offset: [-15, 5],
	delay: 225,
	predelay: 215,
	lazy: false,
	onBeforeShow: function(e, position) {
		var element = e.originalTarget || e.srcElement;
		
		$('#userTooltip').html("<p class='preloader-tooltipUser'>"+ l.loadingUser +"</p>");
		
		$.get(conf.cSiteUrl+'/ajax/user/'+me.attr('rel'), function(data) {
			$('#userTooltip').html(data);
		});
	}
}).dynamic().tooltip().show();

me.addClass('decorated')

}

});

/* tooltips for icons */
$('.tooltipIco[title]').tooltip({
    position: "top center",
    opacity: 1.0,
    effect: 'slide',
    tip: '#icoTooltipWrap',
    offset: [3,0],
	delay: 225,
	predelay: 50,
	lazy: false            
}).dynamic();

/* tooltips for texts, .icoTooltip */
$('.tooltipText[title]').tooltip({
    position: "top center",
    opacity: 1.0,
    effect: 'fade',
    tip: '#textTooltipWrap',
    offset: [-7,0],
	delay: 145,
	predelay: 50,
	lazy: false            
}).dynamic();

/* tooltips for form inputs */
$('.tooltipForm').tooltip({
    position: "center right",
    opacity: 0.8,
    effect: 'fade',
    tip: '#formTooltipWrap',
    offset: [0,10],
	delay: 0,
	predelay: 60,
	lazy: false            
});

/* tabs: no-ajax without history, id .tabbed-nav */
$('.tabbed-nav').tabs("#tab-panes > div", {effect: 'fade'});

/* tabs: no-ajax with history, id .tabbed-nav-history */
$('.tabbed-nav-history').tabs("#tab-panes > div", {effect: 'fade'}).history();

/* tabs: ajax with history, class .tabbed-nav-ajax */
$('.tabbed-nav-ajax').tabs("#tab-panes-ajax > div", {effect: 'ajax', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");

}}).history();

/* tabs: homepage recent items */
$('.tabbed-nav-hp-recent').tabs("#tab-panes-hp-recent > div", {effect: 'ajax', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");
    //photoTooltip();

}});

/* tabs: homepage users */
$('.tabbed-nav-hp-users').tabs("#tab-panes-hp-users > div", {effect: 'ajax', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");
    //userTooltip();

}});

/* tabs - "TV napięcia" categories */

            var catTabs = function() {
            
            var competTargetNode      = $('.mainCompet_CatMore');
            var competTargetPreloader = '<p class="preloader-widget">'+ l.loadingPhoto +'</p>';

            $('#mainCompetSlider .mainCompet_CatList ul li a, #subCompet .mainCompet_CatList ul li a').each(function(idx, obj) {

                $(this).click(function() {

                   $(this).parent().parent().find('a.active').removeClass('active');
                   $(this).addClass('active');

                    competTargetNode.empty();
                    $('.mainCompet_CatMore').prepend(competTargetPreloader);

                    competTargetNode.load(this.href, function() {

                        $('.mainCompet_CatMore .preloader-widget').hide();

                       //photoTooltip();
                       //userTooltip();

                    });

                    return false;

                });

            });
            }

catTabs();

/* tabs: "TV napięcia", competitions - at last... */
$('.tabbed-nav-competitions').tabs("#mainCompetContent > div", {effect: 'ajax', current: 'active', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().empty().html("<p class='preloader-widget-tab'>"+ l.loadingTab +"</p>");

}, onClick: function(event, tabIndex) {

	    if($('.mainCompet_CatList').length>0) {

                if($('.mainCompet_CatList .active').length==0) {

                    $('.mainCompet_CatList ul li:first-child a').addClass('active')

                }

            }
            
            //photoTooltip();
            catTabs();

}}).history();


/* tabs - photo view */
$('.tabbed-nav-ajax-photo').tabs("#photoLargeView", {effect: 'ajax', tabs: 'a.ajaxTab', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");
    //photoTooltipEl.trigger('photoOpenEvent');

}, onClick: function(ev, id) {
     if(photo_show) photo_show()
}}).history();

/* tabs - text view */
$('.tabbed-nav-ajax-text').tabs("#tab-panes-ajax-text > div", {effect: 'ajax', tabs: 'a.ajaxTab', onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");

}}).history();

var checkTabError = function(tab) {

	if($('#settings_form #tab-panes-settings div[rel='+tab+']').find('.error_list').length>0) {
	
	    var errTab = $('.tabbed-nav-settings a[rel='+tab+']');
	    var oldText = $('.tabbed-nav-settings a[rel='+tab+']').html();
	    
	    errTab.addClass('colorRed');
	    errTab.addClass('errors');
	    errTab.addClass('bold');
	    errTab.html(oldText+' (błędy)');
	
	}


}

var getFirstErrorTabIdx = function(tabs) {

    var cont = $(tabs).find('a');
    var errTab = $(tabs).find('.errors:first-child');
    
    return cont.index(errTab);
    
}



/* errors in tabbed-nav forms - implementation (neat ]:->) */
if($('#settings_form').length>0) {

    if($('#settings_form').find('.error_list').length>0) {


	checkTabError('profile')
	checkTabError('data');
	checkTabError('preferences');
	checkTabError('password');
        
    }

}

if(getFirstErrorTabIdx($('.tabbed-nav-settings'))!="-1") {
    var errIndex = getFirstErrorTabIdx($('.tabbed-nav-settings'));
} else { 
    var errIndex = 0; 
}

/* tabs: no-ajax with history for settings, class .tabbed-nav-settings */
$('.tabbed-nav-settings').tabs("#tab-panes-settings div.tab-content", {effect: 'fade', initialIndex: errIndex}).history();

var api = $('.tabbed-nav-settings').tabs(0);

/* steps */
$('.stepRight').click(function(event) {

    api.next();

    event.preventDefault();

});

$('.stepLeft').click(function(event) {

    api.prev();
    
    if(api.getIndex()==0) { $('html').animate({ scrollTop: 150 }, 600); }

    event.preventDefault();

});

var getActiveTabIdx = function(tabs, rel) {

    var cont = $(tabs).find('a');
    var actTab = $(tabs).find('a[href=#'+rel+']');
    
    return cont.index(actTab);
    
}

/* tab-navigation - .boxed-menu - detecting .active class in children tabs, then opening parent tab() - workaround :| */
if($('.tabbed-box-menu-panes .active').length>0) {

    //searching for initial tab index
    var actLink = $('.tabbed-box-menu-panes').find('.active');
    var parentName = actLink.parent().parent().parent().attr("rel");
    
    var startIdx = getActiveTabIdx('.tabbed-box-menu', parentName);

    var startIndex;

if(startIdx!="-1") {
    startIndex = getActiveTabIdx('.tabbed-box-menu', parentName);
} else { 
    startIndex = 0; 
}

}

$('.tabbed-box-menu').tabs("#tab-panes-menuItems > div", {effect: 'fade', initialIndex: startIndex}).history();


/* profile-tabs: commented recenlty */
$('#tabCommentedRecently').tabs("#tabCommentedRecentlyPanes > div", {effect: 'ajax', api: true, onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");

}, onClick: function(event, tabIndex) {

    $('#tabCommentedRecentlyPanes .slider').jCarouselLite({
        btnNext: "#tabCommentedRecentlyPanes .next",
        btnPrev: "#tabCommentedRecentlyPanes .prev",
        mouseWheel: true,
        auto: 7000,
        speed: 400
    });

}});




/* profile-tabs: commented main tabs */
$('.tabCommented').tabs("#tabCommentedPanes > div", {api: true, onClick: function(event, tabIndex) {

    
    if(tabIndex==1) {
    /* profile-tabs: commented mostly */
$('#tabCommentedMostly').tabs("#tabCommentedMostlyPanes > div", {effect: 'ajax', api: true, onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");

}, onClick: function(event, tabIndex) {
    
    $('#tabCommentedMostlyPanes .slider').jCarouselLite({
        btnNext: "#tabCommentedMostlyPanes .next",
        btnPrev: "#tabCommentedMostlyPanes .prev",
        mouseWheel: true,
        auto: 7000,
        speed: 400
    });

}});
    
	$('#firstClick').trigger('click');
    }

}});


/* profile-tabs: visited mostly */
$('.tabVisitedMostly').tabs(".tabVisitedMostlyPanes > div", {effect: 'ajax', api: true, onBeforeClick: function(event, tabIndex) {

    this.getCurrentPane().html("<p class='preloader-whiteBg'>"+ l.loadingTab +"</p>");

}, onClick: function(event, tabIndex) {

    /* profile tabs: sliding */
    /*$('.tabVisitedMostlyPanes .slider ul').cycle({
        fx:    'fade',
        speed:    200,
        timeout:  0,
        prev: '.tabVisitedMostlyPanes .prev',
        next: '.tabVisitedMostlyPanes .next'
    });*/
    
    $('.tabVisitedMostlyPanes .slider').jCarouselLite({
        btnNext: ".tabVisitedMostlyPanes .next",
        btnPrev: ".tabVisitedMostlyPanes .prev",
        mouseWheel: true,
        auto: 7000,
        speed: 400
    });

}});

/* tabs: adding microblog entry */
//$('#tab-nav-microblog-form').tabs("#tab-panes-microblog-form > div", {effect: 'fade'});

/* last comments slider */
    /*$('#lastCommentsSlider ul').cycle({
        fx:    'fade',
        speed:    200,
        timeout:  0,
        prev: '#lastCommentsSlider .prev',
        next: '#lastCommentsSlider .next'

    });*/


/* click menu, .click-menu-open opens .click-menu */
$('.click-menu-open').live('click', function() {

    var menuBtnHeight = this.offsetHeight;
    var showMenuOffsetTop = this.offsetTop+menuBtnHeight+4;
    var showMenuOffsetLeft = this.offsetLeft;

    $(this).toggleClass('active');
    
    $('.click-menu').css({'top': showMenuOffsetTop+'px', 'left': showMenuOffsetLeft+'px'}).toggle();
    
    $('.click-menu').find('form').one("submit",function() {
    
	$.ajax({
	    url: this.action,
	    type: "GET",
	    success: function(data) {
	
		$('.click-menu-open').removeClass('active');
		$('.click-menu').hide();
		$('.click-menu').find('.form-waiter').empty();
	    
	    },
	    error: function(data) {

	        $('.click-menu-open').removeClass('active');
                $('.click-menu').hide();
                $('.click-menu').find('.form-waiter').empty();
                
		alert('błąd');
		
	    
	    }
	
	});
	
	return false;
    
    });
    
    return false;

});
    
/* expose photo */
$(".actionExpose").live("click", function() {

    $('.toExpose').expose({ 
	    opacity: 0.9,
	    loadSpeed: 750,
	    closeSpeed: 100,
        maskId: 'exposeMask',
        onLoad: function() { 
            this.getExposed().css({backgroundColor: '#ff0000'}); 
        }, 
	    onClose: function() { 
            this.getExposed().css({backgroundColor: null}); 
        }, 
        api: true 
        }).load(); 
    }); 


/* modal: information modal with one button */

var iModal = function(title, text, buttons, href) {

    this.title   = title;
    this.text    = text;
    if(buttons) {
	this.buttons = buttons;
    } else {
	this.buttons = "";
    }

    $.modal('<h2>'+ this.title +'</h2><div class="modalContainer">'+ this.text +'</div><div class="modalButtons">'+ this.buttons +'</div>', {opacity: 80, maxWidth: 450, onShow: function(dialog) {

	$('.modal-close-pass').click(function() {
	
	    var targetUrl = $(href).attr("href");
	    window.location.href = targetUrl;
	
	});
	
	$('.modal-close').click(function() {
	
	    $.modal.close();
	
	});
    
    }});

}

var cModal = function(title, text, buttons, href) {

    this.title   = title;
    this.text    = text;
    if(buttons) {
	this.buttons = buttons;
    } else {
	this.buttons = "";
    }

    $.modal('<h2>'+ this.title +'</h2><div class="modalContainer">'+ this.text +'</div><div class="modalButtons">'+ this.buttons +'</div>', {opacity: 80, maxWidth: 450, onShow: function(dialog) {

	$('.modal-confirm-yes').click(function(event) {
	
	    var targetUrl = $(href).attr("href");
	    
	    if($(href).is('input')) { 
	    
		$(document).find('form#settings_form').submit();
	    
	    } else {
		
		if($(href).hasClass('dsh-delete')) {

		    event.preventDefault();
		    var dshRemId = $(href).attr("dshid");
		    $.get(conf.cSiteUrl+'/ajax/dashboard/delete/'+dshRemId, function(data){
			
			if(data.ifOk) {
			    $(href).parent().parent().parent().fadeOut(1000).remove();
			    $.modal.close();
			} else {
			    //t();
			    $.modal.close();
			}
		    
		    }, 'json');

		} else if($(href).hasClass('comment-del')) {
		
		    event.preventDefault();
		    var comRemId = $(href).attr("cid");
		    
		    $.get(conf.cSiteUrl+'/comment/delete/'+comRemId, function(data){
			
			if(data.ifOk) {
			    $(href).parent().parent().fadeOut(1000).remove();
			    $.modal.close();
			} else {
			    //t();
			    $.modal.close();
			}
		    
		    }, 'json');

		} else {
	    
		window.location.href = targetUrl;
		
		}
	    
	    }
	    
	
	});
	
	$('.modal-confirm-no').click(function() {
	
	    $.modal.close();
	
	});
    
    }});

}

var fModal = function(domId) {

    this.domId   = domId;
        
    $.modal($('#'+domId), {opacity: 80, maxWidth: 450, onShow: function() {
    
	// get events for every modal form on site - if has tabs!
	if($('#tab-nav-microblog-form').length>0) {
	    $('#tab-nav-microblog-form').tabs("#tab-panes-microblog-form > div", {effect: 'fade'});
	}

        $('.modal-close').click(function() {

	    $.modal.close();

	});
    
    }});

}

/* modals triggering example for dedicated element
$('#modal-info').click(function(event) {

    iModal('Tytuł modala', 'Teeeeekst informacyjny!!!!!', '<span class="modal-close">OK</span>');
    event.preventDefault();

});

*/

/* modal class: .modal-info needs rel="Title|Message body" */
$('.modal-info').click(function(event) {

    var args  = $(this).attr('rel').split("|");
    var title = args[0];
    var text  = args[1];
    
    iModal(title, text, '<span class="bold modal-close btnPink">OK</span>', this);
    
    event.preventDefault();

});

/* modal class: .modal-info needs rel="Title|Message body" */
$('.modal-info-pass').click(function(event) {

    var args  = $(this).attr('rel').split("|");
    var title = args[0];
    var text  = args[1];
    var btn   = args[2];
    
    iModal(title, text, '<span class="bold modal-close-pass btnPink">'+ btn +'</span><span class="modal-close btnBlue">'+ l.cancel +'</span>', this);
    
    event.preventDefault();

});

/* modal class: .modal-confirm needs rel="Title|Message body" */
$('.modal-confirm').live('click', function(event) {

    var args  = $(this).attr('rel').split("|");
    var title = args[0];
    var text  = args[1];
    
    cModal(title, text, '<span class="bold modal-confirm-yes btnPink">'+ l.yes +'</span><span class="modal-confirm-no btnBlue">'+ l.no +'</span>', this);

    event.preventDefault();

});

/* modal class: .modal-form needs rel="id-of-dom-element-with-form|window title" */
$('.modal-form').click(function(event) {

    var domId   = $(this).attr('rel');
        
    fModal(domId);

    event.preventDefault();

});

/* showing modal forms with validation errors - MUST be per page */
if($('.site-favourites').length>0) {

    if($('.form-editExt').length>0) {
    
	if($('.form-editExt .error_list').length>0) {
	
	    fModal('modal-edit-favourite-new');
	
	}
    
    }

}

if($('.site-photoView').length>0) {

    if($('#form-editPhoto').length>0) {
    
	if($('#form-editPhoto .error_list').length>0) {
	
	    fModal('modal-photo-edit-form');
	
	}
    
    }

}

/* voting mechanism */

$('.actionVote').live('click', function() {
        var oldHtml     = $(this).parent().html();
        var parentObj   = $(this).parent();
        var voteCtn     = $(this).parent().parent().find('.votes');
        var voteCounter = $(this).parent().parent().find('.incVotes');
        var oldVotes    = $(this).parent().parent().find('.incVotes').text();
        var newVotes    = parseFloat(oldVotes) + 1;
        
        parentObj.html('<p class="preloader-vote">'+ l.wait +'</p>')

        $.ajax({
            type: "GET",
            url: conf.cSiteUrl+'/'+ conf.cLang +'/photo/'+this.rel+'/vote',
            dataType: "json",
            complete: function(xhr, textStatus) {
              if(xhr.status=="401") {
                 iModal(l.mustLogTitle,l.mustLogBody, '<span class="bold modal-close-pass btnOrange">'+ l.login +'</span><span class="modal-close btnGrey">'+ l.cancel +'</span>');
                 parentObj.html(oldHtml);
              }
            },
            success: function(data){
              if (data.ifOk) {
                parentObj.html('<p class="icoSuccess">'+l.thanks+'</p>');
                voteCounter.empty().text(newVotes);
                voteCtn.fadeOut(400).fadeIn(300);
              } else {
                iModal(l.comm,data.message,'<span class="modal-close btnGrey">OK</span>');
                parentObj.html(oldHtml);
              }
            }

        })
        return false;

    });

/* Sliding login prompt */
if(!isIE6 && !isIE7) {

        $("#loginFormSlide").click(function() {

           $(this).toggleClass('active');

           $("#loginTopForm #logOnForm").toggle();
           
           /*.expose({ 
	    opacity: 0.4,
	    loadSpeed: 450,
	    closeSpeed: 200,
    	    maskId: 'exposeMaskLogin',
	    onClose: function() { 
            this.getExposed().css({backgroundColor: null}); 
    	    }, 
    	    api: true 
    	    }).load();*/
    	    
           $("#loginTopForm #logOnForm .secondFocus").focus();

           $('#content').click(function() {

                $("#loginTopForm #logOnForm").hide();

           });

           return false;

        });
}

/* colorizer */
$('#toggleColorizer').click(function(event) {

    $(this).toggleClass('active');

    $('#colorizer').slideToggle();

    event.preventDefault();

});



/* colorizer theme switcher, neat :-D */
$('#colorizer ul li a').click(function(event) {

    $('#colorizerImport').remove();

    var theme = $(this).attr('rel') +'.css';
    var path = public_path("css/themes/"+theme);
    __global_selectedTheme = theme;
    
    $('#colorizerTheme').attr('href', path);
    
    event.preventDefault();

});

/* saving theme */
$('#saveColorizer').click(function(event) {

    $.post(conf.cSiteUrl+'/setsetting', { 'css_scheme': __global_selectedTheme});
    
    if($(this).parent().find('p.icoSuccess').length>0) {
	$(this).parent().find('p.icoSuccess').remove;
    } 
    $(this).parent().append('<p class="icoSuccess">Zmieniono!</p>');
    $(this).parent().find('p.icoSuccess').fadeOut(3000);
    
    event.preventDefault();

});

/* scrolling and adding */
if($('.dashboard-wrap-top').length>0) {
    $(".dashboard-wrap-top").animate({ scrollTop: $(".dashboard-wrap-top").attr("scrollHeight") }, 200);
}



if($('#dashboardProfileForm').length>0) {

    $.hideAllComments = function() {


    }

    $.attachCommentEvents = function(container){

	var ct = $(container);

	// show preloader
	ct.find('.list').html('<p class="preloader-form">'+ l.wait +'</p>');

	// cancel button
	ct.find('.cancel').one('click',function(event) {

	    ct.slideToggle('fast');

	    event.preventDefault();

	})

	// gettin dashboard entry id
	var args   = ct.attr('rel').split("_");
	var entId  = args[1];

	// ajax comments url
	var remoteRep  = conf.cSiteUrl+'/ajax/comment/get';

	$.ajax({
	    type: 'POST',
	    url: remoteRep,
	    dataType: 'JSON',
	    data: {
	    'notifications': [
	    {'id': entId}
	    ]
	    },
	    success: function(data) {

                var ar = JSON.parse(data);
		if(ar[entId]!="") {

		    ct.find('.list').empty().append(ar[entId]);

		} else {

		    ct.find('.list').html('<ul class="commentList"></ul><p class="noComments">Nikt nie skomentował jeszcze tego wpisu.</p>');

		}
	    }
	});


	// attach adding comment events
	$("#dashCommentForm_"+entId).validate({
        errorElement: 'em',
        rules: {
                'comment[comment]': {
                    required: true,
                    maxlength: 500
                }

        },
        messages: {
                'comment[comment]': {
                    required: l.v_required,
                    maxlength: l.v_maxlength500
                }

        },
        submitHandler: function() {

	function processNewComment(data) {

    	    if(data.ifOk) {

		// increment comments count
		var commCount = parseFloat(ct.parent().find('.incComments').html());
		var newCommCount = commCount + 1;

		ct.parent().find('.incComments').html(newCommCount);
		
		// change icon
		ct.parent().find('.icoCommentBW').removeClass('icoCommentBW').addClass('icoComment');

		ct.find('.list ul').append(data.body).fadeIn('slow');
		var nick = ct.parent().find('.dashCommentList').attr('cnick');
		//ct.parent().find('.dashCommentList').prepend();

        	$('.preloader-form').remove();
        	$('.noComments').remove();

    	    } else {

        	iModal(l.comm, data.message, '<span class="bold modal-close btnGrey">OK</span>', this);
        	$('.preloader-form').remove();

    	    }

	}(ct);

	var optionsDash = {
    	    dataType:  'json',
    	    success: processNewComment,
    	    beforeSubmit: function() { if($('p.preloader-form').length==0) { ct.find('.submitWrapper').append('<p class="preloader-form">'+ l.wait +'</p>') } }
	};

	ct.find('form').ajaxSubmit(optionsDash);

        }
	});


    }
    
    // unbinding events, to optimize speed
    $.detachCommentEvents = function(container){
    
	var ct = $(container);
	ct.find('.cancel').unbind('click');
	ct.find('.list').empty();
    }

    var __global_targetComm;
    var __global_started;

    function getPeriodical() {

	if($('#dashboard-profile').find('ul#dash > li:first-child').length>0) {
	    var firstEl    = $('#dashboard-profile').find('ul#dash > li:first-child');

	} else { 
	    var firstEl    = $('#dashboard-profile').find('ul#dash')
	}
	
	var lastId    = firstEl.attr("id");
	var lastEl    = $('#dashboard-profile').find('ul#dash > li:last-child');
	var nick       = $('#dashboard-profile').attr("rel"); 
	var userId       = $('#dshInfo').attr("rel"); 
	var remoteRep  = conf.cSiteUrl+'/ajax/dashboard/get';

	__global_started = true;

	if($('#dashboard-profile').hasClass('dashboard-chat-only')) {
	
	    var sendData = {'user_id': userId, 'newer_than': lastId, 'dashboard': '1', type: "Chat"}
	
	} else {

	    var sendData = {'user_id': userId, 'newer_than': lastId, 'dashboard': '1'}
	
	}

	$.ajax({
	    type: 'POST',
	    url: remoteRep,
	    dataType: 'html',
	    data: sendData,
	    success: function(data) { 
		if(data!="") {
		    
		    if($('#dashboard-profile').find('ul#dash > li:first-child').length>0) {
			firstEl.before(data);
		    } else {
			firstEl.empty().append(data);
		    }
		    
		    __global_targetComm = data;
		    
		    if(__global_autoDeleteDash) {
			if($('.dashboard-profile ul li').length>=25) {
			    $('.dashboard-profile ul li:last-child').remove();
			}
		    }

		}
	    },
	    complete: function() {
	    
	    //alert(__global_targetComm);
	    
	    $.each($('.dashboard-profile ul li .comments'), function(idx,val) {
	    
		var targetClick = $(val).parent().find('.toggle');
		
		if(!targetClick.hasEvent('click')) {
		
                    $(targetClick).click(function(event) {
    
                    $(this).toggleClass('active');
	
                    if($(this).parent().find('.comments').is(':visible')) {
                        $.detachCommentEvents($(this).parent().find('.comments'));
                        $(this).parent().find('.toShow').show('fast').addClass('ajaxCommentsGet');
                        $(this).parent().find('.comments').slideToggle('fast').removeClass('ajaxCommentsGet');
                        $(this).parent().find('.lastComments').show();
                    } else {
                        $.attachCommentEvents($(this).parent().find('.comments'));
                        $(this).parent().find('.lastComments').hide();
                        $(this).parent().find('.ajaxCommentsGet').hide('fast').removeClass('ajaxCommentsGet');
                        $(this).parent().find('.comments').slideToggle('fast').addClass('ajaxCommentsGet');
                    }
	
                  event.preventDefault();
		
		});
	    
	    }
	    
	    });
	    
	    }});
	    
	    __global_started = false;
	    
    }

    var holdInterval = setInterval(getPeriodical, 2000);

    $('#dshInfo').keyup(function() {

	limitChars('dshInfo', 400, 'infoRemaining')

    });

    var addMsg = function() {

	var msg        = $('#dshInfo').val();
	var firstEl    = $('#dashboard-profile').find('ul#dash > li:first-child');
	var lastEl     = $('#dashboard-profile').find('ul#dash > li:last-child');
	var nick       = $('#dashboard-profile').attr("rel"); 
	var userId     = $('#dshInfo').attr("rel"); 
	
	if($('#newsfeed').is(':checked')) {
	 var asHP = '1'; 
	} else {
	 var asHP = '0';
	}
	
	//if(__global_autoScroll) { $(".dashboard-wrap-top").animate({ scrollBottom: $(".dashboard-wrap-top").attr("scrollHeight") }, 400); }
	
	$('#dshInfo').val("");
	
	$.ajax({
	    type: 'POST',
	    url: conf.cSiteUrl+'/ajax/dashboard/'+ userId +'/chat',
	    dataType: 'json',
	    data: {message: msg, newsfeed: asHP },
	    success: function(data) { 
		    
		    //getPeriodical();
		    
		    if($('.oneElemAcceptTerms').is(":visible")) {
			$('.oneElemAcceptTerms').toggleFade();
		    }
		    
		    if($('#newsfeed').is(':checked')) {
			$('input[type=checkbox]').attr('checked', false);
		    }
		    
		    /*$('.dashboard-profile ul li#'+data.id+'').fadeOut(200).fadeIn(750);*/
		    $('#infoRemaining').html('400 '+l.charsLeft);
		    
		    //if(__global_autoScroll) { $(".dashboard-wrap-bottom").animate({ scrollTop: $(".dashboard-wrap-bottom").attr("scrollHeight") }, 350); }
		    
		    if($('.dashboard-profile ul li').length>=25) {
			$('.dashboard-profile ul li:last-child').remove();
		    }
		    
	    }
	});
    }
    
    $('#newsfeed').change(function() {
    
	$('.oneElemAcceptTerms').toggleFade();
    
    });
    
    if($('#newsfeed').is(':checked')) {
    
	$('.oneElemAcceptTerms').toggleFade();
    
    }

    $("#dashboardProfileForm").validate({
        errorElement: 'em',
        errorPlacement: function(error, element) {
        	error.appendTo( element.parent() );
        },
        rules: {
                'dshAccept': {
                    required: "#newsfeed:checked"
                }
        },
        messages: {
                'dshAccept': {
                    required: l.v_required
                }

        },
        submitHandler: function() {
        
    	    addMsg();
        
        }
    });

    $(document).bind('keydown', 'ctrl+space', function() {

	addMsg();
    
    });


    /* comments */
    $('.dashboard-profile ul li .toggle').click(function(event) {
    
	$(this).toggleClass('active');
	
        if($(this).parent().find('.comments').is(':visible')) {
            $.detachCommentEvents($(this).parent().find('.comments'));
            $(this).parent().find('.toShow').show('fast').addClass('ajaxCommentsGet');
            $(this).parent().find('.comments').slideToggle('fast').removeClass('ajaxCommentsGet');
            $(this).parent().find('.lastComments').show();
        } else {
            $.attachCommentEvents($(this).parent().find('.comments'));
            $(this).parent().find('.lastComments').hide();
            $(this).parent().find('.ajaxCommentsGet').hide('fast').removeClass('ajaxCommentsGet');
            $(this).parent().find('.comments').slideToggle('fast').addClass('ajaxCommentsGet');
        }
	
	event.preventDefault();
    
    });

}



/* show previous dashboard messages */
$('#dashboard-show-previous-profile').click(function(event) {

    var targetDsh  = $('#dashboard-profile');
    var firstEl    = $('#dashboard-profile').find('ul#dash > li:last-child');
    var nick       = $('#dashboard-profile').attr("rel");
    var remoteRep  = conf.cSiteUrl+'/ajax/dashboard/get';
    var userId       = $('#dshInfo').attr("rel"); 
    var lastId    = firstEl.attr("id");

	if($('#dashboard-profile').hasClass('dashboard-chat-only')) {
	
	    var sendData = {'user_id': userId, 'older_than': lastId, 'dashboard': '1', 'limit': '10', 'type': 'Chat'}
	
	} else {

	    var sendData = {'user_id': userId, 'older_than': lastId, 'dashboard': '1', 'limit': '10'}
	
	}

	$.ajax({
	    type: 'POST',
	    url: remoteRep,
	    dataType: 'JSON',
	    data: sendData,
	    success: function(data) { 
		if(data!="") {
		    __global_autoDeleteDash = false;
		    firstEl.after(data); 
		    //if(__global_autoScroll) { $(".dashboard-wrap-bottom").animate({ scrollTop: $(".dashboard-wrap-bottom").attr("scrollHeight") }, 350); }
		    //$('.dashboard-wrap-profile ul li:last-child').remove();
		}
	    }
	});

    event.preventDefault();

});

$('#dashboard-switch-autoscroll').click(function(event) {

    $(this).toggleClass('active');
    
    if(__global_autoScroll) {
	__global_autoScroll = false;
    } else {
	__global_autoScroll = true;
    }
    
    event.preventDefault();

});

/* main dashboard refreshing */
if($('.dashboard-main-logged').length>0) {

    function getPeriodicalMain() {

	var firstEl    = $('.dashboard-main-logged').find('ul li:first-child');
	var lastId    = firstEl.attr("id");
	var lastEl    = $('.dashboard-main-logged').find('ul li:last-child');
	var userId       = $('.dashboard-main-logged').attr("rel"); 
	var remoteRep  = conf.cSiteUrl+'/ajax/dashboard/get';

	$.ajax({
	    type: 'POST',
	    url: remoteRep,
	    dataType: 'html',
	    data: {'user_id': userId, 'newer_than': lastId, 'dashboard': '1', partial: 'singleShort'},
	    success: function(data) {
		if(data!="") {
		    $('.dashboard-main-logged ul').prepend(data);
		    lastEl.remove();
      		    //userTooltip();
		}
	    }
        });
    }

    var holdIntervalLogged = setInterval(getPeriodicalMain, 8000);
}

/* main info dashboard refreshing */
if($('.dashboard-main-info').length>0) {

    function getPeriodicalMain() {

	var firstEl    = $('.dashboard-main-info').find('ul li:first-child');
	var lastId    = firstEl.attr("id");
	var lastEl    = $('.dashboard-main-info').find('ul li:last-child');
	var userId       = $('.dashboard-main-info').attr("rel"); 
	var remoteRep  = conf.cSiteUrl+'/ajax/dashboard/get';

	$.ajax({
	    type: 'POST',
	    url: remoteRep,
	    dataType: 'html',
	    /*info dashboard data: {'newer_than': lastId, 'dashboard': '0'}, */
	    data: {'newer_than': lastId, 'dashboard': '4'},
	    success: function(data) {
		if(data!="") {
		    $('.dashboard-main-info ul').prepend(data);
		    lastEl.remove();
      		    //userTooltip();
		}
	    }
        });
    }

    var holdIntervalInfo = setInterval(getPeriodicalMain, 6000);
}

/* opening new dashboard window */
$('a[rel="external"]').click( function() {
    window.open( $(this).attr('href'),'dashboard','height=500,width=450,toolbar=no,scrollbars=yes,resizeable=true,left=100,top=100,menubar=no,location=no,status=yes' );
    return false;
});

/* video loading on worthseeing page */
$('.video-grid li a').click(function(event) {

    // getting some params
    var id               = $(this).attr('rel');
    var targetVideoObj   = $('.oneVideoBig object param[name=movie]');
    var targetVideoEmb   = $('.oneVideoBig object embed');
    var targetVideoTitle = $('.oneVideoBig p.title');
    var targetVideoDesc  = $('.oneVideoBig p.desc');
    var YT_pattern_1     = "http://www.youtube.com/v/";
    var YT_pattern_2     = "&hl=pl_PL&fs=1&color1=0x3a3a3a&color2=0x999999";
    var newVideoURL      = YT_pattern_1+id+YT_pattern_2;
    
    // changing video
    targetVideoObj.val(newVideoURL);
    targetVideoEmb.attr("src", newVideoURL);
    $(this).parent().parent().parent().find('.active').removeClass('active');
    $(this).addClass('active');
    
    // changing title and description (oh God, what a shortcut)
    
    var vArgs  = $(this).find('img').attr('title').split("|");
    var vTitle = vArgs[0];
    var vDesc  = vArgs[1];
    
    targetVideoTitle.html(vTitle);
    targetVideoDesc.html(vDesc);
    
    targetVideoTitle.fadeOut(200).fadeIn(400);
    targetVideoDesc.fadeOut(200).fadeIn(400);
    
    event.preventDefault();

});

/* background photo changer */
    $('#bgChanger .white').live('click',function() {

        $('#photoLargeView').animate({backgroundColor:'#FFFFFF'}, 800);
        $('#photoLargeView').animate({color:'#000000'}, 300);

	/* saving default color of photo background to profile */
	if($('.saveDefaultColor').length>0) {

    	    $.post(conf.cSiteUrl+'/setsetting', { 'default_color': 'white'});

	}

        return false;
    });

    $('#bgChanger .black').live('click',function() {

        $('#photoLargeView').animate({backgroundColor:'#222222'}, 800);
        $('#photoLargeView').animate({color:'#FFFFFF'}, 300);
        
        /* saving default color of photo background to profile */
	if($('.saveDefaultColor').length>0) {

    	    $.post(conf.cSiteUrl+'/setsetting', { 'default_color': 'black'});

	}

        return false;
    });

    $('#bgChanger .blue').live('click',function() {

        $('#photoLargeView').animate({backgroundColor:'#00A3F5'}, 800);
        $('#photoLargeView').animate({color:'#FFFFFF'}, 300);
        
        /* saving default color of photo background to profile */
	if($('.saveDefaultColor').length>0) {

    	    $.post(conf.cSiteUrl+'/setsetting', { 'default_color': 'blue'});

	}

        return false;
    });

    /* adding frejks */
    $('.showFrejks').click(function(el) {
        

        var that = this;
        var frejkVal    = $('.frejkInput').val().toString();
        var frejkAdd;
        
        $('.frejkInput').keyup(function() {
        
    	     frejkAdd = $(this).val();
        
        }).keyup();
        
        function processFrejkJson(data) {

          if(data.ifOk) {

              $('.frejkModInput').html(l.thanks);
              var frejkOldVal = parseFloat($('.frejkNum').html());
              var frejkNewVal = parseFloat(frejkOldVal-(frejkAdd*5));

              var obj = $.create('div',
                        {'id':'messageWindow', 'title':l.comm}, []
              );

              $(obj).append('<h2>'+ l.comm +'</h2><div class="modalContainer"><strong class="colorPink">'+data.message +'</strong><p class="marginTop">'+ l.votesNum + ' <strong>'+ data.votes +'</strong></p><p> '+ l.frejksNum +' <strong>'+ data.frejks+'</strong></p></div><div class="modalButtons"><span class="bold modal-close btnGrey">OK</span></div>');

	      $.modal.close();
              $.modal($(obj),{opacity: 80, maxWidth: 450, onShow: function() {
              
		            $('.modal-close').click(function() {

                              if($('.site-compet-running').length>0) {

                                  location.reload(true);

                              } else {

				    $.modal.close();
				    $('.frejkNum').html(frejkNewVal);
                                    $('.incVotes').empty().text(data.votes);
                                    $('.votes .incPlace').empty().text(data.place);
                                    $('.votes').fadeOut(400).fadeIn(300);
                              }

                              });
              
              
              }});

          } else {

              $.modal.close();
	      iModal(l.comm, data.message, '<span class="bold modal-close btnGrey">OK</span>', this);

          }

        }(that, frejkAdd);

        var options = {
            dataType:  'json',
            beforeSubmit: function() { $('.frejkModInput form').html('<p class="preloader-form">'+ l.wait +'</p>') },
            success:   processFrejkJson
        };

        var pID = this.rel;

        $.modal($('#modal-frejk-adding'), {opacity: 80, maxWidth: 450, onShow: function() {

            $('.modal-close').click(function() {

                $.modal.close();

            });

            $('.frejkMore form').validate({
                submitHandler: function(form) {
	            $(form).ajaxSubmit(options);
                },
                rules: {
                    frejk: {
                        required: true,
                        digits: true
                    }
                },
                messages: {
                    frejk: {
                        digits: l.v_numeric_short,
                        required: l.v_required_short
                    }
                }
           });

    }});

        return false;

    })

/* scrolling to level in running compet */

if($('.site-compet-running').length>0) {

  if($('.site-compet-running').attr("rel")=="1") {

    if(__global_chrome) {
	$('body').animate({ scrollTop: 650 }, 1300);
    } else {
	$('html').animate({ scrollTop: 650 }, 1300);
    }

  } else if($('.site-compet-running').attr("rel")=="2") {

    if(__global_chrome) {
	$('body').animate({ scrollTop: 540 }, 1300);
    } else {
	$('html').animate({ scrollTop: 540 }, 1300);
    }


  } else if($('.site-compet-running').attr("rel")=="3") {

    if(__global_chrome) {
	$('body').animate({ scrollTop: 430 }, 1300);
    } else {
	$('html').animate({ scrollTop: 430 }, 1300);
    }
    
  }

}

if($('.site-compet-future').length>0) {

  $('body').animate({ scrollTop: 620 }, 1300);

}

/* ajax comment adding */
if(!isIE6) {

    if($('#photoCommentForm').length>0) {

    $("#photoCommentForm").validate({
        errorElement: 'em',
        rules: {
                'comment[comment]': {
                    required: true
                }

        },
        messages: {
                'comment[comment]': {
                    required: l.v_required
                }

        }
    });

    function processJson(data) {
        if(data.ifOk == true) {

            $("#photoCommentFormBox").animate({height:'60px'}, 550);
            $("#photoCommentsList ul").prepend(data.body).fadeIn('slow');
            $("#photoCommentForm").html("<p class='message message-notice'>"+ l.addComm +"</p>")
            $("#photoCommentsList .noComments").remove();

        }

        if(data.ifOk == false && data.message) {
          iModal(l.comm, data.message, '<span class="bold modal-close btnGrey">OK</span>', this);
          $('.preloader-form').remove();
        }

    }

    var options = {
        dataType:  'json',
        success: processJson,
        beforeSubmit: function() { if($('p.preloader-form').length==0) { $('.submitWrapper').append('<p class="preloader-form">'+ l.wait +'</p>') } }
    };

    $('#photoCommentForm').ajaxForm(options);

    }
    
    
    /* text ajax comments */
    
    if($('#textCommentForm').length>0) {

    $("#textCommentForm").validate({
        errorElement: 'em',
        rules: {
                'comment[comment]': {
                    required: true
                }

        },
        messages: {
                'comment[comment]': {
                    required: l.v_required
                }

        }
    });

    function processJsonText(data) {
        if(data.ifOk == true) {


            $("#textCommentFormBox").animate({height:'60px'}, 550);
            $("#textCommentsList ul").prepend(data.body).fadeIn('slow');
            $("#textCommentForm").html("<p class='message message-notice'>"+ l.addComm +"</p>")
            $("#textCommentsList .noComments").remove();

        }

        if(data.ifOk == false && data.message) {
          iModal(l.comm, data.message, '<span class="bold modal-close btnGrey">OK</span>', this);
          $('.preloader-form').remove();
        }

    }

    var optionsText = {
        dataType:  'json',
        success: processJsonText,
        beforeSubmit: function() { if($('p.preloader-form').length==0) { $('.submitWrapper').append('<p class="preloader-form">'+ l.wait +'</p>') } }
    };

    $('#textCommentForm').ajaxForm(optionsText);

    }    

}

/* -----------------------------------------------------------------*/
/* -----------------------------------------------------------------*/
/* weird bug with remembering password in Mozilla
*  input with NIP gets user e-mail, then goes into bad valiation
*  kind of workaround ...*/
/* -----------------------------------------------------------------*/
/* -----------------------------------------------------------------*/

if($('#userSettings_nip').length>0) {

    if($('#userSettings_nip').val().indexOf('@')!=-1) {

        $('#userSettings_nip').val(' ');

    }

}

/* photo upload progress bar */

$('#upload_form').submit(function() {

    $('#progressbar').progressbar({value: 100});

    $.modal($('#modal-dialog-progress'), {opacity: 80, maxWidth: 600, onShow: function() {

            $('.modal-close').click(function() {

                $.modal.close();
                
                return false;

            });

    }});

    return true;

});

/* photo large view options effect */
//if($('#photoLargeView .moreInfo').length>0) {

    $('#photoLargeView .moreInfo').live('mouseenter', function() {
    
	$(this).animate({'opacity': '1.0'}, 500);
    
    });
    
    $('#photoLargeView .moreInfo').live('mouseleave', function() {
    
	$(this).animate({'opacity': '0.6'}, 500);
    
    });

//}

/* slider gallery for photo view */
var container = $('div.sliderGallery');
            var ul = $('ul', container);
            
            var itemsWidth = ul.innerWidth() - container.outerWidth()+30;
            
            var active     = $('.sliderGallery .active');
            var activePos  = parseInt(active.attr("offsetLeft"))-parseInt(440);            
            
            $('.slider', container).slider({
                min: 0,
                max: itemsWidth,
                stop: function (event, ui) {
                    ul.animate({'left' : ui.value * -1}, 500);
                },
                slide: function (event, ui) {
                    ul.css('left', ui.value * -1);
                }
                
            
	    });

	    $('.slider', container).slider("value",activePos);
	    ul.css('left', "-" + $('.slider', container).slider("value") + "px");


//fr.activeDefault();

/* texts events */
if($('textarea#text_body').length>0) { 
    $.ckeditor.config = {path: public_path("js/ckeditor/"), height:300 }; 
    $('#text_body').ckeditor({ 
      toolbar: 'text',
      height: 350,
      width: 966,
      filebrowserUploadUrl: public_path('upload/ckeditor')
    });
}

if($('textarea#userSettings_partner_message').length>0) { 
    $.ckeditor.config = {path: public_path("js/ckeditor/")}; 
    $('#userSettings_partner_message').ckeditor({ toolbar:'partnerAd', height:100, width:725 }); 
}

function validateText() {

/* text form validate */
$("#form-editText").validate({
          errorElement: 'em',
          errorPlacement: function(error, element) {
        	error.appendTo( element.parent().parent() );
          },
          rules: {
          'text[is_own]': {
              required: true
          },
          'text[title]': {
              required: true
          },
          'text[summary]': {
              required: true
          }

          },
          messages: {
          'text[is_own]': {
              required: l.v_required
          },
          'text[title]': {
              required: l.v_required
          },
          'text[summary]': {
              required: l.v_required
          }
          
          }
          
          });
}

/* saving text */
if($('#save_text').length>0) {

	$('#save_text').live('click', function(event) {

	$('#form-editText').append('<input type="hidden" name="save" value="1" id="save-hidden">');
	
	if($('#form-editText').valid()) {
          
              $('#preloader').empty().html('<p class="preloader-form">'+ l.wait +'</p>');

              var optionss = {
                  success: function(datas) {

                      if(datas.ifOk) {

                        $('#save-hidden').remove();
                        $('#preloader').empty();
                        $('#lastSave').show();
                        $('#lastSave span').html(datas.updated_at);
                        $('#text_id').attr('value', datas.id);

                      } else {

//                        $('#save-hidden').remove();
                        iModal(l.comm,l.textSaveError, '<span class="bold modal-close btnGrey">OK</span>');

                      }

                  },
                  dataType:'json'
              };

              $('#form-editText').ajaxSubmit(optionss);

        } else {
	
	$('#form-editText').submit().validate({
          errorElement: 'em',
          errorPlacement: function(error, element) {
        	error.appendTo( element.parent().parent() );
          },
          rules: {
          'text[is_own]': {
              required: true
          },
          'text[title]': {
              required: true
          },
          'text[summary]': {
              required: true
          }

          },
          messages: {
          'text[is_own]': {
              required: l.v_required
          },
          'text[title]': {
              required: l.v_required
          },
          'text[summary]': {
              required: l.v_required
          }
          
          }});
          
        }

	event.preventDefault();

});


$('#preview_text').live('click', function(event) {

	$('#form-editText').append('<input type="hidden" name="save" value="1" id="save-hidden">');

	if($('#form-editText').valid()) {
	
	var options = {
    	    success: function(datas) {

			if(datas.ifOk) {
	                    $('#save-hidden').remove();
			    $('#text_id').attr('value', datas.id); 
			    window.open(datas.text_url);
			
			} else {
	
				iModal(l.comm,l.textSaveError, '<span class="bold modal-close btnGrey">OK</span>');
			
			}

    	    
    	    },
    	    dataType:'json'
        }; 

	$('#form-editText').ajaxSubmit(options);
	
	} else {
	
	$('#form-editText').submit().validate({
          errorElement: 'em',
          errorPlacement: function(error, element) {
        	error.appendTo( element.parent().parent() );
          },
          rules: {
          'text[is_own]': {
              required: true
          },
          'text[title]': {
              required: true
          },
          'text[summary]': {
              required: true
          }

          },
          messages: {
          'text[is_own]': {
              required: l.v_required
          },
          'text[title]': {
              required: l.v_required
          },
          'text[summary]': {
              required: l.v_required
          }
          
          }});
        
	
	}

	event.preventDefault();
	
	});

}

/* printing text */
if($('#printText').length>0) {

    $('#printText').click(function(event) {
    
	window.print();
	
	event.preventDefault();
    
    });

}

/* system console */

if($('#notifShow').length>0) {


/* showing ajax latest notifications */

$("#notifShow").click(function() {

       $(this).toggleClass('active');

       var userId       = $('#notifShow').attr("rel"); 
       //$('.user-waiter').empty();
       //$("#userList .list").empty();
       $('#notifList ul').empty().html('<p class="preloader-form">'+ l.wait +'</p>');
       $("#notifList").slideToggle("fast");


//            $('#notifList ul').

            $.ajax({
                type: "POST",
                url: conf.cSiteUrl+'/ajax/dashboard/get',
                data: {'user_id': userId, 'limit': '30', 'dashboard': '2'},
                dataType: "html",
                success: function(html){
                    //$('.user-waiter').empty();
                    if(html!="") {
                	$("#notifList ul").html(html)
                	//t();
                    } else { /*t();*/ }
                }

            })

       //$('#statusSetter form textarea').focus();

//       $('#content').click(function() {

            //$("#statusSetter").slideToggle();

//       });

       return false;

    });

/* getting periodical last notification for console */

function getPeriodicalNotif() {

        var userId       = $('#notifShow').attr("rel"); 
        var lastId	 = $('#notifOne li:first-child').attr('id');
	
	$.ajax({
	    type: 'POST',
	    url: conf.cSiteUrl+'/ajax/dashboard/get',
	    dataType: 'html',
	    data: {'user_id': userId, 'limit': '1', 'newer_than': lastId, 'dashboard': '2'},
	    success: function(html) {
		if(html!="") {
		    $('#notifOne').empty().html(html);
		    
		    $('.notifBar').animate({ 'opacity': "0.1"}, 1000, function() {
    
			$('.notifBar').animate({ 'opacity': "1.0"}, 600);
    
		    });
		} 
	    }
        });
    }

    var holdIntervalNotif = setInterval(getPeriodicalNotif, 25000);

}

/* AJAX status setter */

    var optionsSetter = {
            success:   function() {

                $('.form-waiter').empty();
                $("#statusSetter").slideUp();
                var newStatus = $('#statusSetter form textarea').val(); $('#statusFrag span.stat').text(newStatus);
                $('#actualStatus').attr("class", "");
                
                
                var actualStatus = $("input[name='status']:checked").val();
                
                if(actualStatus==1) {
                
            	    $('#actualStatus').addClass('status-online');
            	    $('#statusFrag').empty().html("Online");
                
                } else if(actualStatus==2) {
                
            	    $('#actualStatus').addClass('status-away');
            	    $('#statusFrag').empty().html(l.statusAway);
                
                } else if(actualStatus==3) {
                
            	    $('#actualStatus').addClass('status-invisible');
            	    $('#statusFrag').empty().html(l.statusInv);
                
                } else {
                
        	    $('#actualStatus').addClass('status-offline');
        	    $('#statusFrag').empty().html("Offline");
                
                }
                                

            },
            beforeSubmit: function() {

                if($('#statusSetter form textarea').val().length>120) {

                    $('.form-waiter').empty();
                    alert(l.s_maxlength);
                    $('#statusSetter form textarea').focus();
                    return false;

                }

            }
        };

    /* AJAX form submiting for status */
    $('#statusSetter form').ajaxForm(optionsSetter);

    /* AJAX user list at console */
    $("#userlistShow").click(function() {

       $(this).toggleClass('active');

       $('.user-waiter').empty();
       $("#userList .list").empty();
       $("#userList").slideToggle("fast");


            $('.user-waiter').html('<p class="preloader-status">'+ l.wait +'</p>');

            $.ajax({
                type: "GET",
                url: conf.cSiteUrl+'/ajax/user/friends',
                dataType: "html",
                success: function(html){
                    $('.user-waiter').empty();
                    $("#userList .list").append(html)
                }

            })

       return false;

    });

/* new message modal */
if($('#console').length>0) {

    $('#console .newMesg').live('click', function(event) {
    
    $.modal.close();
    
    var nick = $(this).attr('rel');
    
    $("#userList").slideToggle("fast");
    
    if($('#notifList').is(':visible')) {
	$("#notifList").slideToggle("fast");
    }

    $.modal('<h2>'+ l.newMessage +'</h2><div class="modalContainer"><p class="preloader-form">'+ l.wait +'</p></div>', {opacity: 80, autoResize: true, maxWidth: 550, onShow: function(dialog) {

    $.ajax({
      type: "GET",
      url: conf.cSiteUrl+'/'+ conf.cLang +'/user/'+nick+'/message',
      dataType: "html",
      success: function(html){


          $('.modalContainer').html(html);
          //userTooltip();

          $("#newMessage_form").validate({
          errorElement: 'em',
          rules: {
          'email[mail]': {
              required: true,
              email: true
          },
          'email[message]': {
              required: true
          },
          'private_message[subject]': {
              required: true
          },
          'private_message[body]': {
              required: true
          }

          },
          messages: {
          'email[mail]': {
              required: l.v_required,
              email: l.v_emailMail
          },
          'email[message]': {
              required: l.v_required
          },
          'private_message[subject]': {
              required: l.v_required
          },
          'private_message[body]': {
              required: l.v_required
          }


          },submitHandler: function(form) {

              $('#newMessage_form .form-waiter').empty().html('<p class="preloader-form">'+ l.wait +'</p>');

              var options = {
                  success: function(datas) {

                if(datas.ifOk) {

                    //$('.modalContainer').html(l.thanks);
                    $.modal.close();
                    iModal(l.comm, l.mesgSent, '<span class="bold modal-close btnGrey">OK</span>', '');

                }

              },
              dataType:'json'
              };

              $(form).ajaxSubmit(options);


        }
        });

    }
    });

    }});

    event.preventDefault();
    
    });

    /* adding favourites external */
    $('#console #favFormShow').live('click', function(event) {
    
    $.modal.close();
        
    $.modal('<h2>'+ l.newFav +'</h2><div class="modalContainer"><p class="preloader-form">'+ l.wait +'</p></div>', {opacity: 80, maxWidth: 550, onShow: function(dialog) {

    $.ajax({
      type: "GET",
      url: conf.cSiteUrl+'/ajax/favourites/newExternal',
      dataType: "html",
      success: function(html){

          $('.modalContainer').html(html);

          $("#newFav_form").validate({
          errorElement: 'em',
          rules: {
          'favourite[external_url]': {
              required: true,
              maxlength: 300
          },
          'favourite[external_description]': {
              required: true
          }
          },
          messages: {
          'favourite[external_url]': {
              required: l.v_required,
              maxlength: l.v_maxlength300
             
          },
          'favourite[external_description]': {
              required: l.v_required
          }
          
          },submitHandler: function(form) {

              $('#newFav_form .form-waiter').empty().html('<p class="preloader-form">'+ l.wait +'</p>');

              var options = {
                  success: function(datas) {

                if(datas.ifOk) {

                    $.modal.close();
                    iModal(l.comm, 'Favourite has been added successfully.', '<span class="bold modal-close btnGrey">OK</span>', '');

                }

              },
              dataType:'json'
              };

              $(form).ajaxSubmit(options);


        }
        });
    
    }
    });

    }});

    event.preventDefault();
    
    });




}

/* ajax friends search */

if($('#searchFriendWizard').length>0) {

    $('#searchFriendWizard').submit(function(event) {
    
	    $.ajax({
                type: "GET",
                url: conf.cSiteUrl+'/pl/friend_search',
                data: { 'query': $('#searchFormText').val() },
                dataType: "html",
                beforeSend: function() {
                
            	    $('#results').html('<p class="preloader-form">'+ l.wait +'</p>');
                
                },
                success: function(html){
                    $('#results').empty().html(html);
                    //userTooltip();
                }

            })
            
            event.preventDefault();
    
    });

}

/* nick color picker */
if($('.f-nickColor').length>0) {

    $('#chooseColor, .f-nickColor').ColorPicker({ 
    
    onChange: function (hsb, hex, rgb) {
        $('#chooseColor').css('backgroundColor', '#' + hex);
        $('.f-nickColor').val(hex);
    }

    });

}

/* reporting terms violation */
$('.report-term').live('click', function(ev){

    $.get($(this).attr("href"))

    $(this).parent().html(l.thanks).addClass('icoSuccess marginLeft');

    ev.preventDefault();

});

/* blink text function */
function makeBlink(el) {

    $(el).animate({ 'opacity': "0.2"}, 800, function() {
    
	$(el).animate({ 'opacity': "1.0"}, 800, function() {
	
	    makeBlink(el);
	
	});
    
    });
    
}


/* blinking when new - system console */
if($('.blink').length>0) {

    $.each($('.blink'), function() {
    
	//makeBlink(this);
    
    });

    

}

/* limit chars */
if($('#userSettings_about_me').length>0) {
    $('#userSettings_about_me').keyup(function() {

	limitChars('userSettings_about_me', 255, 'aboutRemaining')

    });
}

if($('#userSettings_hobby').length>0) {

    if($('.site-settings').attr('rel')!="soliver-true") {

    $('#userSettings_hobby').keyup(function() {

	limitChars('userSettings_hobby', 350, 'hobbyRemaining')

    });
    
    }

}

/* date picker */
if($('.date-picker').length>0) {
    $('.date-picker').datepicker({dateFormat: 'yy-mm-dd', buttonText: 'Wybierz', showOn: 'button', buttonImage: public_path('images/icons/icoCalendar.png'), buttonImageOnly: true});
}

/* resize container on href method */

$.resizeContainer = function(elem,target) {

    var _t = target;
    var _e = elem;
    var _o = parseFloat(elem.width());
    var _s = parseFloat(_t.width());
    var _r = _s-_o;

    // mouseenter effect
    elem.mouseenter(function(event) {

	_t.animate({width: _r},200);
	_e.animate({opacity: 1.0},200);
    
    });
    
    // mouseleave effect
    elem.mouseleave(function(event) {

	_t.animate({width: _s},200);
	_e.animate({opacity: 0.6},200);
    });
    
    
};

/* activate dashboard profile hovers 
* resize entry when buttons are hovered;
*/
/*$.each($('.dashboard-profile ul li'), function(idx,val) {

    $.resizeContainer($(val).find('.userOptions'), $(val).find('.data'));

});*/
//$.resizeContainer($('.dashboard-profile ul li .userOptions'), $('.dashboard-profile ul li .data'));

/* turn on text validation */

validateText();

})

