jQuery(document).ready(function() {
    jQuery('a[rel*=external]').click( function() {
        window.open(this.href);
        return false;
    });
    
    // Cufon - Dear Joe font for testresult widget.
    if (typeof Cufon != 'undefined') {
        Cufon.replace('.h3-cufon');
    }

    if (typeof jQuery.fancybox != 'undefined') {
        // large Fancybox
        jQuery('.register-link, a#password-reminder-request-link, a#login-password-reminder-request-link').fancybox({
            'padding': 0,
            'width': 618,
            'height': 722,
            'overlayOpacity': .2,
            'overlayColor': '#000',
            'titleFormat': null,
            'type': 'iframe'
        });
        
        // small Fancybox
        jQuery('a.not-ok').fancybox({
            'padding': 0,
            'width': 618,
            'height': 400,
            'overlayOpacity': .2,
            'overlayColor': '#000',
            'titleFormat': null,
            'type': 'iframe'
        });
        
        // open images in an fancybox
        jQuery("a.fancybox-image").fancybox();
        
        // open videos in an fancybox
        jQuery(".fancybox-video").fancybox({
            'scrolling' : 'no',
            'titleShow' : false
        });
    }

    // Limit texarea and show remaining # of characters
    var onEditCallback = function(remaining){
        jQuery(this).siblings('.charsRemaining').text(remaining + ' tekens over.');
    }

    jQuery('textarea[maxlength]').limitMaxlength({
        onEdit: onEditCallback
    });

    // delete an avatar of a kid
    jQuery('.delete-kid-avatar').live('click', function() {
        jQuery('#kid-info').append('<input type="hidden" name="profile[delete_kid_avatars][]" value="' + jQuery(this).attr('rel') + '" />')
        jQuery(this).remove();
    });

    if (typeof tinyMCE != "undefined") {
        // Init tinyMce
        tinyMCE.init({
            theme : "advanced",
            theme_advanced_buttons1 : "bold,italic, |,link,unlink",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_buttons4 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            width : "383",
            mode : "specific_textareas",
            editor_selector : "mceEditor"
        });
    }

    if (typeof jQuery.watermark != 'undefined') {
        // Add watermarks
        jQuery(':password').watermark('wachtwoord...', {className: 'hasPlaceholder'});
        jQuery('.e-mail-login').watermark('e-mailadres...', {className: 'hasPlaceholder'});
        jQuery('.media-embed').watermark('Plaats hier uw embed code van Youtube of andere media via een <iframe>.', {className: 'hasPlaceholder'});
        jQuery('.telephone-watermark').watermark('0201234567', {className: 'hasPlaceholder'});
    }

    // unset default styling for blockUI
    if (typeof jQuery.blockUI != 'undefined') {
        jQuery.blockUI.defaults.css = {};
    }
    
    // Toggles add media block
    jQuery('#toggle-add-media').bind('click', function(){
        jQuery('#add-media').toggle();
    });
    
    // Toggles faq
    jQuery('.toggle-faq').bind('click', function() {
        // first close the other opened faq items
        jQuery(this).parent().siblings().removeClass('test-result-expanded');
        jQuery(this).parent().siblings('.test-result').children('ul').hide();
        
        // toggle current faq item
        jQuery(this).next().slideToggle('fast');
        jQuery(this).parent().toggleClass('test-result-expanded');
    });
    
    // Toggles sub items faq
    jQuery('.toggle-faq-sub').bind('click', function(e){
        e.preventDefault();
        
        // first close the other opened questions
        jQuery('.toggle-faq-sub-content').not(jQuery(this).next()).hide();
        
        jQuery(this).next().slideToggle('fast');
    });
    
    // Toggles testresult
    jQuery('.toggle-testresult').bind('click', function() {
        // toggle current faq item
        jQuery(this).next().slideToggle('fast');
        jQuery(this).parent().toggleClass('test-result-expanded');
    });
    
    // add FB like click to statistics
    if (typeof FB != 'undefined') {
        FB.Event.subscribe('edge.create', function(href) {
            var like = getLike(href);
            like.count = '+1';
            jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/facebookLike.php', like, function(data) {});
        });
    
        FB.Event.subscribe('edge.remove', function(href) {
            var like = getLike(href);
            like.count = '-1';
            jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/facebookLike.php', like, function(data) {});
        });

        /**
         * Check if the like url matches the criteria
         */
        function getLike(url) {
            var like = {};

            url = unescape(url);

            var myRegExp = /comment-(\d+)/;
            var matches = url.match(myRegExp);

            if (matches != null && matches.length > 0) {
                like.type = 'comment';
                like.object_id = matches[1];
                return like;
            }

            var myRegExp = /\/vraag\/(.*)\//;
            var matches = url.match(myRegExp);

            if (matches != null && matches.length > 0) {
                like.type = 'question';
                like.object_id = matches[1]
                return like;
            }

            return like;
        }
    }

    if (window.location.hash == '#settings') {
        jQuery('#profile-1').hide();
        jQuery('#profile-2').hide();
        jQuery('#profile-3').show();

        // toggle highlighted tab
        jQuery('div.tabs a.button-own').removeClass('button-own');
        jQuery('div.tabs a.tab-last').addClass('button-own');
    }

});

