/**
 * **********************************************************************
 * **********************************************************************
 * bbcom global Object
 * initializing JavaScripts on bbcom, parsing links
 *
 * @author Benedikt Bast
 * @date 2010-07-14
 *
 * @version 1.0.0
 *
 *
 * @tested Firefox 3, IE6-7-8, WebKit, Opera10+
 * @requires jQuery v1.4.2
 * 
 *
 * **********************************************************************
 * ******
 */


var bb;
if (!bb) bb = {};
    else if (typeof bb != 'object')
        throw new Error('bb exists, but is not an object!');


bb.init= function() {
 
    jQuery('.youtube').click( function(ev) { 
                                bb.lightbox.init(this);
                                ev.preventDefault();
                            })
    ;

    jQuery('.gal').click( function(ev) { 
                                bb.lightbox.init(this);
                                ev.preventDefault();
                            })   
    ;

    jQuery('.cntImg').click( function(ev) { 
                                bb.lightbox.init(this);
                                ev.preventDefault();
                            })   
    ;

    if (jQuery.browser.msie) {
        bb.centerContent();
        jQuery(window).resize( function() {bb.centerContent();} )
    }
    
    if (jQuery('div#tweet').length > 0 ) {
        bb.getTweet.importTwitterJSON();
    }

    bb.hashHandler();


};


/**
 * **********************************************************************
 * **********************************************************************
 * Handler for URL Hashes
 *
 * @author Benedikt Bast
 * @date 2010-07-29
 *
 * @version 0.0.1
 *
 *
 * @tested  IE6-7-8
 * @requires jQuery v1.4.2
 * 
 *
 * **********************************************************************
 * ******
 */

bb.hashHandler= function() {

    var imgPattern = /^#picture=([\w.-]*)(.jpg|png|gif)$/m;
    setTimeout (function() {
        
        if (imgPattern.test(location.hash)) {
            with (bb.lightbox) {
                    conf.mode = 'image';
                    conf.anc = location.protocol+'//'+location.hostname+'/content_images/'+location.hash.match(imgPattern)[1]+location.hash.match(imgPattern)[2];
                    init(null);
            }
        }    
        
        
    },500);
    

}


/**
 * **********************************************************************
 * **********************************************************************
 * IE Fix for vertically centered Content
 *
 * @author Benedikt Bast
 * @date 2010-07-14
 *
 * @version 1.0.0
 *
 *
 * @tested  IE6-7-8
 * @requires jQuery v1.4.2
 * 
 *
 * **********************************************************************
 * ******
 */

bb.centerContent= function() {
    
    jQuery('#Positioner').css({
           'margin-top':(jQuery(window).height() - jQuery('#Positioner').height())/2+'px'
    });

}




/**
 * **********************************************************************
 * **********************************************************************
 * bbcom lightbox Object
 * opening Youtube videos (hd), gallery in iFrame, content Images
 *
 * @author Benedikt Bast
 * @date 2010-08-01
 *
 * @version 1.0.3
 *
 *
 * @tested Firefox 3, IE6-7-8, WebKit, Opera10+
 * @requires jQuery v1.4.2
 * @requires bbcom Object for initializing
 * 
 *
 * **********************************************************************
 * ******
 */

