/* scroller */
// simple jQuery infinite scroller from http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery
// a few mods by me to ensure things get returned in the right order
    var dataReturned = true;

    var reachedBottom = false;

    function lastPostFunc() {
        //$('div#lastPostsLoader').html('<img src="bigLoader.gif" />');
        dataReturned = false;
        $.ajax({
            type: "GET",
            url: "/scroll.ajax.php?lastID="+$(".recent:last").attr("id"),
            success: function(data){
                    if(data != "") {
                        if(data=="bottom") {
                            if(!reachedBottom) {
                                // this is the first time we've hit the bottom; change the text
                                $('#moreLoading').text('no more things').fadeTo('slow',0);
                                // using fadeTo instead of fadeOut so that the element remains in the document instead of being hidden - this way its opacity is zero but it still has width and height.
                            }
                            // and stop sending requests after they reach the bottom
                            reachedBottom = true;
                        } else {
                            $(".recent:last").after(data);
                        }
                    }
                    dataReturned = true;
                    //$('div#lastPostsLoader').empty();
                },
            async: false
        });
    }

    function loadMoreRecent() {
        if(!reachedBottom) {
            for(var i=0 ; i<3 ; i++) {
                if(dataReturned) lastPostFunc();
            }
        }
    }

    $(window).scroll(function() {
        // when they scroll, load more items until window full or 10 more items loaded.
    //if($(window).scrollTop() + $(window).height() - $(document).height()<=0) {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
            loadMoreRecent();
    }
    });
/* /scroller */

/* form validation */
function validate() {
    var go = true;
    if($('#postForm input[name="name"]').val()=="") {
        go = false;
        alert('Please give a name to the thing (eg, "bus ticket" or "muddy pawprint")');
    } else if($('#postForm input[name="isbn"]').val()=="") {
        go = false;
        alert('Please enter the book\'s ISBN or title\n(The ISBN is prefered, and can usually be found above the barcode)');
    } else {
        // we are allowing (n-1) blank fields; so we can't just bomb out when we find a blank
        // so we assume they fail and then pass when we find a non-blank field
        go = false;
        // using :file is a bit shotgun, but there aren't any other file fields yet so I'm letting it pass.
        $('#postForm :file').each(function() {
            if($(this).val()!='') {
                go = true;
            }
        });
        if(!go) {
            alert('You must provide at least one image of the thing - we want to see it!');
        }
    }

    if(go) {
        $('#submitBtn').val('uploading, please wait');
        $('#postForm').submit();
    }
}
/* /form validation */

function isbnText() {
    if($('#isbnText').hasClass('jQueryShowing')) {
        $('#isbnText').text('The book doesn\'t have an ISBN!').removeClass('jQueryShowing');
        $('#isbnLabel').text("Book's ISBN");
    } else {
        $('#isbnText').text('Oh wait, I found the ISBN').addClass('jQueryShowing');
        $('#isbnLabel').text('Book Title');
    }
}

var numBoxes = 0;
function newBox(){
    numBoxes++;
    if(numBoxes<5) {
        // (there's probably a one-line bit of jQuery that can do this....)
        // the tricky bit is copying all the element's attributes except value - we can't just copy them all then say .value="" as it's type="file" - readonly!!
        var el = document.getElementById('fileInput');
        var newInput = document.createElement('input');
        newInput.type = "file";
        newInput.name = "image[]";
        $(newInput).change(function () {
            checkFileType(this,'jpg jpeg');
        }).insertBefore(el);
    } else if(numBoxes<10){
        $('#addMore').text('Sorry, maximum of five.');
    } else {
        $('#addMore').text('Stop clicking me !');
    }
}

function checkFileType(el,allowed) {
    var last_dot_pos = el.value.lastIndexOf('.');
    var extension = "";
        if(last_dot_pos>=0) {
            // filename does have a dot; return extension
            extension = el.value.substring(last_dot_pos+1).toLowerCase();
        }
        if(allowed.indexOf(extension)==-1) {
            alert('sorry, '+allowed+' file types only at the moment');
            el.value = '';
        }
}

var origHeights = new Array();
function biggerBox(id,factor) {
    if(!factor) {
        factor = 3;
    }
    if(!$('#'+id).hasClass('blnBigger')) {
        // save original height
        origHeights[id] = $('#'+id).css('height');
        $('#'+id).addClass('blnBigger').animate({
            height: parseInt(origHeights[id])*factor+'px'
        }, function() {
            $('#'+id).next().contents().text('ok make it smaller');
        });
    } else {
        $('#'+id).removeClass('blnBigger').animate({
            height: origHeights[id]
        }, function() {
            $('#'+id).next().contents().text('I need a bigger box again!');
        });

    }
}

function toggleForm() {
    if($('#farcol').hasClass('jQueryShowing')) {
        $('#showForm').slideUp();
        $('#content').animate({width:"580px"},function(){
            $('#farcol').removeClass('jQueryShowing').fadeIn('normal',function(){
            });
        });
        } else {
        $('#farcol').addClass('jQueryShowing').fadeOut('normal',function(){
            $('#content').animate({width:"810px"});
            $('#showForm').slideDown();
        });
    }
}

function toggleLogin() {
    if($('#forgot').hasClass('jQueryShowing')) {
        $('#forgot').fadeOut('fast',function() {
            $('#login').fadeIn('fast');
        }).removeClass('jQueryShowing');
    } else {
        $('#login').fadeOut('fast',function(){
            $('#forgot').fadeIn('fast').addClass('jQueryShowing');
        })
    }
}

function swapImage(imgSrc) {
    $('#mainimg a.thickbox').attr('href','/things/'+imgSrc+'.jpg');
    $('#mainimg a.thickbox img').attr('src','/things/'+imgSrc+'_med.jpg');
}

var removeTimeout = 3000;
function removeMessages() {
    // clear up messages every few seconds
    $('.jQueryRemoveMe').fadeOut('slow');
    window.setTimeout(removeMessages,removeTimeout);
}

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 * this function stolen from http://malsup.com/jquery/form/
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};


$(document).ready(function() {
    // auto-pass captcha test (yes yes, it's not 100% secure, but it works for now. I have actually written research on captchas)
    // if you're a spammer reading this, please, just don't. you'll spam me for one day. I'll put a captcha in place and that'll be that.
    // just don't bother. go somewhere else
    $("input[name='captcha']").attr('value','iamnotaspammer');

    // load recent items to the bottom of the page
    loadMoreRecent();

    // ajax up the ratings ;)
    $('.mystar').rating({
        required: true,
        callback: function() {
            $.get("/rate.ajax.php", { ThingID: this.form.ThingID.value, rating: $(this).val(), ajax: 1},function(data){
                var msg = '';
                switch(data) {
                    case '1':
                        msg='rating saved';
                        break;
                    case '0':
                        msg='rating changed';
                        break;
                    case '-1':
                        msg='not logged in';
                        break;
                    default:
                        msg='error';
                        break;
                }
                $('#ratings').html('<br /><small>'+msg+'</small>').show().addClass('jQueryRemoveMe');
            });
        }
    });
    window.setTimeout(removeMessages,removeTimeout);
});