// Function to limit textarea
jQuery.fn.limitMaxlength = function(options){

    var settings = jQuery.extend({
        attribute: "maxlength",
        onLimit: function(){},
        onEdit: function(){}
    }, options);

    // Event handler to limit the textarea
    var onEdit = function(){
        var textarea = jQuery(this);
        var maxlength = parseInt(textarea.attr(settings.attribute));

        if(textarea.val().length > maxlength){
            textarea.val(textarea.val().substr(0, maxlength));

            // Call the onlimit handler within the scope of the textarea
            jQuery.proxy(settings.onLimit, this)();
        }

        // Call the onEdit handler within the scope of the textarea
        jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
    }

    this.each(onEdit);

    return this.keyup(onEdit)
                .keydown(onEdit)
                .focus(onEdit)
                .live('input paste', onEdit);
}

/**
 * Copies kid-info-template
 */
function copyChildInfo()
{
    template = jQuery('#kid-info-template').html();

    new_id = jQuery('#kid-info').children('.kid-info').length;

    template = template.replace(/##ID##/g, new_id);
    // Somehow IE can't replace disabled="disabled" at once.
    template = template.replace(/="disabled"/gi, '');
    template = template.replace(/disabled/gi, '');

    jQuery('#kid-info').append(template);
}

/**
 * Delete a reaction via an ajax call
 * @param int   id
 * @return void
 *
 */
function deleteReaction(id)
{
    if (confirm('Weet u zeker dat u deze reactie wilt verwijderen?')) {
        var postData  = [];

        var tmp = {};
        tmp.name = 'id';
        tmp.value = id;
        postData.push(tmp);

        jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/deleteReaction.php', postData, function(data) {
            if(data == 'ok') {
                window.location.reload();
            }
        });
    }
}

/*
 * Deletes a message with ajax
 * @param int   id
 */
function deleteMessage(id, redirect)
{
    if (confirm('Weet u zeker dat u dit bericht wilt verwijderen?')) {
        var postData  = [];
        
        var tmp = {};
        tmp.name = 'id';
        tmp.value = id;
        postData.push(tmp);
        
        jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/deleteMessage.php', postData, function(data) {
            if(data != 'error') {
                if (redirect == 'messages') {
                    window.location = base_url + '/mijn-berichten/berichten/';
                } else if (data != 'ok') {
                    window.location = base_url + '/mijn-berichten/bericht-sturen/?id=' + data;
                } else {
                      window.location = base_url + '/mijn-berichten/berichten/';
                }
            }
        });
    }
}


/**
 * Sends a request through an e-mail to become friends.
 * @param   int     id1  id of the requester
 * @param   int     id2  id of the receiver
 */
function friendRequest(id1, id2, e)
{
    var postData  = [];
    
    var tmp = {};
    tmp.name = 'id1';
    tmp.value = id1;
    postData.push(tmp);
    
    var tmp = {};
    tmp.name = 'id2';
    tmp.value = id2;
    postData.push(tmp);

    jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/friendRequest.php', postData, function(data) {
        if (data == 'ok') {
            jQuery(function() {
                jQuery.growlUI('Vrienden worden', 'Je aanvraag is verstuurd! Deze zal nog door haar geaccepteerd moeten worden'); 
                // Fadeout
                jQuery(e).fadeOut('slow');
            });
        }
    });
}

/*
 * Follow a post or a user
 */
