var log = function(msg) {
    if(window.console && window.console.log) {
        window.console.log(msg);
    }
};

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// authenticated?
var auth = false;
$(function() {
    if($('body.logged-in').length > 0) {
        auth = true;
    }
});

// login popup
var highlight_invalid_fields = function(selector) {
    $(selector).css({backgroundColor: "#ff0000"})
                   .animate({backgroundColor: "#ffffff"}, 1000);
};

var openlogin, closelogin;
$(function() {
    var light = document.getElementById('light');
    var fade = document.getElementById('fade');
    openlogin = function() {
        light.style.display = 'block';
        fade.style.display = 'block';
        return false;
    };
    closelogin = function() {
        light.style.display = 'none';
        fade.style.display = 'none';
        return false;
    };
    var submit = function() {
        var form = document.forms.login;
        var username = form.username.value;
        var password = form.password.value;
        var error = false;
        if(!username || !password) {
            highlight_invalid_fields('.logifield');
        } else {
            $.post("/ajax/login", { username: username, password: password },
                function(data) {
                    if(data.ban) {
                        closelogin();
                        alert("Je bent gebanned.");
                    } else if(data.correct) {
                        window.location.href = "/redirect?u=" + escape(window.location.href);
                    } else {
                        highlight_invalid_fields('.logifield');
                    }
                }, "json");
        }
        return false;
    };
    $('.openlogin').click(openlogin);
    $('.closelogin').click(closelogin);
    $('.logiknop').click(submit);
    $('.logiform').submit(submit);
});

$(function() {
    var submit = function() {
        form = document.forms.register;
        v_username = form.reg_username.value;
        v_email = form.reg_email.value;
        v_password = form.reg_password.value;
        v_password_confirm = form.reg_password_confirm.value;

        error_fields = [];
        if(!v_username) error_fields.push('username');
        if(!v_email) error_fields.push('email');
        if(!v_password) error_fields.push('password');
        if(v_password_confirm != v_password) error_fields.push('password_confirm');

        form.reg_username.style.backgroundColor = 'white';
        form.reg_email.style.backgroundColor = 'white';
        form.reg_password.style.backgroundColor = 'white';
        form.reg_password_confirm.style.backgroundColor = 'white';

        data = {username: v_username, email: v_email, password: v_password};
        $.post('/ajax/register', data,
            function(data) {
                if(data.ok) {
                    alert("Bedankt voor je registratie! Je bent meteen ingelogd.");
                    window.location.href = "/redirect?u=" + escape(window.location.href);
                } else {
                    if(data.error_messages && data.error_messages.length > 0) {
                        if(data.error_messages.length == 1) {
                            message = data.error_messages[0];
                        } else {
                            message = "";
                            for(i = 0, j = data.error_messages.length; i < j; i++)
                                message = message + "- " + data.error_messages[i] + "\n"
                            message = rtrim(message);
                        }
                        alert(message);
                    }
                    if(data.error_fields) {
                        for(i = 0, j = data.error_fields.length; i < j; i++)
                            highlight_invalid_fields('input[name="reg_' + data.error_fields[i] + '"]');
                    }
                }
            }, 'json');

        return false;
    };
    $('.regiform').submit(submit);
    $('.regiknop').click(submit);
});

// album.comments
$(function() {
    var reply_to = function() {
        textarea = document.forms.comment.comment;
        val = ltrim(textarea.value);
        val = val.replace(new RegExp('^@\\d+'), '');
        prepend = '@' + comment_id + '\n';
        val = prepend + ltrim(val);
        textarea.value = val;
        textarea.focus();
        set_cursor(textarea, prepend.length, prepend.length);
    };
    var set_cursor = function(elem, start, end) {
        if(elem.setSelectionRange) {
            elem.focus();
            elem.setSelectionRange(start, end);
        } else if (el.createTextRange) {
            range = elem.createTextRange;
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    }

    $('.atreply').click(function() {
        if(document.forms.comment) {
            comment_id = this.parentNode.id;
            window.location.hash = 'reply' + comment_id;
            reply_to(comment_id);
            return false;
        } else {
            return true;
        }
    });
    $('.reaknop').click(function() {
        document.forms.comment.submit();
        return false;
    });

    $('.reainput')
    .focus(function() {
        $(this).addClass('nobg');
    })
    .blur(function() {
        if(trim(this.value) == "") {
            $(this).removeClass('nobg');
        }
    });

    var re_hash = /^#?reply(\d+)$/;
    var match = re_hash.exec(window.location.hash);
    if(document.forms.comment && match) {
        var comment_id = match[1];
        reply_to(comment_id);
    }

    var re_hash = /^#reageer$/;
    if(document.forms.comment && re_hash.test(window.location.hash)) {
        document.forms.comment.comment.focus();
    }
});

// rating
$(function() {
    var rating = function(sel, url) {
        // find element
        var elem = $(sel);
        if(elem.length < 1) return false;

        // find stars
        var stars = $('.star', elem);

        // get rating
        var data = elem.metadata();
        if(data.rating == undefined) return false;
        var rating = data.rating;
        var orig_rating = rating;

        // get object id
        var object_id = data.id;

        // handle events
        var render = function() {
            stars.each(function(i) {
                e = $(this);
                if(rating > i) {
                    e.removeClass('steruit');
                    e.addClass('steraan');
                } else {
                    e.removeClass('staraan');
                    e.addClass('steruit');
                }
            });
        };

        stars.each(function(i) {
            this._i = i;
        });

        stars.mouseover(function() {
            rating = this._i + 1;
            render();
        });
        stars.mouseout(function() {
            rating = orig_rating;
            render();
        });
        stars.click(function() {
            if(rating < 1 || rating > 5) return false;
            log("rate: " + rating);
            if(auth) {
                orig_rating = rating;
                $.post(url, { id: object_id, rating: rating });
            } else {
                openlogin();
            }
            return false;
        });

        render();
    };

    rating('.gallery-rating', '/ajax/rating/gallery');
    rating('.album-rating', '/ajax/rating/album');
});

// search
$(function() {
    sel = '.searchinput'
    watermark = 'Neukert zoeken';
    $(sel)
    .focus(function() {
        if(this.value == watermark) {
            this.value = '';
        }
    })
    .blur(function() {
        if($.trim(this.value) == '') {
            this.value = watermark;
        }
    });
    if($(sel).attr('value') == '') {
        $(sel).attr('value', watermark);
    }
});

