$(document).ready(function() {
    //$('textarea.wysiwyg').wysiwyg({ css : '/media/css/wysiwyg.css' });
    textareaWysiwyg('textarea.wysiwyg');
/*
    $('textarea.wysiwyg').tinymce({
        // Location of TinyMCE script
        script_url : '/media/js/jquery.tinymce/tiny_mce.js',

        // General options
        theme : "advanced",
        plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,|,pastetext,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        //theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        //theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        //content_css : "css/content.css",

    });
*/
    
    // prozatimni reseni spatne fungujiciho Wysiwyg editoru v Editaci profilu -> NEUKLADAL, pouze po kliku
    $('#saveProfileInfo').click(function() {
        $('#cv').html($('.iframe').contents().find('body').html().replace(/<br>/ig, "\n")); //return false;
    });
    $('#saveProfilePoliticalInfo').click(function() {
        $('#political_profile').html($('.iframe').contents().find('body').html().replace(/<br>/ig, "\n")); //return false;
    });
    
    
    // povoleni poli v ProfileEdit pri stisknuti F5
    $('form#profile-edit #user-resort').removeAttr('disabled');
    $('form#profile-edit input#user-resort-button').removeAttr('disabled');

    // efekt zobrazeni kolik procent je stavajici pocet hlasu v jednotlivych sloupcich ankety
    $('.poll-status a').hover(
        function() {
            $('.poll-status a b').hide();
            $('.poll-status a i').show();
        },
        function() {
            $('.poll-status a b').show();
            $('.poll-status a i').hide();
        } 
    );
/*
    // zobrazeni Tooltipu u prvku se tridou class="tips"
    $('.tooltip').bt({
        fill: '#F7F7F7', 
        strokeStyle: '#B7B7B7', 
        spikeLength: 10, 
        spikeGirth: 10, 
        padding: 8, 
        cornerRadius: 0, 
        positions: 'right',
        cssStyles: {
            fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
            fontSize: '11px'
        }
    });*/

    // zobrazeni login popup okna po kliknuti na "Muj profil", pokud neni uzivatel prihlasen
    $('#loginButton').click(function() {
        $('#login-dialog').slideToggle('fast');

        return false; 
    });

/*
	var zIndexNumber = 1000;
	$('div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
*/
/*
    // kontrola aby se neslo prihlasit s nekorektnimi daty
    $('#login-dialog form').submit(function(event) {
        var errors = false;
        if($('#login-dialog input.email').val() == 'Email' || $('#login-dialog input.email').val() == '') { errors = true; }
    });

    // skryvani helptextu v login formulari
    $('#login-dialog input.email').focus(function() {
        if(this.value == 'Email') {
            this.value = '';
        }
    });
    $('#login-dialog input.email').blur(function() {
        if(this.value == '') {
            this.value = 'Email';
        }
    });
    $('#login-dialog input.password').focus(function() {
        if(this.value == 'Heslo') {
            this.type = 'password';
            this.value = '';
        }
    });
    $('#login-dialog input.password').blur(function() {
        if(this.value == '') {
            this.type = 'text';
            this.value = 'Heslo';
        }
    });


    if($("#formErrors").text() != '') {
        $msg = 'Je třeba vyplnit všechny položky.';
        if($("#formErrors #mail-is-registered").text() != '') { $msg = $("#formErrors #mail-is-registered").text(); }
        Boxy.alert($msg, null, {title: 'Nedostatečně vyplněný formulář', draggable:true});
    }
    */
    
    $('#js-login-form label').inFieldLabels();

/*
    // funkce pro kontrulu validity emailove adresy
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }
    */
    // kontrola přihlášní uživatele
    var status=true;
    function checkSignIn() {    

        var response = $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':'signIn'}),
                'dataType': 'json',
                'success': function(response) {
                    
                    if(response.status=='false') {
                        $('<div><p class="box">Nejste přihlášen/a</p></div>').dialog({
                            title: 'Příhlášení',
                            show: 'scale',
                            buttons: {
                                "Registrovat": function() { window.location='/registrace/';  },
                                "Přihlásit": function() { window.location='/prihlaseni/'; },
                                "Zavřít okno": function() { $(this).dialog("close"); } 
                            },
                            draggable: false,
                            resizable: false,
                            modal: true,
                            open: function(){
    						    $(".ui-dialog-buttonpane button:contains('Zavřít okno')").addClass("discard");
						  	},
						    width: 256       
                        });
                        status = false;
                    }
                    
             
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            }); 
            
           return status;          
    }

    // hlasování
    $('.hlasuj').live('click', function() { 
        var what = $(this).attr('id');
        var temp = what.split('_');
        var what_rel = $(this).attr('rel');

        var sign = checkSignIn();
        
        var x = 1;

        if (sign === true) { 
            
            if (what_rel === 'electionDown' || what_rel === 'electionUp') {
                
                var type = 'user_election';
                
                if (what_rel == "electionDown") { x = 1; 
                    
                        $(".op-per-vote-" + temp[3]).attr('rel','electionUp').removeClass("pern-election").addClass("pern-election-checked").attr('title', 'Odebrat permanentní hlas'); 
                        
                        
                    /*tooltip('.op-per-vote-' + temp[3], 'mouseover', 'mouseout');*/
                
                            
                } else if (what_rel == "electionUp") { x = -1; 
                        
                        $(".op-per-vote-" + temp[3]).attr('rel','electionDown').removeClass("pern-election-checked").addClass("pern-election").attr('title', 'Dát permanentní hlas'); 
                       /* tooltip('.op-per-vote-' + temp[3], 'mouseover', 'mouseout');*/
                }
                    
                var before = parseInt($("." + type + "_votes_" + temp[3] + ":first").text()) + x;
                $("." + type + "_votes_" + temp[3]).html(before);
            }
            
            if (what_rel=='') { 

                what_rel = temp[2]; 
                
            }
            
            var status = true;
            
            $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':temp[0], 'id':temp[1], 'vote':what_rel, 'for':temp[3]}),
                'dataType': 'json',
                'success': function(response) {
                    
                    status = response.status;
                    
                    // Pokud nastane chyba vyskočí dialog
                    if (response.status === false) {
                        $("<div>" + response.message + "</div>").dialog({
                            title: 'Dialog',
                            buttons: { "Ok": function() { $(this).dialog("close"); } },
                            draggable: false,
                            resizable: false,
                            modal: true        
                        });
                    }

                    return false;                
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            }).responseText;
                  
            if (status === true) {
         
                if (temp[0] == 'votePetition') {  
                	
                	var url = document.location.href;
                	var title = document.title;
                	
                	$('<div><p class="box">Děkujeme za podepsání petice</p></div>').dialog({
                            title: 'Podpis petice',
                            show: 'scale',
                            buttons: {
                                "Sdílet na Facebook": function() { window.open('http://www.facebook.com/sharer.php?u=' + url, '_blank'); $(this).dialog("close"); },
                                "Zavřít okno": function() { $(this).dialog("close"); } 
                            },
                            draggable: false,
                            resizable: false,
                            modal: true,
                            open: function(){
    						    $(".ui-dialog-buttonpane button:contains('Zavřít okno')").addClass("discard");
						  	},
						    width: 256       
                        });
                	               	
                    $('.' + what).remove();
                    $('.petition' + temp[3] + ' .pencil-gray').switchClass('pencil', 'pencil-gray', 'slow'); 
                    
                    var type = 'petition';
                    
                    var before = parseInt($("." + type + "_votes_" + temp[3] + ":first").text()) + x;
                    $("." + type + "_votes_" + temp[3]).html(before);
                }
                
                if (temp[0] == 'voteTopic') {  
                    /* $('.topic' + temp[3] + ' .tooltip').qtip('hide');*/
                     $('#' + what).remove();
                     $('.topic' + temp[3] + ' .fire-gray').switchClass('fire', 'fire-gray', 'slow'); 
                }
                
                // Při hlasování 
                if (temp[0] == 'voteUser') {
                    
                    /*$('#thumbs-opinion-' + temp[1] + ' .tooltip').qtip('hide');*/
                                    
                    if(temp[2] == 'down') {
                        $($(this).parent()).html('<span class="thumb-up-gray tooltip" title="Palec nahoru - už bylo hlasováno">Palec nahoru</span><span class="thumb-down tooltip" title="Palec dolů - už bylo hlasováno">Palec dolů</span>');
                    }
                    
                    if(temp[2] == 'up') {
                        $($(this).parent()).html('<span class="thumb-up tooltip" title="Palec nahoru - už bylo hlasováno">Palec nahoru</span><span class="thumb-down-gray tooltip" title="Palec dolů - už bylo hlasováno">Palec dolů</span>');
                    }
                    
                    // Zrefreshování tooltipů u nových palců
                    /*tooltip('#thumbs-opinion-' + temp[1] + ' .tooltip');*/
                             
                }
                
                // Při hlasování na spam
                if (temp[0] == 'voteOpinion') {
                    
                   /* $('#spam-box-' + temp[3] + ' .tooltip-top').qtip('hide');*/
                                    
                    if(temp[2] == 'down') {
                        $($(this).parent()).html('<span class="spam-yes-gray tooltip-top" title="Nahlásit autora jako jedinečnou osobnost se zajímavými názory - už bylo hlasováno">Ano</span><span class="spam-no tooltip-top" title="Nahlásit autora za vulgární, rasistický či neetický obsah - už bylo hlasováno">Ne</span>');
                    }
                    
                    if(temp[2] == 'up') {
                        $($(this).parent()).html('<span class="spam-yes tooltip-top" title="Nahlásit autora jako jedinečnou osobnost se zajímavými názory - už bylo hlasováno">Ano</span><span class="spam-no-gray tooltip-top" title="Nahlásit autora za vulgární, rasistický či neetický obsah - už bylo hlasováno">Ne</span>');
                    }
                    
                    // Zrefreshování tooltipů u nových palců
                   /* tooltip('#spam-box-' + temp[3] + ' .tooltip-top', 'mouseover', 'mouseout', 'top');*/
                             
                }
                
               
            }
         }
        
        return false;        
    
    });
    
    // hlasování
    $('.confirm').live('click', function() {
        
        var sign = checkSignIn();
        if (sign === true) {
                    
            var what_id = $(this).attr('id');
            var what_rel = $(this).attr('rel');
            
            var temp = what_id.split('_');
            
            var title = '';
            var text = '';
            
            if (temp[0] == 'votePetition') { 
                title = 'Podepsat petici';
                text = 'Opravdu chcete podepsat petici?';
            } else if (temp[0] == 'voteUser') {
                if (what_rel == 'electionDown') {
                    title = 'Dát hlas';
                    text = 'Opravdu chcete dát hlas?';
                } else {
                    title = 'Vzít hlas';
                    text = 'Opravdu chcete vzít hlas?'; 
                }
            } else {
                title = 'Hlas';
                text = 'Opravdu chcete dát hlas?';   
            }
            
            $('<div><p class="box">' + text + '</p></div>').dialog({
                            title: title,
                            show: 'scale',
                            buttons: {
                                "Ano": function() { 
                                    sendVote(what_id,what_rel); 
                                    $(this).dialog("close");  
                                    
                                    if (temp[0] == 'votePetition') {  
                                        $('#' + what_id).remove();
                                        $('.petition' + temp[3] + ' .pencil-gray').switchClass('pencil', 'pencil-gray', 'slow'); 
                                    }
                                                                
                                    /*$('.tooltip').qtip('hide'); */
                                },
                                "Ne": function() { $(this).dialog("close"); } 
                            },
                            draggable: false,
                            resizable: false,
                            modal: true,
                            open: function(){
        						$(".ui-dialog-buttonpane :button:contains('Ne')").addClass("discard");
    						  						},
    						width: 256
            
                        });
        }
        
        
        return false;
    
    });
    
    // přidávací box
    $('.add').live('click', function() {
        var what = $(this).attr('id');
        var title = $(this).attr('title');
        var toggle = false;
        
        var temp = what.split('_');
        
        // Kontrola jestli uživatel je přihlášen. Pokud ne, tak se zobrazí dialog pro přihlášení.
        var sign = checkSignIn();
        
        if (sign === true) { 
        
        var htmlButton = '';
            
        // Měnění button u titulku
        if ($(this).hasClass('button-big-red')) { htmlButton = title; toggle = true; } else { htmlButton = 'Zavřít'; }
        $(this).html('<span>' + htmlButton + '</span>').toggleClass('button-big-red');
        
        // Pokud je formulář otevřen, tak se jenom zavře a nebude se získávat formulář
        if(toggle === true) { $('#add-box').slideToggle(); return false; }
                    
            var response = $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':'add', 'what':temp[0], 'other':temp[1]}),
                'dataType': 'json',
                'success': function(response) {
                    
                    $('#add-box').html(response.message).slideToggle();

                    return false;                
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            });
         }   
         
         return false;     
    });
    
    // zavíraní box
    $('.close').live('click',function() {
        
        $(this).parent().slideUp();
        
        return false;
    });
    