bb.lightbox = {
    
    conf : {

        color       : 'gray',
        opacity     : '0.60',
        mode        : '',
        anc         : '',
        hd          : '',
        preloader   : '/data/preloader.gif'
        
    },
    
    init: function(o) {
    
        var conf = this.conf;
    
        if (o) { //if lightbox is called by hashandler no object is provided
                 //hashhandler writes config itself
                conf.anc = o.href;
                if ( jQuery(o).hasClass('youtube') ) {conf.mode = 'youtube'}
                if ( jQuery(o).hasClass('HD') )      {conf.hd = true}
                if ( jQuery(o).hasClass('gal') )     {conf.mode='gal'}
                if ( jQuery(o).hasClass('cntImg') )  {conf.mode='image'}
        }

        var layer = jQuery('<div></div>')
                        .attr('id','lightbox')
                        .css({
                                'background-color': conf.color ,
                                'opacity':conf.opacity,
                                'width' : jQuery(document).width() + 'px',
                                'height': jQuery(document).height() + 'px',
                                'top':'0px',
                                'left':'0px',
                                'z-index':'99',
                                'float':'left',
                                'position':'absolute',
                                'cursor':'pointer',
                                'display':'none'
                            })
                        .click( function() { bb.lightbox.destroy(); } )
                        .appendTo(jQuery('body'))
                        .fadeIn(500, function() { bb.lightbox.showContent(); } )
        ;
        
        jQuery(window).resize( function() { jQuery('#lightbox')
                                                .css({
                                                        'width' : jQuery(document).width() + 'px',
                                                        'height': jQuery(document).height() + 'px'
                                                    })
                                            ;
                                            
                                            jQuery('#lightboxContent')
                                                .css({
                                                        'top' : (jQuery(window).height() - jQuery('#lightboxContent').height())/2+'px',
                                                        'left': (jQuery(window).width()  - jQuery('#lightboxContent').width())/2+'px'
                                                    })
                                          })
        ;
        
        jQuery(document).bind('keydown', function(ev) {
                if (ev.keyCode === 27) {
                    bb.lightbox.destroy();
                    jQuery(this).unbind('keydown');
                }
            })
        ;

        
    },
    
    
    showContent: function() {
    
        var conf = this.conf;
    
        if (conf.mode == 'youtube') {
            bb.lightbox.buildYT();
        }
      
        if (conf.mode == 'gal') {
            bb.lightbox.buildGal();
        }
      
        if (conf.mode == 'image') {
            bb.lightbox.contentImage();
        }
   
    },
    
    
    buildYT: function() {
     
        var conf = this.conf, 
            height,
            width,
            movID
        ; 
         
        pattern = /^(http:\/\/)?(www.|de.|it.|fr.|nl.|jp.|ru.|pl.|es.|ie.)?youtube.(de|com|ru|com.br|fr|jp|nl|pl|es|ie|co.uk|it|kr)\/watch\?v=([\w-]*)(&\S*)*$/m;

        if (pattern.test(conf.anc)) {
            movID = conf.anc.match(pattern)[4];
        } else {
            throw new Error('Youtube link invalid');
        }

        (conf.hd)?height='':height='385';
        (conf.hd)?width='':width='480';
        
        //alert(movID);
        //<embed width="854" height="480" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/Ghgg_fukbvU&autoplay=1">
       
                jQuery('<div></div>')
                        .attr({
                               'id':'lightboxContent'
                               })
                         .css({
                                'position':((jQuery.browser.msie) && (jQuery.browser.version == '6.0')) ? 'absolute' : 'fixed',
                                'z-index':'199',
                                'width':width+'px',
                                'height':height+'px',                               
                                'top' : (jQuery(window).height() - height)/2+'px',
                                'left': (jQuery(window).width()  - width )/2+'px',
                                'display':'block',
                                'margin':'0',
                                'padding':'0'
                            })
                        .append(jQuery('<embed></embed>')
                                   .attr({
                                            'width':width+'px',
                                            'height':height+'px',
                                            'allowfullscreen':'true',
                                            'allowscriptaccess':'always',
                                            'type':'application/x-shockwave-flash',
                                            'src':'http://www.youtube.com/v/'+movID+'&autoplay=1&fs=1&fmt=18'
                                        })
                                )
                        .appendTo(jQuery('body'))

    },
    
    
    buildGal: function() {
        
        var conf = this.conf,
            url = conf.anc,
            height = 480,
            width  = 690
        ;
        
       
                jQuery('<div></div>')
                        .attr('id','lightboxContent')
                         .css({
                               'position':((jQuery.browser.msie) && (jQuery.browser.version == '6.0')) ? 'absolute' : 'fixed',
                               'z-index':'199',
                               'top' : (jQuery(window).height() - height)/2+'px',
                               'left': (jQuery(window).width()  - width )/2+'px',
                               'display':'block',
                               'margin':'0',
                               'padding':'0'
                               })
                        .append(jQuery('<iframe>')
                                   .attr({
                                        'width':width+'px',
                                        'height':height+'px',
                                        'frameborder':'0',
                                        'allowtransparency':'true',
                                        'scrolling':'no',
                                        'src': url
                                        })
                                )
                        .appendTo(jQuery('body'))
    },    

    contentImage : function() {
        
        var conf = this.conf,
            contentImageUrl = conf.anc
        ;
        
        var preloader = jQuery('<img />')
                            .attr({
                                    src:conf.preloader,
                                    position:'absolute',
                                    id : 'preloader'
                                })
                            .load(function() {
                             
                                        jQuery('<div></div>')
                                            .attr('id','lightboxContent')
                                            .append(preloader)
                                            .css({
                                                    'position':((jQuery.browser.msie) && (jQuery.browser.version == '6.0')) ? 'absolute' : 'fixed',
                                                    'z-index':'199',
                                                    'width':preloader.width()+'px',
                                                    'height':preloader.height()+'px',
                                                    'top' : (jQuery(window).height() - preloader.height())/2+'px',
                                                    'left': (jQuery(window).width()  - preloader.width() )/2+'px',
                                                    'display':'block',
                                                    'margin':'0',
                                                    'padding':'0'
                                                })
                                            .appendTo(jQuery('body'))
                             
                             //alert('loaded');
                            })
        ;

                
        var contentImg = jQuery('<img />')
                                .attr({
                                        id:'cntImage',
                                        src : contentImageUrl
                                        })
                                .load(function () { 
                                            preloader.remove();
                                            jQuery('div#lightboxContent')
                                                .append(contentImg)                    
                                                .css({
                                                        'width':contentImg.width()+'px',
                                                        'height':contentImg.height()+'px',
                                                        'top' : (jQuery(window).height() - contentImg.height())/2+'px',
                                                        'left': (jQuery(window).width()  - contentImg.width())/2+'px'
                                                 })
                                                    
                                }) 
        ;
                    
                                                    
    },
    
    destroy: function() {
        
        jQuery('#lightboxContent').fadeOut(500, function() { jQuery('#lightboxContent').remove(); } );
        jQuery('#lightbox').fadeOut(500, function() { jQuery('#lightbox').remove(); } );
        jQuery(window).unbind('resize');
        location.href = '#';

    }
    

}


