(function($){$(function(){

    /**
     * Slideshow
     */
    (function(){
        var $slideshow = $('.slideshow');

        // TODO: define a loading image
        $slideshow
            .slides({
                preload: true,
                autoHeight: true
            });

        function adjust_slide_size()
        {
            $slideshow.find('.slides_container, .slides_control > *')
                .width($slideshow.innerWidth())
        }
        adjust_slide_size();
        $(window).resize(adjust_slide_size);

    })();

    /**
     * Desbinarize
     */
    (function(){
        var $desbinarize = $('.desbinarize');
        var $source = $desbinarize.find('.desbinarize-source');
        var $output = $desbinarize.find('.desbinarize-output');
        var $fail   = $desbinarize.find('.desbinarize-fail');

        var doBinarize = function(str)
        {
            var o = '';
            var tmp;

            // iterate through the string converting each char
            for ( var i=0; i < str.length; i++ ) {
                tmp = "00000000" + str.charCodeAt(i).toString(2);
                o += tmp.substr(-8) + " ";
            }
            
            return o;
        }

        var doDesbinarize = function(str, failCallback)
        {
            var o = '';
            var tmp;

            // strips off anything that's not 0 or 1
            str = str.replace(/[^01]/g, '');
            
            // if it's not divisible by 8, then it fails
            if (('' == str || 0 != (str.length % 8)) && typeof failCallback == 'function') {
                failCallback();
                return;
            }
            
            // iterate through the string getting chunks of 8 chars
            for (var i=0; '' != (tmp = str.substr(i*8, 8) ); i++) {
                // adding to the output
                o += String.fromCharCode(parseInt(tmp, 2));
            }
                
            return o;
        }
        
        $desbinarize
            .find('.desbinarize-ascii2bin')
                .click(function(){
                    $output.text(doBinarize($source.val()));
                })
            .end()
            .find('.desbinarize-bin2ascii')
                .click(function(){
                    $output.text(doDesbinarize($source.val(), function(){
                        $fail.slideDown();
                        setTimeout(function(){ $fail.slideUp(); }, 6000);
                    }));
                })
            .end();
    })();


})})(jQuery);