/********
    =Přidávací formulář
*/ 
    
    $('.add-form').live('submit',function() { 

        $(this).ajaxSubmit({
            'url': '/ajax',
            'dataType': 'json',
            'beforeSubmit': function(formData, jqForm, options) {
                $("#validateForm").validate();
                
                var val = $('#validateForm').valid();
                if (val === false) { return false; }
                else { return true; }
            },
            'success': function(responseText, statusText) {
                
                    $('#add-box').html(responseText.message).effect('highlight','',1500); 
                    
                    // Pokud se text má přidat ještě 
                    if(responseText.box != 'null') { 
                        $('#inside-text').prepend(responseText.box); 
                        $('#' + responseText.id).effect('highlight','',3000);
                    }
                    
            }
        }); 

        return false; 
    });
    
    $('.validateForm').validate();

    $('.ui-dialog-buttonpane button:contains("Ne")').addClass('discard'); 
    
    function sendVote(what, what_class) {
        
        var temp = what.split('_');
        
        if (what_class==='') { 

            what_class[0] = temp[2]; }
                
        var response = $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':temp[0], 'id':temp[1], 'vote':what_class, 'for':temp[3]}),
                'dataType': 'json',
                'success': function(response) {
                    
                    // Pokud nastane chyba vyskočí dialog
                    if (response.status === false) {
                        $("<div>" + response.message + "</div>").dialog({
                            title: 'Dialog',
                            buttons: { "Ok": function() { $(this).dialog("close"); } },
                            draggable: false,
                            resizable: false,
                            modal: true        
                        });
                    }

                    return false;                
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            }).responseText;

        return eval('(' + response + ')');
    
    }
    
    $("a[rel^='prettyPhoto']").prettyPhoto({
        animationSpeed: 'normal', /* fast/slow/normal */
        padding: 40, /* padding for each side of the picture */
        opacity: 0.35, /* Value betwee 0 and 1 */
        showTitle: true, /* true/false */
        allowresize: true, /* true/false */
        counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
        theme: 'dark_rounded' /* light_rounded / dark_rounded / light_square / dark_square */
    });
    
    
    $(".filter select").live("change", function() {
        var main = $(".main-filter").val();
        var orderBy = $(".order-by").val();
        var league = $('.league').val();
        var what = $(".filter").attr("id").split('_');
        var department = $(".departments").val();
        var type = $('.type').val();
        var availability = $('.availability').val();

        
        var response = $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':what[0], 'main':main, 'orderBy':orderBy, 'department':department, 'league':league ,'other':what[1], 'typeofopinion':type, 'availability':availability }),
                'dataType': 'json',
                'success': function(response) {
                    
                    $(".box-" + what[0]).html(response.message);
                    /*tooltip('.tooltip', 'mouseover', 'mouseout');*/
                    
                    
                    return false;                
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            });
                
        return false;
    });

    /********************************************************************************************************************
     * EDITACE PROFILU
     */

    // policko Funkce a jeho zavislost na Funkce jina
    $('form#profile-edit select#political_post').change(function() {
         var selected = $('form#profile-edit select#political_post option:selected');
         if(selected.val() === 0) {
            $('form#profile-edit input#political_post_other').show();
         }
         else {
            $('form#profile-edit input#political_post_other').hide();
         }
    });

    $('form#profile-edit #user-resort-fields a.user-resort-close').live("click", function(event){
        var option = $(this).attr('id').split('|');
        $('form#profile-edit #user-resort-fields #user-resort-box-'+option[0]).remove();

        if($('form#profile-edit #user-resort option').val() === '') {
            $('form#profile-edit #user-resort option').remove();
            $('form#profile-edit #user-resort').removeAttr('disabled');
            $('form#profile-edit input#user-resort-button').removeAttr('disabled');
        }

        $('form#profile-edit #user-resort').append('<option value="'+option[0]+'" selected="selected">'+option[1]+'</option>');

        return false;
    });


    // formular ProfileEdit
    $('form#profile-edit input#user-resort-button').click(function(event) {
        var selected = $('form#profile-edit #user-resort option:selected');
        if(selected.val()) {
            $('form#profile-edit #user-resort-fields').prepend('<table id="user-resort-box-'+selected.val()+'"><tr><td><label for="user-resort-'+selected.val()+'">'+selected.text()+'</label></td><td><textarea id="user-resort-'+selected.val()+'" name="user-resort['+selected.val()+']"></textarea></td><td><a href="#" class="user-resort-close red-button input width-auto" id="'+selected.val()+'|'+selected.text()+'">Odebrat</a></td></table>');
            $('form#profile-edit #user-resort-fields textarea#user-resort-'+selected.val()).focus();
            selected.remove();
            
            if(!$('form#profile-edit #user-resort option').val()) {
                $('form#profile-edit #user-resort').append('<option value="" selected="selected">žádný další</option>');
                $('form#profile-edit #user-resort').attr('disabled', 'disabled');
                $('form#profile-edit input#user-resort-button').attr('disabled', 'disabled');
            }
        }
        else {
            // no
            alert('Chyba: kontaktuje administrátora.');
        }
    });

    $('#query_users').html("<input type='text' name='que' id='query' class='required' /><input type='hidden' value='' name='opinion_id' id='user_id' />");
    $('#query').autocomplete({
        serviceUrl: '/ajax/',
        minChars: 2,
        params: { action: 'query_users' },
        onSelect: function(value, data) { $('#user_id').attr('value', data); }          
    });
    

    $('.tab-ajax').click(function() {
                    
        var me = $(this);
        
        $('#tabs ul li').removeClass('active');
        $(me).parent().addClass('active');
                    
        temp = me.attr('id').split('_');
        
        showPage(temp,'tab_text');
        
        try {
            $('#search-people').attr("value", "");            
            $('.filter-form')[0].reset();
	        $('#reset-search').hide();
            $('#loader').hide();
        } catch(e) {
            
        }
        
        return false;
    });
    
    var timeout_var;
    
    $('#search-people').keyup(function() {
    	if ($(this).val().length >= 3) {

    	        if(timeout_var) { clearTimeout(timeout_var); }
    	        
        	    timeout_var = setTimeout(function() {

            	    var template = $('#inside-text').attr('class');
            	                		
            		 var response = $.ajax({
                        'type': 'POST',
                        'url': '/ajax',
                        'data': ({action: 'query_people', searchterm: $('#search-people').val(), tpl: template}),
                        'dataType': 'json',
                        'beforeSend': function() {
            		        $('#reset-search').hide();
                            $('#loader').show();
                        },
                        'success': function(response) {
                            $('#inside-text').hide();
            		        $('.pages').hide();
                    		$('#search-box').show();
                 			$('#search-box').html(response.message);
        
                            return false;                
                        },
                        'complete': function() {
                            $('#loader').hide();
            		        $('#reset-search').show();
                        },
                        'error': function(XMLHttpRequest, textStatus, errorThrown) {
                            alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                            return false;
                        }
                    });
            		
              },1000);

	    } else {
    		$('#search-box').hide();
    		$('#inside-text').show();
	        $('#reset-search').hide();
    		$('.pages').show();
    	}
    	
    	if ($(this).val().length = 0) {
	        $('#reset-search').hide();
	    }
    	
    	return false;
    });
    
    $('#reset-search').click(function() {
        $('#search-people').attr("value", "");    
        $('#reset-search').hide();  
		$('#search-box').hide();
		$('#inside-text').show();
		$('.pages').show();
		
		return false;
    });
        
    /*tooltip('.tooltip', 'mouseover', 'mouseout');*/
    /*tooltip('.tooltip-input', 'focus', 'unfocus');*/
    /*tooltip('.tooltip-top', 'mouseover', 'mouseout', 'top');*/
    
    $('.switcher a').click(function() {
    	
    	var rel = $(this).attr("rel");
    	var id = $(this).parents('div:eq(1)').attr('id');
    	
    	if(rel == 'week-stats') {
    		$('#' + id + ' .week-stats').show();
    		$('#' + id + ' .all-stats').hide();
    	} else {
    		$('#' + id + ' .week-stats').hide();
    		$('#' + id + ' .all-stats').show();
    	}
    	
    	$('#' + id + ' .switcher a').removeClass('active');
    	$(this).addClass('active');
    	
    	return false;
    	
    });
    
    
    $('.show-more-petitions-signs').click(function() {
        
        var htmlButton = '';
        
        // Měnění button u titulku
        if ($(this).hasClass('button-big-red')) { htmlButton = $(this).attr('title'); } else { htmlButton = 'Zavřít podpisy'; }
        $(this).html('<span>' + htmlButton + '</span>').toggleClass('button-big-red');
        
        $('.who-sign-petition-more').slideToggle();
        
        return false;
    });
    
    $('.page').live("click",function() {
        
        var main = $(".main-filter").val();
        var type = $('.type').val();
        var orderBy = $(".order-by").val();
        var me = $(this);   
                
        var temp = me.attr('id').split('_');
        
        var department = $(".departments").val();
        
        var response = $.ajax({
                'type': 'POST',
                'url': '/ajax',
                'async': false,
                'data': ({'action':temp[0], 'main':main, 'orderBy':orderBy, 'department':department, 'offset':temp[2], 'other':temp[1], 'type':temp[3], 'typeofopinion':type, 'league':temp[4]}),
                'dataType': 'json',
                'success': function(response) {
                    
                    $('.pages li a').removeClass('active');
                    me.addClass('active');
                    $("#inside-text").html(response.message);
                    
                    return false;                
                },
                'error': function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Chyba pri pouziti AJAX. ' + textStatus + ' ' + errorThrown);
                    return false;
                }
            });
         
         $.scrollTo('#inside-text',1500);    
               
        return false; 


    });
    
    FB_RequireFeatures(["XFBML"], function(){ 
        FB.init("db6cf8b53b75cc4ac1ede984ccd66407", "/xd");
    }); 

    $('.fb-disconnect').click( function() {
            var parent = $(this).parent();
        
            var response = $.ajax({
                "type": "POST",
                "url": "/ajax",
                "async": false,
                "data": ({"action":"fb_dis"}),
                "dataType": "json",
                "success": function(response) {
                    if (response.status == 'ok') {
                        $('.fb-disconnect').remove();
                        parent.html('Zrušení partnerství proběhlo úspěšně').effect('highlight','',1500);
                    } 
                    
                    return false;       
                },
                "error": function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Chyba pri pouziti AJAX. " + textStatus + " " + errorThrown);
                    return false;
                }
            });
    
            
        return false;   
    });



}); 

    function showPage(temp,changer) {
      var response = $.ajax({
            'type': 'POST',
            'url': '/ajax',
            'async': false,
            'data': ({'action':temp[0], 'what':temp[1], 'offset':temp[2], 'id':temp[3]}),
            'dataType': 'json',
            'success': function(response) {
                
                $('#' + changer).html(response.message);
               /* tooltip('#' + changer + ' .tooltip', 'mouseover', 'mouseout');*/
               
                
                return false;
            },
            'error': function(XMLHttpRequest, textStatus, errorThrown) {
                alert('Chyba pri pouziti AJAX. ' + textStatus);

                return false;
            }
        }); 
        
        return false; 
        
    }
    
    function up() {
              
          FB.Facebook.get_sessionState().waitUntilReady(function()
          {
          
            FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["uid","sex","first_name","last_name","birthday","current_location","email_hashes"], function(unifoo, ex){
                               
                $(".fb_user").html('Registrační formulář byl předvyplněn údaji z Facebook.com.<br /><span class="silver">Nemusí se nahrát všechny údaje, záleží na nastavení Vašeho Facebook účtu.</span>');
                
                $("#uid").attr('value',unifoo[0]['uid']);
                $("#firstname").attr('value',unifoo[0]['first_name']);
                $("#lastname").attr('value',unifoo[0]['last_name']);
                
                var sex = unifoo[0]['sex'];
                $('select.sex').val(sex).attr("checked","checked");
                
                try {
                    var born = unifoo[0]['birthday'].split(' ');
                    $("#year_of_birth").attr('value',born[2]);
                } catch (err) { }
                
                try {
                   $("#town").attr('value',unifoo[0]['current_location']['city']); 
                } catch (err) { }
                
    
    
    
            });
       });

      }
      
      function tooltip(selector, whenShow, whenHide, where) {
                
          var target = '';
          var tooltip = '';
          
              if(where == 'top') {
                  target = 'topMiddle';
                  tooltip = 'bottomMiddle';
              } else {
                  target = 'rightMiddle';
                  tooltip = 'leftMiddle';
              }
          
              // Notice the use of the each() method to acquire access to each elements attributes
               $(selector).each(function()
               {
                  var content = $(this).attr('title');
                  $(this).attr('title','');
                       
                  $(this).qtip({
                     content: content, // Use the tooltip attribute of the element for the content
                    position: {
                        corner: {
                            target: target,
                            tooltip: tooltip
                        }
                     },
                    style: {
                              border: {
                                 width: 1,
                                 radius: 3,
                                 color: '#231F20'
                              },
                              tip: 'bottomLeft',
                              padding: 2, 
                              textAlign: 'center',
                              background: '#231F20',
                              color: 'white'
                           },
              
                    show: {
                        delay: 0,
                        when: {
                            event: whenShow
                        }
                    },
                    hide: {
                        when: {
                            event: whenHide
                        }
                    }
            
            
                  });
               });
      }
      
  function login() { 
   FB.Facebook.get_sessionState().waitUntilReady(function()
          {
            var response = $.ajax({
                "type": "POST",
                "url": "/ajax",
                "async": false,
                "data": ({"action":"fb"}),
                "dataType": "json",
                "success": function(response) {
                    if (response.status == "redirect") {
                       window.location=response.message;
                    } else { location.reload();  }            
                },
                "error": function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Chyba pri pouziti AJAX. " + textStatus + " " + errorThrown);
                    return false;
                }
            });
    
            
        return false;
    
     
         
     });
  }
  
  function link_fb() { 

   FB.Facebook.get_sessionState().waitUntilReady(function()
          {
            
            var parent = $('.fblog').parent();     
            
            var response = $.ajax({
                "type": "POST",
                "url": "/ajax",
                "async": false,
                "data": ({"action":"fb_link"}),
                "dataType": "json",
                "success": function(response) {
                       if (response.status == "false") {
                           $(".error").html(response.message + "<br />");                     
                       } else {
                           $(".fblog").remove();
                           parent.html('Propojení proběhlo úspěšně').effect('highlight','',1500);
                       }
                       
                       return false;
                },
                "error": function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Chyba pri pouziti AJAX. " + textStatus + " " + errorThrown);
                    return false;
                }
            });
    
            
        return false;
 
     });
  }
  
  function fb_logout() { 

            var response = $.ajax({
                "type": "POST",
                "url": "/ajax",
                "async": false,
                "data": ({"action":"fb_logout"}),
                "dataType": "json",
                "success": function(response) {
                    window.location = "/uvodni-stranka";
                },
                "error": function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Chyba pri pouziti AJAX. " + textStatus + " " + errorThrown);
                    return false;
                }
            });

    
     }
     
 function textareaWysiwyg(what, width, height) {
     $(what).htmlarea({
        // Override/Specify the Toolbar buttons to show
        toolbar: [
            ["bold", "italic", "underline"],
            ["orderedlist","unorderedlist"],
            ["link", "unlink", "|", "image","horizontalrule"]
            /*
            [{
                // This is how to add a completely custom Toolbar Button
                css: "custom_disk_button",
                text: "Save",
                action: function(btn) {
                    // 'this' = jHtmlArea object
                    // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button
                    alert('SAVE!\n\n' + this.toHtmlString());
                }
            }]
            */
        ],

        // Override any of the toolbarText values - these are the Alt Text / Tooltips shown
        // when the user hovers the mouse over the Toolbar Buttons
        // Here are a couple translated to German, thanks to Google Translate.
        toolbarText: $.extend({}, jHtmlArea.defaultOptions.toolbarText, {
                "bold": "Tučné",
                "italic": "Kurzíva",
                "underline": "Podtržené",
                "orderedlist": "Číslovaný seznam",
                "unorderedlist": "Seznam s odrážkami",
                "link": "Vložit odkaz",
                "unlink": "Zrušit odkaz",
                "image": "Vložit obrázek",
                "horizontalrule": "Vložit vodorovný oddělovač"
            }),

        // Specify a specific CSS file to use for the Editor
        css: "/media/js/jquery.jhtmlarea/css/jHtmlArea.Editor.css",

        // Do something once the editor has finished loading
        loaded: function() {
            //// 'this' is equal to the jHtmlArea object
            //alert("jHtmlArea has loaded!");
            //this.showHTMLView(); // show the HTML view once the editor has finished loading
        },
        
        width: width,
        height: height
    });
 }