// ajax
$(document).ready(function($) {
    $(".thank").live('click', function() {
        var id = $(this).attr("id").replace(/^t/, "");
        var block = $("#tb" + id);   
                      
        var loader=small_loader_show($(this), id); 
        $(this).hide();    
        $.post("/thank.php", {
            p: id,
            action: "add"
        }, function(data) {
            $(block).html(data);
            small_loader_hide(loader);
            $(".thank").show(); 
        });
    });

    $(".unthank").live('click', function() {
        var id = $(this).attr("id").replace(/^t/, "");
        var block = $("#tb" + id); 
        var loader=small_loader_show($(this), id);   
        $(this).hide();      
        $.post("/thank.php", {
            p: id,
            action: "del"
        }, function(data) {
            $(block).html(data);
            small_loader_hide(loader);
            $(".unthank").show(); 
        });
    });

    $(".thanks").one('click', function() {
        var id = $(this).attr("id").replace(/^tl/, "");
        var button = $("#t" + id); 
        var self=$(this);
        var loader=small_loader_show(button, id); 
        button.hide();
        $.get("/thank.php", {
            p: id
        }, function(data) {
            $(self).removeClass("thanks").html(data);
            small_loader_hide(loader);   
            button.show();         
        });
    });

    //подписка на темы
    $('a#watchlink').click(function() {
        var topic_id=parseInt($(this).attr('rel'), 10);
        
        $.ajax({
            url:'/aj/ajaxsubscribe.php',
            type:'POST',
            dataType:'json',       
            data:'topic_id='+topic_id,
            success: function(data) {
                if (data.error) {
                    alert(data.error_text);
                } else {
                    $('a#watchlink').html(data.result.link);
                    //alert(data.result.message);
                }
            }
        });
        return false;
    });
});

