var blogNumPostsToDisplay = 1;
var blogDescMaxLen = 190;
var blogCache = null;
var slides = null;
var carouselManualMode = false;
var isInitialLoad = true;
var youtubeControlsHeight = 20;
var videoWidth = 848;
var videoHeight = 480;
var cycleCount = 0;

$(document).ready(function () {
    var numTestimonials = ('#testimonialList li').length;
    var numSlides = $('#carousel>li').length;

    $('div.slide').each(function () {
        $(this).css('display', 'block');
    });

    showRandomTestimonial();

    $('#nextTestimonial').bind('click', function () {
        var testimonials = $('#testimonialList li'),
            active = $('#testimonialList li:visible'),
            numTestimonails = testimonials.length,
            testimonialIndex = testimonials.index(active);

        if (testimonialIndex < numTestimonails - 1) {
            // not the last testimonial
            testimonialIndex++;
        } else {
            // start from the beginning
            testimonialIndex = 0;
        }

        active.fadeOut(function () {
            $('#testimonialList li:eq(' + testimonialIndex + ')').fadeIn();
        });

        return false;
    });


    /* Carousel Setup */
    /*$('#carousel').jcarousel({
    scroll: 1,
    auto: 3,
    wrap: 'last',
    initCallback: mycarousel_initCallback,
    // This tells jCarousel NOT to autobuild prev/next buttons
    buttonNextHTML: null,
    buttonPrevHTML: null,
    itemVisibleInCallback: function (carousel, li, index, state) {
    if (state !== 'init') {
    var zeroBasedIndex = index - 1;
    markAsSelected($('#selection li:eq(' + zeroBasedIndex + ')'));
    }
    }
    });*/


    slides = $('#carousel').cycle({
        timeout: 5000,
        before: function (currSlideElement, nextSlideElement, options, forwardFlag) {
            if (!carouselManualMode) {
                var index = 0;

                // can we still move foward?
                if (options.currSlide < numSlides - 1) {
                    index = options.currSlide + 1;
                } else {
                    //CycleComplete();
                }

                // ignore before event on page load
                if (isInitialLoad) {
                    index = 0;
                    isInitialLoad = false;
                }

                markAsSelected($('#selection li:eq(' + index + ')'));
            }
        }
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    $('div.slide').hover(function () {
        slides.cycle('pause');
    }, function () {
        if (!carouselManualMode) {
            slides.cycle('resume');
        }
    });

    var buttons = $('#selection li a').bind('click', function () {
        // we've now taken manual control over the slides
        carouselManualMode = true;

        // get the one-based index of the button pressed
        var index = buttons.index(this);

        // lets set the new slide
        slides.cycle(index);
        slides.cycle('pause');
    });



    /* Carousel buttons */
    $('#selection li:not(li.selected) img.active').each(function () {
        $(this).hide();
    });

    $('#selection li a').hover(function () {
        // hover in
        $('img.active', $(this)).fadeIn();
    }, function () {
        // hover out
        // don't fadeout if we're hovering over the currently selected li
        if (!$(this).parent().hasClass('selected')) {
            $('img.active', $(this)).fadeOut();
        }
    });

    $('#selection li a').bind('click', function () {
        markAsSelected($(this).parent());
        return false;
    });

    /* Hover graphics (older ie doesn't support hover over divs with css) */
    $('#corePracticeAreaHeader a').hover(function () {
        $(this).parent().css('background-image', "url('graphics/gs_home_core_prac_hover.gif')");
    }, function () {
        $(this).parent().css('background-image', "url('graphics/gs_home_core_prac.gif')");
    });

    $('#syndicatedResearchHeader a').hover(function () {
        $(this).parent().css('background-image', "url('graphics/gs_home_surveys_trends_hover.gif')");
    }, function () {
        $(this).parent().css('background-image', "url('graphics/gs_home_surveys_trends.gif')");
    });

    /* Fancy box */
    $('.fancybox').fancybox({
        autoScale: false
    });

    $('.fancybox').bind('click', function () {
        $('#fancybox-content').css('border-color', 'white');
        $('#fancybox-outer').css('background', 'white');
    });

    $('a.vimeo').fancybox({
        'padding': 8,
        'margin': 0,
        'autoScale': false,
        'titleShow': false,
        'type': 'iframe',
        'autoDimensions': false,
        'width': videoWidth,
        'height': videoHeight + youtubeControlsHeight,
        'overlayOpacity': 0.8,
        'overlayColor': '#222'
    });

    $('a.vimeo').bind('click', function () {
        $('#fancybox-content').css('border-color', '#111');
        $('#fancybox-outer').css('background-color', '#111');
    });
	
    $('a.vzaar').fancybox({
        /*'padding': 8,
        'margin': 0,
        'autoScale': false,
        'titleShow': false,
        'type': 'inline',*/
        'overlayOpacity': 0.8,
        'overlayColor': '#222',
        'onClosed': function() { 
            $('#videoEmbedContainer iframe').attr('src', videoSrc) 
        }
    });
    
    var videoSrc = $('#videoEmbedContainer iframe').attr('src');

    $('a.vzaar').bind('click', function () {
        $('#fancybox-content').css('border-color', '#111');
        $('#fancybox-outer').css('background-color', '#111');
    });
	
    $('a.video').fancybox({
        'padding': 8,
        'margin': 0,
        'autoScale': false,
        'titleShow': false,
        'type': 'inline',
        /*'autoDimensions': false,
        'width': videoWidth,
        'height': videoHeight + youtubeControlsHeight,
        */
        'overlayOpacity': 0.8,
        'overlayColor': '#222'
    });

    $('a.video').bind('click', function () {
        $('#fancybox-content').css('border-color', 'transparent');
        $('#fancybox-outer').css('background', 'transparent none');
    });


    /* Get the latest finding item */
    $.getJSON('findings/app/ajaxHandlers/api.php?type=json&maxResults=1&withCharts=true', function (data) {
        if (data.errorMessage == undefined) {
            if (data.findings != undefined && data.findings.length > 0) {
                var finding = data.findings[0];

                $("#finding-title").text(finding.title);
                $("#finding-link").attr('href', finding.link);

                // We want to cut the html if it's too long (text is one or multiple <p>text</p>)
                var paras = finding.html.split(/<\/p>\s*<p>/g);

                var maxLen = 550;
                var count = 0;
                var i = 0;
                var newHtml = '';

                // for each paragraph
                while (count < maxLen && i < paras.length) {
                    // check to see if we've breached the max char len
                    if (count + paras[i].length < maxLen) {
                        newHtml += paras[i] + '</p><p>';
                        count += paras[i].length;
                        // may need to reduce maxlen here due to paragraph adding extra space
                        maxLen -= 60;
                    } else {
                        var cutPos = getIdealCutLocation(paras[i], maxLen - count);
                        newHtml += $.trim(paras[i].substring(0, cutPos)) + '...</p>';
                        count += cutPos;
                        break;
                    }

                    i++;
                }

                newHtml = newHtml.replace(/<\/p><p>$/, '</p>');

                $("#finding-content").html(newHtml);

                if (finding.charts != undefined && finding.charts.length > 0) {
                    var chart = finding.charts[0]
                    $("#finding-image-link").attr('href', chart);
                    $("#finding-image").attr('src', chart);
                } else {
                    // no chart, so remove the container and update to the full width
                    $('#finding-image-link').remove();
                    $('#finding-content').css('width', '480px');
                }
            } else {
                // no published findings

            }
        } else {
            alert(data.errorMessage);
        }
    });
    /*#fancybox-outer {
    background:transparent none !important;
    }
    #fancybox-content {
    border-color:transparent !important;
    }*/
    /*$('a.video').each(function () {
    $(this).bind('click', function () {
    var youtubeControlsHeight = 22,
    videoWidth = 848,
    videoHeight = 480;

    $.fancybox({
    'padding': 0,
    'autoScale': false,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'title': $(this).attr('title'),
    'width': videoWidth,
    'height': videoHeight + youtubeControlsHeight,
    'overlayOpacity': 0.8,
    'overlayColor': '#222',
    'href': $(this).attr('href').replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
    'type': 'swf',
    'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true'}
    });

    return false;
    });

    });*/

    /*$('.fancybox-video').fancybox({
    autoScale: false,
    'titleShow'     : false,
    'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
    'type'      : 'swf',
    'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
    });*/




    $('#twitter a.header').bind('click', function () {
        var content = $(this).parent().find('div.content');

        if (content.is(':visible')) {
            content.slideUp();
        } else {
            content.slideDown().show(function () {
                $(this).show();
                collapseBlogColumn();
            });
        }

        $(this).toggleClass('expanded');

        return false;
    });

    $('#blog a.header').bind('click', function () {
        var content = $(this).parent().find('div.content');

        if (blogCache === null) {
            populateBlog(blogNumPostsToDisplay, blogDescMaxLen);
        } else if (content.is(':visible')) {
            content.slideUp();
        } else {
            content.slideDown(collapseTwitterColumn);
        }

        return false;
    });
});


function collapseBlogColumn() {
    $('#blog a.header').removeClass('expanded');

    var blogContent = $('#blog .content');
    if (blogContent.is(':visible')) {
        blogContent.slideUp();
    }
}

function collapseTwitterColumn() {
    $('#twitter a.header').removeClass('expanded');

    var twitterContent = $('#twitter .content');
    if (twitterContent.is(':visible')) {
        twitterContent.slideUp();
    }
}

function populateBlog(numPostsToDisplay, maxDescLength) {
    $.getFeed({
        url: 'proxy/blogger_proxy.php?count=1',
        success: function (feed) {
            if (feed.items != undefined) {
                blogCache = feed.items.slice(0, numPostsToDisplay);
                setBlogItems('#blog ul', blogCache, maxDescLength);
                $('#blog .content').slideDown(collapseTwitterColumn);
            }
        }
    });
}

function getIdealCutLocation(text, startPos) {
    var cutPos = startPos;

    var subStr = text.substring(startPos, text.length - startPos);
    var nextSpacePos = subStr.search(/[!,.;: ]/g) + startPos;
    if (nextSpacePos >= startPos) {
        cutPos = nextSpacePos;
    }

    return cutPos;
}

function setBlogItems(blogSelector, items, maxDescLength) {
    var html = '';

    for (var i = 0; i < items.length; i++) {
        var text = parseTextFromHtml(items[i].description);

        if (text != undefined && text.length > maxDescLength) {

            // attempt to cut at a space if possible
            var cutPos = getIdealCutLocation(text, maxDescLength);

            text = text.substring(0, cutPos) + "...";
        }

        // link currently isn't linking to the blog post.
        var link = 'http://globescaninsights.blogspot.com'; //items[i].link

        html += '<li>';
        html += '<h3><a href="' + link + '">' + items[i].title + '</a></h3>';
        html += '<p>' + text + '</p>';
        html += '</li>';
    }

    $(blogSelector).html(html);
}

function parseTextFromHtml(html) {
    var tmp = document.createElement('div'); 
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText;
}


function markAsSelected(li) {
    if (!li.hasClass('selected')) {
        // remove the currently selected item
        var currentSelection = $('#selection li.selected');
        currentSelection.removeClass('selected');
        $('img.active', currentSelection).fadeOut();

        // update the selected item
        li.addClass('selected');
        $('img.active', li).fadeIn();
    }
}

/*function CycleComplete() {
    cycleCount++;

    var numTestimonials = $('#testimonialList li').length;
    var index = cycleCount %testimonials = 
}*/

function random(min, max) {
    return Math.floor((Math.random() * (max - min + 1)) + min);
}

function showRandomTestimonial() {
    var testimonials = $('#testimonialList li');
    testimonials.hide();
    var randomIndex = random(0, testimonials.length - 1);
    $('#testimonialList li:eq('+ randomIndex +')').show();
} 

// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el) {
    var curOverflow = el.style.overflow;
    if (!curOverflow || curOverflow === "visible")
        el.style.overflow = "hidden";

    var isOverflowing = el.clientWidth < el.scrollWidth
      || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
}


/**
* We use the initCallback callback
* to assign functionality to the controls
*/
/*function mycarousel_initCallback(carousel) {

    
//    var numSlides = $('#carousel li').length;
//    var slideWidth = $('#carousel li:first').css('width').replace("px", "");

//    $('#carousel').css('width', slideWidth * numSlides);

    var buttons = $('#selection li a').bind('click', function () {
        // get the one-based index of the button pressed
        var index = buttons.index(this) + 1;

        // lets scroll to that item and set the automation to manual control
        carousel.scroll(index);
        carousel.stopAuto();

        carouselManualMode = true;
    });

    jQuery('.jcarousel-scroll select').bind('change', function () {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

//    jQuery('#mycarousel-next').bind('click', function () {
//        carousel.next();
//        return false;
//    });

//    jQuery('#mycarousel-prev').bind('click', function () {
//        carousel.prev();
//        return false;
//    });
    
//    // Disable autoscrolling if the user clicks the prev or next button.
//    carousel.buttonNext.bind('click', function () {
//        carousel.startAuto(0);
//    });

//    carousel.buttonPrev.bind('click', function () {
//        carousel.startAuto(0);
//    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function () {
        carousel.stopAuto();
    }, function () {
        if (!carouselManualMode) {
            carousel.startAuto();
        }
    });

};*/

