/**
 *  Cuban Council
 *  Work page JS
 *
 *  Dependencies
 *  - jQuery
 *
 */

(function($) {

    var cssOpacity = $('html').attr('class').match(/opacity/);
    var isIE = $('html').hasClass('ie');

    var CubanHome = {

        init: function() {

            // clients list
            // todo: this needs to be smoother
            $('.btn-showclients').click(function(e) {
                e.preventDefault();
                var self = this;
                var winScroll = $(window).scrollTop();
                if ($('.home-clients .clients-wall').css('height') == '44px') {
                    var newWinScroll = (winScroll+parseInt(clientsFullHeight)) - 44;
                    $('.home-clients .clients-wall').animate({ height: clientsFullHeight }, { queue: false, duration: 400, easing: 'easeOutQuad', step: function() { $(window).trigger('resize'); } });
                    if (!isIE) {
                        $('body, html').animate({"scrollTop": newWinScroll}, 400);
                    }
                    $(self).addClass('btn-hideclients');
                } else {
                    $('.home-clients .clients-wall').animate( { height: '44px' }, { queue: false, duration: 400, easing: 'easeOutQuad', step: function() { $(window).trigger('resize'); } });
                    $(self).removeClass('btn-hideclients');
                }
            });

            // news
            CubanHome.newsWheel();

            // twitter
            CubanHome.twitterFix();

            // messaging
            CubanHome.sssssSecret();

            // work mouseovers
            $('.box-werktb a').mouseenter(function(){
                if (cssOpacity) {
                    $(this).children('.werktb-over').fadeIn(200);
                } else {
                    $(this).children('.werktb-over').css('display','block');
                }
            }).mouseleave(function(){
                if (cssOpacity) {
                    $(this).children('.werktb-over').fadeOut(200);
                } else {
                    $(this).children('.werktb-over').css('display','none');
                }
            });

        },

        newsWheel: function() {
            
            var newsWheelSel = 1;
            //$('.npimg img').hide();

            var updateNewsImageSize = function(ele) {
                var minWidth = 290;
                var minHeight = 290;
                var w = $(ele).width();
                var h = $(ele).height();
                var ratio = w / h;
                if (ratio > 1) {
                    $(ele).css('height', minHeight + 'px');
                    $(ele).css('width', (minHeight * ratio) + 'px');
                } else {
                    $(ele).css('width', minWidth + 'px');
                    $(ele).css('height', (minWidth / ratio) + 'px');
                }
                $(ele).fadeIn('fast');
            }

            $('.npimg img').each(function() {
                var self = this;
                $(self).bind('load', function() {
                    updateNewsImageSize(self);
                });
                if ($(self).width() > 290 && $(self).height() > 290) {
                    updateNewsImageSize(self);
                } else {
                    $(self).show();
                }
            });

            // left arrow
            $('.home-news .arr-l').click(function(e) {
                e.preventDefault();
                if (newsWheelSel < newsWheelNum) {
                    $('.home-news .arr-r').removeClass('linkoff');
                    curTxt = $('#nptxt'+(newsWheelSel));
                    newTxt = $('#nptxt'+(newsWheelSel+1));
                    // fade text
                    curTxt.fadeOut(200, function() {
                        newTxt.css({'opacity': '1', 'display': 'none'});
                        newTxt.fadeIn(100);
                    });
                    // slide out current image
                    $('#npimg'+(newsWheelSel)).animate( { left: '341px', top: '-320px' }, { queue:false, duration:300 });
                    // slide in new image
                    $('#npimg'+(newsWheelSel+1)).css({'left': '-341px'});
                    $('#npimg'+(newsWheelSel+1)).css({'top': '320px'}).animate( { left: '0px', top: '0px' }, { queue:false, duration:300 });
                    // update link
                    newsWheelSel++;
                    if (newsWheelSel == newsWheelNum) {
                        $('.home-news .arr-l').addClass('linkoff');
                    }
                }
            });

            // right arrow
            $('.home-news .arr-r').click(function(e) {
                e.preventDefault();
                if (newsWheelSel > 1) {
                    $('.home-news .arr-l').removeClass('linkoff');
                    curTxt = $('#nptxt'+(newsWheelSel));
                    newTxt = $('#nptxt'+(newsWheelSel-1));
                    // fade text
                    curTxt.fadeOut(200, function() {
                        newTxt.css({'opacity': '1', 'display': 'none'});
                        newTxt.fadeIn(100);
                    });
                    // slide out current image
                    $('#npimg'+(newsWheelSel)).animate( { left: '-341px', top: '320px' }, { queue:false, duration:300 });
                    // slide in new image
                    $('#npimg'+(newsWheelSel-1)).css({'left': '341px'});
                    $('#npimg'+(newsWheelSel-1)).css({'top': '-320px'}).animate( { left: '0px', top: '0px' }, { queue:false, duration:300 });
                    // update link
                    newsWheelSel--;
                    if (newsWheelSel == 1) {
                        $('.home-news .arr-r').addClass('linkoff');
                    }
                }
            });

        },

        twitterFix: function() {

            var tweetsCurHeight = 0;
            var tweetsMaxHeight = parseInt($('.news-tweets').css('height'));
            var tweetsPad = 0;

            $('.news-tweets li').each(function() {
                eleHeight = $(this).innerHeight();
                if ((tweetsCurHeight + eleHeight) < (tweetsMaxHeight + 1)) {
                    // all good
                    tweetsCurHeight = tweetsCurHeight + eleHeight;
                } else {
                    $(this).remove();
                }
            });

            if (tweetsCurHeight < 119) {
                tweetsPad = parseInt(((tweetsMaxHeight - tweetsCurHeight) / 2));
                tweetsPad = tweetsPad - 1;
                $('.news-tweets').css('padding-top', tweetsPad + 'px');
                $('.news-tweets').css('height', (tweetsMaxHeight - tweetsPad) + 'px');
            }

        },

        sssssSecret: function() {

            var decoderRing = function(str) {
                var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
                var invalid = {
                    strlen: (str.length % 4 != 0),
                    chars:  new RegExp('[^' + chars + ']').test(str),
                    equals: (/=/.test(str) && (/=[^=]/.test(str) || /={3}/.test(str)))
                };
                if (invalid.strlen || invalid.chars || invalid.equals) {
                    throw new Error('Invalid base64 data');
                }
                var decoded = [];
                var c = 0;
                while (c < str.length) {
                    var i0 = chars.indexOf(str.charAt(c++));
                    var i1 = chars.indexOf(str.charAt(c++));
                    var i2 = chars.indexOf(str.charAt(c++));
                    var i3 = chars.indexOf(str.charAt(c++));
                    var buf = (i0 << 18) + (i1 << 12) + ((i2 & 63) << 6) + (i3 & 63);
                    var b0 = (buf & (255 << 16)) >> 16;
                    var b1 = (i2 == 64) ? -1 : (buf & (255 << 8)) >> 8;
                    var b2 = (i3 == 64) ? -1 : (buf & 255);
                    decoded[decoded.length] = String.fromCharCode(b0);
                    if (b1 >= 0) decoded[decoded.length] = String.fromCharCode(b1);
                    if (b2 >= 0) decoded[decoded.length] = String.fromCharCode(b2);
                }
                return decoded.join('');
            }

            if (Math.round(Math.random() * 10) == 5) {
                if ($('#cc-msg').html() != "") {
                    var msg = $('<div>' + decoderRing($("#cc-msg").html()) + '</div>');
                    var wrap = $('<div></div>');
                    $('#cc-msg').remove();
                    wrap.css({
                        "position": "fixed",
                        "display":"none",
                        "top": "0",
                        "left": "0",
                        "z-index": "1000",
                        "width": "100%",
                        "height": "100%"
                    })
                    msg.css({
                        "display":"table-cell",
                        "background-color": "#ff739e",
                        "color": "#000",
                        "font-size":"150px",
                        "line-height":"155px",
                        "letter-spacing":"-2px",
                        "font-weight":"bold",
                        "vertical-align":"middle",
                        "text-align":"center"
                    })
                    $('body').append(wrap.append(msg));
                    window.setTimeout(function() {
                        wrap.css('display','table');
                        window.setTimeout(function() {
                            wrap.remove();
                        }, 150);
                    }, Math.random() * 5000 + 5000);
                }
            }
        }

    };

    window.CubanHome = CubanHome;

    $(document).ready(function() {
        CubanHome.init();
    });

})(jQuery);