/**
 * **********************************************************************
 * **********************************************************************
 * bbcom Twitter Import Object
 *
 * @author Benedikt Bast
 * @date 2010-08-01
 *
 * @version 1.0.9
 *
 *
 * @tested Firefox 3, IE6-7-8, WebKit, Opera10+
 * @requires jQuery v1.4.2
 * @requires bbcom Object for initializing
 * @requires bbcom Date Object 1+
 * @requires bbcom hasHandler
 *
 * **********************************************************************
 * ******
 */

bb.getTweet = {

    conf : {
      'twUser' :'BenediktBast',
      'twMax':2
    },
        

    importTwitterJSON: function() {
        
        var conf = this.conf;

            //jQuery.getJSON('http://search.twitter.com/search.json?q=from%3A' +conf.twUser+ '&rpp=' +conf.twMax+ '&callback=?',
            jQuery.getJSON('http://twitter.com/statuses/user_timeline/'+ conf.twUser +'.json?count=' +conf.twMax+ '&callback=?',
                function(data) {
                    if (data.results != '') {
                        bb.getTweet.buildTweets(data);
                    } else {
                        throw new Error ("JSON empty or Path wrong")
                        }
                }
            );

    },
    
    buildTweets: function(data) {
        
        jQuery.each(data, function(i) {

            var twDate = new Date(this.created_at),
                twShowDate = bb.date.convert("%M/%D/%Y",twDate),
                twText = bb.getTweet.urlParser(this.text)
            ;

            jQuery('<div></div>')
                .addClass('tweetEntry')
                //.html(twShowDate+'<br />'+twText)
                .html(twText)
                .appendTo(jQuery('div#tweet'))
            ;
        });
        
        //bind lightbox links with hashHandler
        jQuery('div#tweet .cntImg').click(function() {bb.hashHandler()});
        
        jQuery('div#tweet')
          .css({'display':'block'})
        ;
    },
    
    
    urlParser : function (txt) {

        var urlPattern = /(\w+):\/\/([\w.-]+)\/(\S*)?/g,
            contentImgLinkPattern = /(http:\/\/)?([\w.]+)?benedikt-bast.com\/#picture=([\w.-]*)(.jpg|png|gif)/g;
            fileNamePattern = /^([\S]*)#picture=([\w.-]*)$/m;
            urlArray =  txt.match(urlPattern),
            target = '',
            linkclass = '',
            wording = ''
        ;


            if (urlArray !== null) {
                for (var i=0, l=urlArray.length; i<l; i++) {
                    // build anchor with the parsed url
                    if (urlArray[i].indexOf('benedikt-bast.com') != -1) {
                        if (contentImgLinkPattern.test(urlArray[i])) {
                            target = '_self';
                            linkclass = 'cntImg';
                            wording = urlArray[i].match(fileNamePattern)[2].toUpperCase();
                        } else {
                            target = '_self';
                            linkclass = '';
                            wording = urlArray[i];
                        }
                    } else {
                        target = '_blank';
                        linkclass = '';
                        wording = urlArray[i];
                    }
                    
                    twLink = " <a href=\"" +urlArray[i]+ "\" class=\""+ linkclass +"\" target=\""+ target +"\">" +wording+ "</a>";
                    // replace the url-string with the built anchor
                    txt = txt.replace(urlArray[i], twLink);
                }
            } 
        
        return txt;
        
    }
}