// content
$(document).ready(function($) {
    $.extend($.expr[':'], {
        longestOver: function (element, index, meta) {
            return $(element).width() > meta[3] || $(element).height() > meta[3];
        }
    });

    $('.post.brief table.quote img:longestOver(100)').aeImageResize({width: 100, height:100});
    $('.post.brief img:longestOver(150)').aeImageResize({width: 150, height:150});
    $('.post table.quote img:longestOver(350)').aeImageResize({width: 350, height: 350});
    $('.post img:longestOver(640)').aeImageResize({width: 640, height: 640});

    //$('.post br:first-child').remove();
    $('div[id^="google_ads_div_"]').removeAttr('style');
    $('a.textad').each(function() {
        var $link = $(this).attr('href');
        $(this).find('td').click(function() {
            window.location.href=$link;
        });
    });

    // Video
    $('.post a.auto[href^="http://www.youtube.com/watch"], .post a.auto[href^="http://youtube.com/watch"], .post a.auto[href^="http://youtu.be"], .post a.auto[href^="http://www.youtu.be"]')
        .not('.post table.quote a')
        .each(function() {
            var result = /(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?[^?]*?v=)?([0-9a-zA-Z-]+)/.exec( $(this).attr('href') );
            if (result !== null) {
                $(this).replaceWith('<div class="videoContent"><iframe width="420" height="345" src="http://www.youtube.com/embed/'+result[1]+'" frameborder="0"></iframe>');
            }
        });
    $('.post a.auto[href^="http://www.vimeo.com"], .post a.auto[href^="http://vimeo.com"]')
        .not('.post table.quote a')
        .each(function() {
            var result = /(?:http:\/\/)?(?:www\.)?vimeo\.com\/([0-9a-zA-Z-]+)/.exec( $(this).attr('href') );
            if (result !== null) {
                $(this).replaceWith('<div class="videoContent"><iframe width="506" height="380" src="http://player.vimeo.com/video/'+result[1]+'" frameborder="0"></iframe>');
            }
        });

    // Spreadsheets
    $('.post a.auto[href^="http://spreadsheets.google.com"], .post a.auto[href^="http://www.spreadsheets.google.com"], .post a.auto[href^="https://spreadsheets.google.com"], .post a.auto[href^="https://www.spreadsheets.google.com"], .post a.auto[href^="http://spreadsheets0.google.com"], .post a.auto[href^="https://spreadsheets0.google.com"]')
        .not('.post table.quote a')
        .each(function () {
            var result = /(?:https?:\/\/)?(?:www\.)?(spreadsheets\d*\.google\.com\/(spreadsheet\/)?pub\?.*key=[^&]+).*/.exec( $(this).attr('href') );
            if (result !== null) {
                $(this).replaceWith('<div class="googleDocsContent"><iframe src="http://'+result[1]+'&amp;output=html"></iframe></div>');
            }
        });

    // Fight enemy smilies
    $.each([
        'http://smajliki.ru', 'http://smiles2k.net', 'http://x-lines.ru', 'http://www.x-lines.ru', 'http://giiif.ru', 'http://smayli.ru',
        'http://galaxie.ru', 'http://animashka.info', 'http://www.animashka.info', 'http://bestgif.narod.ru', 'http://best-image.org',
        'http://fotocvetov.ru', 'http://www.fotocvetov.ru', 'http://colnyshko.ru', 'http://www.colnyshko.ru', 'http://gs105.rimg.info',
        'http://static.colnyshko.ru', 'http://zdesvsyo.ru', 'http://funlove.at.ua', 'http://www.giffun.ru', 'http://giffun.ru',
        'http://gifzona.ru', 'http://www.gifzona.ru', 'http://gifzona.com', 'http://www.gifzona.com', 'http://krasota-gif.narod.ru',
        'http://www.krasota-gif.narod.ru', 'http://xxlsite.narod.ru', 'http://miranimashek.com', 'http://melochi-jizni.ru', 'http://positiveland.ru',
        'http://motivators.ru', 'http://4.komaro.z8.ru', 'http://mirgif.com', 'http://kotomatrix.ru', 'http://bestgif.su',
        'http://www.bestanimationgif.com', 'http://www.vsyaanimaciya.ru', 'http://www.best-animation.ru', 'http://best-animation.ru',
        'http://gifportal.ru', 'http://best-image.ucoz.ru', 'http://smiles.33bru.com', 'http://rimg.info', 'http://smiles.33b.ru',
        'http://4.komaro.z8.ru', 'http://www.rewalls.com', 'http://www.allday.ru', 'http://vsyaanimaciya.ru', 'http://tanya7979.ucoz.ru',
        'http://gifr.ru', 'http://muzotkrytka.narod.ru', 'http://www.biggif.ru', 'http://www.cool-birthday.com',
        'http://www.topglobus.ru', 'http://yoursmileys.ru', 'http://гык.рф', 'http://fantasyflash.ru', 'http://blestki.com',
        'http://chudetstvo.ru', 'http://gif-anim.narod.ru', 'http://ah.toppik.ru', 'http://anime.toppik.ru', 'http://t-smertina.narod.ru',
        'http://file.mobilmusic.ru', 'http://cool-pictures.ucoz.ru', 'http://krassota.com', 'http://images.gifmania.ru',
        'http://bestsmiles.net.ru', 'http://s.rimg.info', 'http://s1.rimg.info', 'http://s2.rimg.info', 'http://s3.rimg.info', 'http://s4.rimg.info',
        'http://s5.rimg.info', 'http://s6.rimg.info', 'http://s7.rimg.info', 'http://s8.rimg.info', 'http://s9.rimg.info', 'http://s10.rimg.info',
        'http://s11.rimg.info', 'http://s12.rimg.info', 'http://s13.rimg.info', 'http://s14.rimg.info', 'http://s15.rimg.info', 'http://s16.rimg.info',
        'http://s17.rimg.info', 'http://a12005.rimg.info'
    ], function (index, element) {
        $('.post a[href^="'+element+'"], .post img[src^="'+element+'"]').remove();
    });

    // URLs
    $('.post a')
        .not('[href^="http://club.osinka.ru"]')
        .not('[href^="http://www.osinka.ru"]')
        .not('[href^="http://osinka.ru"]')
        .attr('target', '_blank');

    /**
     * @const
     * @type{number}
     */
    var maxUrl = 38;
    $('.post a.auto').each(function() {
        var href = $(this).attr('href');
        if (href.length > maxUrl-3) {
            $(this).html( href.substring(0, maxUrl-3) + "&hellip;");
        }
    });

    $('.post').mousedown(function() {
        $(this).find('a.auto').each(function() {
            var href = $(this).attr('href');
            $(this).html(href);
        });
    });
});