function followPostUserTest(type, id, e)
{
    var postData  = [];
    
    var tmp = {};
    tmp.name = 'type';
    tmp.value = type;
    postData.push(tmp);
    
    var tmp = {};
    tmp.name = 'id';
    tmp.value = id;
    postData.push(tmp);

    jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/followPostUserTest.php', postData, function(data) {
        // show correct message for follow post or follow mama
        if (data == 'ok-post') {
            jQuery(function() {
                jQuery.growlUI('Vraag volgen', 'Je volgt nu de vraag'); 
                // Fadeout
                jQuery(e).fadeOut('slow');
            });
        } else if (data == 'ok-user') {
            jQuery(function() {
                jQuery.growlUI('Mama volgen', 'Je volgt nu deze mama'); 
                // Fadeout
                jQuery(e).fadeOut('slow');
            });
        } else if (data == 'ok-test') {
            jQuery(function() {
                jQuery.growlUI('Test volgen', 'Je volgt nu deze test'); 
                // Fadeout
                jQuery(e).fadeOut('slow');
            });
        }
    });
}

/*
 * Unfollow a post, user or test
 */
function unfollowPostUserTest(type, id)
{
    var postData  = [];
    
    var tmp = {};
    tmp.name = 'type';
    tmp.value = type;
    postData.push(tmp);
    
    var tmp = {};
    tmp.name = 'id';
    tmp.value = id;
    postData.push(tmp);

    jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/unfollowPostUserTest.php', postData, function(data) {
        if (data == 'ok-post' || data == 'ok-user' || data == 'ok-test') {
            window.location.reload()
        }
    });
}

/*
 * Unfriend a user
 */
function unfriendUser(id)
{
    if (confirm('Weet je zeker dat je niet meer vriendinnen wilt zijn?')) {
        var postData  = [];
        
        var tmp = {};
        tmp.name = 'id';
        tmp.value = id;
        postData.push(tmp);

        jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/unfriendUser.php', postData, function(data) {
            if (data == 'ok') {
                window.location.reload()
            }
        });
    }
}

/**
 * Add pageview to a post to memcache via an ajax call
 * @param int   id
 * @return void
 *
 */
function addPageView(id)
{
    var postData  = [];

    var tmp = {};
    tmp.name = 'id';
    tmp.value = id;
    postData.push(tmp);

    jQuery.post(base_url + '/wp-content/themes/volgensmama/ajax/addPageView.php', postData, function(data) {});
}

/**
 * Toggle the tabs on the profile edit screen
 * @param int   id
 * @param object    element
 * @return void
 */
function toggleProfile(id, element)
{
    if (id == 1) {
        jQuery('#profile-1').show();
        jQuery('#profile-2').hide();
        jQuery('#profile-3').hide();
    } else if (id == 2) {
        jQuery('#profile-1').hide();
        jQuery('#profile-2').show();
        jQuery('#profile-3').hide();
    } else if (id == 3) {
        jQuery('#profile-1').hide();
        jQuery('#profile-2').hide();
        jQuery('#profile-3').show();
    }

    // toggle highlighted tab
    jQuery(element).siblings().removeClass('button-own');
    jQuery(element).addClass('button-own');
}

/**
 * Toggle the tabs on the homepage
 * @param   int id
 * @return  void
 */
function toggleHomeTabs(id)
{
    if (id == 'home-forum-popular') {
        // buttons
        jQuery('#forum-recent-button').removeClass('current');
        jQuery('#forum-recent-button').addClass('button');
        jQuery('#forum-popular-button').removeClass('button');
        jQuery('#forum-popular-button').addClass('current');
        
        // tabs
        jQuery('#home-forum-popular').removeClass('hide');
        jQuery('#home-forum-recent').addClass('hide');
    } else if (id == 'home-forum-recent') {
        // buttons
        jQuery('#forum-popular-button').removeClass('current');
        jQuery('#forum-popular-button').addClass('button');
        jQuery('#forum-recent-button').removeClass('button');
        jQuery('#forum-recent-button').addClass('current');
        
        //tabs
        jQuery('#home-forum-recent').removeClass('hide');
        jQuery('#home-forum-popular').addClass('hide');
    } else if (id == 'home-test-popular') {
        // buttons
        jQuery('#test-recent-button').removeClass('current');
        jQuery('#test-recent-button').addClass('button');
        jQuery('#test-popular-button').removeClass('button');
        jQuery('#test-popular-button').addClass('current');
        
        // tabs
        jQuery('#home-test-popular').removeClass('hide');
        jQuery('#home-test-recent').addClass('hide');
    } else if (id == 'home-test-recent') {
        // buttons
        jQuery('#test-popular-button').removeClass('current');
        jQuery('#test-popular-button').addClass('button');
        jQuery('#test-recent-button').removeClass('button');
        jQuery('#test-recent-button').addClass('current');
        
        //tabs
        jQuery('#home-test-recent').removeClass('hide');
        jQuery('#home-test-popular').addClass('hide');
    }
}