/**
 * **********************************************************************
 * **********************************************************************
 * bbcom Date Object
 * converts Time Stamp
 *
 * @author Benedikt Bast
 * @date 2010-07-14
 *
 * @version 1.0.0
 *
 *
 * @tested Firefox 3, IE6-7-8, WebKit, Opera10+
 * @requires jQuery v1.4.2
 * 
 *
 * **********************************************************************
 * ******
 */

bb.date = {
    
    conf : {
        dateRegExp : new RegExp("%[dDmwMByY]","g"),
        monthNames : {
            de : ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],
            en : ["January","February","March","April","May","Juny","July","August","September","October","November","December"]
        },
        weekDay : {
            de : ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
            en : ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
        }
    },

    convert : function (dateFormat,date,lang) {

        var dateRegExp = bb.date.conf.dateRegExp;

        date = date || new Date();
        lang = lang || "en";

        return dateFormat.replace(dateRegExp, function(m){
               switch(m) {   
                case "%B" : return bb.date.conf.monthNames[lang][date.getMonth()];
                case "%d" : return date.getDate();
                case "%D" : return ((date.getDate()+1) < 10 ) ? '0' + (date.getDate()) : (date.getDate());
                case "%m" : return (date.getMonth()+1);
                case "%M" : return ((date.getMonth()+1) < 10 ) ? '0' + ((date.getMonth())+1) : (date.getMonth()+1);
                case "%y" : return date.getYear();
                case "%Y" : return date.getFullYear();
                case "%w" : return bb.date.conf.weekDay[lang][date.getDay];
                default   : return "";
            }
        });         
        
    }

}

//alert(new Date('Fri Jul 30 07:30:17 +0000 2010'));
//alert(bb.date.convert('%M / %D / %Y',new Date('Mon, 1 Mar 2010 17:54:03 +0000'),'de'));