$(document).ready(

function () {

    /* handles next page of the same author widget */
    $('#next_acelasi_autor').live('click', function () {
        $('#loader_autor').show();

        $('#acelasi_autor').load(("/ajax/same-author"),

        {
            id: $('#acelasi_autor_id').val(),
            type_id: $('#acelasi_autor_type_id').val(),
            slug: $('#acelasi_autor_slug').val(),
            page: (parseInt($('#acelasi_autor_page').val()) + 1),
            type: $('#acelasi_autor_type').val()
        },

        function (responseText, textStatus, XMLHttpRequest) {
            $('#loader_autor').hide();
            $('#acelasi_autor_page').val(
            parseInt($('#acelasi_autor_page').val()) + 1);
        });
    });

    /* handles previous page of the same author widget */
    $('#previous_acelasi_autor').live('click', function () {
        $('#loader_autor').show();

        $('#acelasi_autor').load(("/ajax/same-author"),

        {
            id: $('#acelasi_autor_id').val(),
            type_id: $('#acelasi_autor_type_id').val(),
            slug: $('#acelasi_autor_slug').val(),
            page: (parseInt($('#acelasi_autor_page').val()) - 1),
            type: $('#acelasi_autor_type').val()
        },

        function (responseText, textStatus, XMLHttpRequest) {
            $('#loader_autor').hide();
            $('#acelasi_autor_page').val(
            parseInt($('#acelasi_autor_page').val()) - 1);
        });
    });

    /* handles next page of the same album widget */
    $('#next_acelasi_album').live('click', function () {
        $('#loader_album').show();

        $('#acelasi_album').load(("/ajax/same-album"),

        {
            id: $('#acelasi_autor_id').val(),
            alb_id: $('#acelasi_album_id').val(),
            type_id: $('#acelasi_album_type_id').val(),
            page: (parseInt($('#acelasi_album_page').val()) + 1),
            slug: $('#acelasi_autor_slug').val(),
            type: $('#acelasi_album_type').val()
        },

        function (responseText, textStatus, XMLHttpRequest) {
            $('#loader_album').hide();
            $('#acelasi_album_page').val(
            parseInt($('#acelasi_album_page').val()) + 1);
        });
    });

    /* handles previous page of the same album widget */
    $('#previous_acelasi_album').live('click', function () {
        $('#loader_album').show();

        $('#acelasi_album').load(("/ajax/same-album"),

        {
            id: $('#acelasi_autor_id').val(),
            alb_id: $('#acelasi_album_id').val(),
            type_id: $('#acelasi_album_type_id').val(),
            page: (parseInt($('#acelasi_album_page').val()) - 1),
            slug: $('#acelasi_autor_slug').val(),
            type: $('#acelasi_album_type').val()
        },

        function (responseText, textStatus, XMLHttpRequest) {
            $('#loader_album').hide();
            $('#acelasi_album_page').val(
            parseInt($('#acelasi_album_page').val()) - 1);
        });
    });

    /* cauta dubluri ale aceleasi resurse */
    $('#resources_title').keyup(function () {
        $('#resurse_dubluri').html("");
    });

    $('#dubluri').click(function () {
        if ($('#resources_title').val().length >= 5) {
            $('#resurse_dubluri').load("/ajax/search-for-duplicates", {
                titlu: $('#resources_title').val(),
                slug: $('#form_slug').val(),
                id: $('#resource_id').val() ? $('#resource_id').val() : 0,
                res_type_id: $('#resource_res_type_id').val() ? $('#resource_res_type_id').val() : 0 
            }, 
            function (responseText, textStatus, XMLHttpRequest) {});
        } 
        else 
        	$('#resurse_dubluri').html("Completati minim 5 caractere");
    });

    $('#res_favorita').click(function () {
        if ($('#favorita_logat').val()) {
            var adaugata = $('#favorita_adaugata').val();
            $('#res_favorita').load("/ajax/adauga-favorita", {
                res_id: $('#resource_id').val(),
                user_id: $('#favorita_logat').val(),
                adaugata: adaugata
            }, function (
            responseText, textStatus, XMLHttpRequest) {
                $('#favorita_adaugata').val(
                1 - $('#favorita_adaugata').val());
                if (adaugata == 0) {
                    $(this).removeClass('favorite');
                    $(this).addClass('deleteFavorita');
                } else {
                    $(this).removeClass('deleteFavorita');
                    $(this).addClass('favorite');
                }
            });
        }
        return false;
    });

    /* adauga un comentariu */
    $('#submitComentariiForm').click(function () {
        if ($("#commentForm").validate().form()) {
            $('#add_comentarii').hide();
            $('#comentarii-loader').show();
            $('#raspuns_adaugare').load("/ajax/add-comment", {
                subject: $('#comments_subject').val(),
                comentariu: $('#comments_content').val(),
                email: $('#comments_email').val(),
                identity: $('#comments_identity').val(),
                id: $('#resource_id').val(),
                resource_user_id: $('#resource_user_id').val()
            },

            function (responseText, textStatus, XMLHttpRequest) {
                $('#comentarii-loader').hide();
                $('#raspuns_adaugare').show();
                if ($('#resource_user_id').val() == $('#user_id').val())
                	location.reload();
            });
        }
    });

    /* raporteaza o resursa ca nepotrivita */
    $('#report_nepotrivit').click(function () {
        if ($("#sugestiiForm").validate().form()) {
            $('#res_problems').hide();
            $('#sugestii-loader').show();
            $('#rasp_nepotrivit').load("/ajax/marcheaza-resursa-nepotrivita", {
                email: $('#sugestii_email').val(),
                message: $('#sugestii_message').val(),
                id: parseInt($('#resource_id').val())
            },

            function (responseText, textStatus, XMLHttpRequest) {
                $('#sugestii-loader').hide();
                $('#rasp_nepotrivit').show();
            });
        }
    });

    $(':regex(id,^comment_page([0-9])+$)').live('click', function () {
        var spanContent = this.innerHTML;
        var matches = spanContent.match(/([0-9]+)/g);
        var page_nr
        if (matches) 
        	page_nr = matches[0];
        else {
            var elId = this.id;
            matches = elId.match(/([0-9]+)/g);
            page_nr = matches[0];
        }
        $('#comentarii').load("/ajax/load-comments", {
            page: page_nr,
            res_id: $('#resource_id').val()
        }, function (responseText, textStatus, XMLHttpRequest) {

        });
        return false;
    });

    $('#jurnal_nu').live('click', function () {
        // il vom abona la jurnal
        $('#nu_jurnal').load("/ajax/toggle-jurnal", {
            abonat: 1
        }, function (responseText, textStatus, XMLHttpRequest) {})
    });

    $('#jurnal_da').live('click', function () {
        // il vom abona la jurnal
        $('#da_jurnal').load("/ajax/toggle-jurnal", {
            abonat: 0
        }, function (responseText, textStatus, XMLHttpRequest) {})
    });

    $('#recuperare_parola').click(function () {
        // recuperare parola by mail
        $('#status_recuperare').load("/ajax/retrievePassword", {}, function (responseText, textStatus, XMLHttpRequest) {})
    });

    if ($(':regex(id,^date_daily_res([0-9]*)$)').length > 0) {
        $(':regex(id,^date_daily_res([0-9]*)$)').datepicker({
            monthNames: ['Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'],
            dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            changeYear: true,
            minDate: 0
        });
    }

    $('#add_res_zilei').click(function () {
        var id = parseInt($('#resource_id').val());
        var data = $('#res_zilei_data').val();


        $('#resursa_zilei').load(("/ajax/adauga-resursa-zilei"), {
            id: id,
            data: data
        },

        function (responseText, textStatus, XMLHttpRequest) {
            var arr = responseText.split('.');

            if (arr[0] == 'error') {
                alert(arr[1] + ' ' + data);
                $('#resursa_zilei').html('');
            }
        });
    });

    /* handles captcha */
    $('button[id^="validate_captcha_"]').live('click', function () {
        id = $(this).attr("id").replace("validate_captcha_", "");
        $('#captcha_request_' + id).load(("/ajax/check-captcha"),

        {
            value: $('#res_captcha_' + id).val(),
            id: $('#res_captcha_id_' + id).val()
        },

        function (responseText, textStatus, XMLHttpRequest) {});
    });

    // add a new message to guestbook
    $('#submitGuestbookForm').click(function () {
        if ($("#guestbookForm").validate().form()) {
            $('#formular_guestbook').hide();
            $('.ajax-loader').show();
            $.ajax({
                type: "POST",
                url: "/ajax/add-guestbook",
                data: {
                    subject: $('#guestbook_subject').val(),
                    message: $('#guestbook_message').val(),
                    email: $('#guestbook_email').val(),
                    name: $('#guestbook_contact_name').val()
                },
                success: function (data) {
                    $('.ajax-loader').hide();
                    $('#raspuns_guestbook').html('<div class="flash_notice"><div class="successMsg">Va multumim pentru mesajul dumneavoastra. Cu stima, echipa resursecrestine.ro</div></div>');
                    $('#raspuns_guestbook').show();
                    $('#guestbook_content').prepend(data);
                }
            });
        }

    });

    // Handles Jocul Biblic new game type
    $(':regex(id,^game([0-9]){2}$)').click(function () {
        var strid = this.id;
        var matches = strid.match(/([0-9]{2})/g);
        var type = matches[0]
        $('#bible-game').load(("/ajax/joc-biblic-new-game"), {
            gameType: type
        });
    });

    // Handles Jocul Biblic answer question
    $(':regex(id,^answer([0-9]){1}$)').live('click', function () {
        var strid = this.id;
        var matches = strid.match(/([0-9]{1})/g);
        var answwer = matches[0]
        $('#bible-game').load(("/ajax/joc-biblic-answer"), {
            answer: answwer
        });
    });

    // Handles Jocul Biblic save name
    $('#scoreNameButton').live('click', function () {
        if ($('#scoreName').val() == '') alert('Trebuie sa completati numele');
        else $('#bible-game').load(("/ajax/joc-biblic-salveaza-nume"), {
            name: $('#scoreName').val()
        });
    });

    // Handles the updating of the date of the daily resource
    $(':regex(id,^setdate([0-9]*)$)').live('click', function () {
        var strid = this.id;
        var matches = strid.match(/([0-9]+)/g);
        var id = matches[0];
        var content_id = 'daily_resource_content' + id;
        $('#' + content_id).load(("/ajax/update-daily-resource"), {
            id: parseInt(id),
            date: $('#date_daily_res' + id).val()
        });
        return false;
    });

    // Handles referintele biblice
    $(':regex(id,^ref_([0-9]){1}$)').live('click', function () {
        var strid = this.id;
        var matches = strid.match(/([0-9]+)/g);
        var id = matches[0];
        var id_complet = 'ref_' + id;
        //                    $('.res-ref-link-active').addClass('res-ref-link');
        $('.res-ref-link-active').removeClass('res-ref-link-active');
        $('#' + id_complet).addClass('res-ref-link-active');
        $.ajax({
            type: "POST",
            url: "/ajax/get-text-referinta",
            data: {
                id_verset_from: $('#id_verset_from_' + id).val(),
                id_verset_to: $('#id_verset_to_' + id).val()
            },
            success: function (data) {
                $('#res-ref-text').html(data);

            }
        });
        return false;
    });

    // Handles butonul de trimitere mail spre edituri
    $(':regex(id,^btemail_([0-9])*$)').live('click', function () {
        var strid = this.id;
        var matches = strid.match(/([0-9]+)/g);
        var id_editura = matches[0];
        $.ajax({
            type: "POST",
            url: "/ajax/send-email-editura",
            data: {
                id_editura: id_editura,
                an: $('#an_' + id_editura).val(),
                luna: $('#luna_' + id_editura).val()
            },
            success: function (data) {
                $('#btemail_' + id_editura).html(data);
            }
        });
        $('#btemail_' + id_editura).attr("disabled", "true")
        return false;
    });
    
    //delete attachments
    $('.delete-attachment').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(7, link_id.length);
       
        $.ajax({
            type: "POST",
            url: "/ajax/delete-attachment",
            data: "id=" + id,
            success: function(data){
               $('#attachment_' + id).remove();
            }
        });
        return false;
    });
    
    //delete attachments
    $('.delete-referinta').click(function() {
        var link_id = $(this).attr('id');
        var id = link_id.substr(7, link_id.length);
        $.ajax({
            type: "POST",
            url: "/ajax/delete-referinta-" + $('#ref_type').val(),
            data: "id=" + id,
            success: function(data){
               $('#referinta_' + id).remove();
            }
        });
        return false;
    });
    
    $('.make-visible').click(function() {
    	var link_id = $(this).attr('id');
        var id = link_id.substr(5, link_id.length);
        $.ajax({
            type: "POST",
            url: "/ajax/activate-resource",
            data: {
                id: id
            },
    		dataType: 'json',
            success: function(data){
                if (data.visible) {
                    $('#show_' + id).removeClass('active-record');
                    $('#show_' + id).addClass('inactive-record');
                    $('#show_' + id).html('Ascunde');
                }
                else {
                    $('#show_' + id).removeClass('inactive-record');
                    $('#show_' + id).addClass('active-record');
                    $('#show_' + id).html('Arata');
                }
            }
        });
        return false;
    });

     $('.externalUrl').click(function() {
        var url = $(this).attr('name');
        $.ajax({
            type: "POST",
            url: "/ajax/ajax-to-url",
            data: "url=" + url,
            success: function(data){
               return true;
            }
        });
        return true;
    });
});