// forms
$(document).ready(function($) {
    $(":input[rel='validate']").change(function () {
        if ($(this).hasClass('text_validate_error') && $(this).val()!=='') {
            $(this).removeClass('text_validate_error');
        }
    });  
    $(":input[rel='validate']").keypress(function (e) {
        if ($(this).hasClass('text_validate_error') && $(this).val()!=='') {
            $(this).removeClass('text_validate_error');
        }
    });  
    
    $('.autochecked').focus();
});

function go_url(u)
{
    window.location.href=u;
}

function pgs(t)
{
    if (t.options[t.selectedIndex].value !== -1) { go_url(t.options[t.selectedIndex].value);}
}

function pgt(event, t, url, on_page, total_pages, per_page)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; 
    if ( keyCode === 13 ) 
    { 
        var page_no = parseInt(t.value, 10); 
        if ( !isNaN(page_no) && page_no <=total_pages && page_no > 0) { 
            var start = String((page_no - 1)*per_page); 
            go_url(url+'&start='+start);
            return false;
        } else { 
            t.value =on_page; 
            return false;
        } 
    }
}

//простейший валидатор форм
function form_validate(form_id)
{   
    var flag=true; 
    $("#"+form_id+" :input[rel='validate']").each(function() {
        var val=$(this).val();
        if (val==='') {
            $(this).addClass('text_validate_error');
            $(this).focus();
            flag=false;
        }
    }); 
    return flag;
}

function choicetag(tag)
{
    var tarea,val;
    if (tarea=document.getElementById('ptgsare'))
    {
        val=tarea.value;
        var oRegExp = new RegExp("([\s,; ]+|^[\s,; ]?)"+tag+"([\s,; ]+|[\s,; ]?$)","im");
        if (val.search(oRegExp)!==-1) {
                val=val.replace(oRegExp," ");
                val=val.replace(/^\s+|\s+$/, "");
        } else {
                val+=' '+tag+' ';
                val=val.split('  ').join(' ');
                val=val.replace(/^\s+|\s+$/, "");
        }
        tarea.value=val;
    }
    return void(0);
}

function unsafelink(url)
{
    if (confirm('Мы считаем, что контент страницы может быть небезопасен. Вы хотите перейти по ссылке?')) {
        return true;
    }
    return false;
}

function small_loader_show(button, id)
{
    var html='<div id="sm_loader_'+ id +'" class="sm_loader"></div>';
    var obj=$(html).appendTo("body");    
    var offset=button.offset();    
    obj.css('left', offset.left+ 2 + 'px');
    obj.css('top',  offset.top + 1 + 'px');
    obj.show();
    return obj;
}

function small_loader_hide(obj)
{
    obj.hide();  
    obj.remove();
}

function big_loader_show()
{
    var obj=$('#big_loader');
    var w = $(window);
    var top=(w.height()-obj.height())/2+w.scrollTop();
    var left= (w.width()-obj.width())/2+w.scrollLeft();
    obj.css('left', left+'px');
    obj.css('top', top+'px');
    obj.show();
}
function big_loader_hide()
{
    $('#big_loader').hide();
}