function show_autori(litera, id, slug) {
    $('#autoriDupaLitera').load(("/ajax/authors-by-letter"), {
        letter: litera,
        res_type_id: id,
        slug: slug
    }, function (responseText, textStatus, XMLHttpRequest) {});
    $(".litera").removeClass('active');
}

jQuery.expr[':'].regex = function (elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
        method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
        property: matchParams.shift().replace(validLabels, '')
    },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i)) new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
            // add a new wmode parameter
            else new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        }
        else {
            // cloneNode is buggy in some versions of Safari & Opera, but works
            // fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window') new_embed.setAttribute('wmode', 'transparent');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i)) new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            try {
                for (j = 0; j < children.length; j++) {

                    if (children[j].getAttribute('name').match(/flashvars/i)) {
                        new_object = html.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                    }
                }
            }
            catch (e) {

            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}

function activate_comment(id) {
    $.ajax({
        type: "POST",
        url: "/ajax/approve-comment",
        data: {
            id: id
        },
        dataType: 'json',
        success: function (data) {
            if (data.success) {
                $('#comment_' + id).removeClass('inactive-comment');
                $('#comment_' + id).addClass('active-comment');
                $('#comment_' + id).html('Activeaza');
                $('#comment_status_' + id).html('Pentru a activa comentariul apasati');
            }
            else {
                $('#comment_' + id).removeClass('active-comment');
                $('#comment_' + id).addClass('inactive-comment');
                $('#comment_' + id).html('Dezactiveaza');
                $('#comment_status_' + id).html('Pentru a dezactiva comentariul apasati');
            }
        }
    });
}