function SmoothScroll() {
    $('.scroll').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace('/^\//', '')
	  && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target
		|| $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body')
		  .animate({ scrollTop: targetOffset }, 1000);
                return false;
            }
        }
    });
}

// Gallery Widget - Image Flow	
function GalleryWidget() {

    var imageCount = $("div#imageThumbs img").size();
    var centerImage = Math.round(imageCount / 2);

    var instanceOne = new ImageFlow();
    instanceOne.init({
        ImageFlowID: 'imageThumbs',
        captions: false,
        reflections: false,
        startID: centerImage,
        circular: true,
        buttons: true,
        imageFocusMax: 3,
        percentLandscape: 145,
        aspectRatio: 3,
        xStep: 120,
        imageCursor: 'pointer',
        opacity: true,
        opacityArray: [10, 10, 8, 2],
        onClick: function() {
            Shadowbox.open({
                content: $(this).attr("longdesc"),
                player: "img",
                title: $(this).attr("title")
            });
        }
    });
}

// Accordion
function Accordion() {

    var togglers = $('.accordion .section > h2 a');
    var elements = ".accordion .sectionContent";

    $(elements).hide();
    //$(elements + ':first').show()
    //$('.accordion .section > h2 a:first span').addClass('active');
    togglers.click(
 function() {
     var checkElement = $(this).parent().next();
     if ((checkElement.is(elements)) && (checkElement.is(':visible'))) {
         $(elements + ':visible').slideUp(300);
         $(this).children().removeClass('active');
         return false;
     }
     if ((checkElement.is(elements)) && (!checkElement.is(':visible'))) {
         $(elements + ':visible').slideUp(300);
         checkElement.slideDown(300);
         $(this).children().addClass('active');
         return false;
     }
 });

}

function relTime(time_value) {
    time_value = time_value.replace(/(\+[0-9]{4}\s)/ig, "");
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
    if (timeago < 60) return 'less than a minute ago';
    else if (timeago < 120) return 'about a minute ago';
    else if (timeago < (45 * 60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
    else if (timeago < (90 * 60)) return 'about an hour ago';
    else if (timeago < (24 * 60 * 60)) {
        var hours = (parseInt(timeago / 3600));
        var plural = '';
        if (hours > 1) {
            plural = 's';
        }
        return 'about ' + hours.toString() + ' hour' + plural + ' ago';
    }
    else if (timeago < (48 * 60 * 60)) return '1 day ago';
    else return (parseInt(timeago / 86400)).toString() + ' days ago';
}

function urlToLink(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1'>$1</a>");
}

function PopulateTwitterPod() {
    $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=TopDrawerLondon&count=20&callback=?", 
        function(tweetdata) {
            var tweetPod = $("#tweetList");
            tweetPod.empty();
            var tweetFooter = $("#tweet");
            tweetFooter.empty();

            $.each(tweetdata, function(i, tweet) {
                PopulateTweetPod(i, tweet, tweetPod);
                PopulateTweetFooter(i, tweet, tweetFooter);
            }
            );
        }
    );
}

function PopulateTweetPod(i, tweet, tweetlist) {
    var content = "";
    if (i < 3) {

        content = content + ('<li>');
        content = content + ('<p>' + urlToLink(tweet.text) + '</p>');
        content = content + ('<p>Posted ' + relTime(tweet.created_at) + '</p>')
        content = content + ('</li>');

        tweetlist.append(content);
    }
}
function PopulateTweetFooter(i, tweet, tweetlist) {
    var content = "";
    if (i < 1) {
        content = content + ('<p>' + urlToLink(tweet.text) + '</p>');
        content = content + ('<p class="timeStamp">Posted ' + relTime(tweet.created_at) + '</p>')
        tweetlist.append(content);
    }
}


$(document).ready(function() {

    Shadowbox.init();
    SmoothScroll();
    GalleryWidget();
    Accordion();
    $(document).pngFix();

    var volatile = $("input[type=text]")
    volatile.focus(function(event) {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        } 
    }, volatile.blur(function(event) {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    }
    ));


    // CarouFredSel

    var slideCounter = $('div#primary .carousel ul.slider li').size();
    $("div#primary .carousel ul.slider li:not(:first) a").attr("tabIndex", "-1");
    $("div#primary .carousel ul.slider").carouFredSel({
        items: {
            visible: 1
        },
        scroll: {
            pauseOnHover: true,
            duration: 1000,
            easing: "easeInOutExpo",
            onBefore: function(oldItems, newItems) {
                oldItems.children('a').attr("tabIndex", "-1");
                newItems.children('a').removeAttr("tabIndex");
            }
        },
        prev: "div#primary .carousel div.controls .prev",
        next: "div#primary .carousel div.controls .next",
        pagination: {
            container: ".carouselNav",
            anchorBuilder: function(nr) {
                var str = '<li><a href="#">';
                str += 'Slide' + ' ' + nr + ' ' + 'of' + ' ' + slideCounter;
                str += '</a></li>';
                return str;
            }
        }
    });

    $("div#secondary .carousel ul.slider").carouFredSel({
        items: {
            visible: 4
        },
        scroll: {
            duration: 800,
            items: 1
        },
        auto: true,
        prev: "div#secondary .carousel div.controls .prev",
        next: "div#secondary .carousel div.controls .next"
    });

    //Iframe
    $('.iframe').click(function(e) {
        e.preventDefault();
        var $this = $(this);

        if ($this.attr('rel')) {
            var dialogDimensions = $this.attr('rel').split("x");
            var dialogWidth = dialogDimensions[0]
            var dialogHeight = dialogDimensions[1]
        }
        else {
            var dialogWidth = 500
            var dialogHeight = 500
        }

        $('<div><iframe class="externalSite" width="100%" height="100%" frameborder="0" src="' + this.href + '" /></div>').dialog({
            title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
            width: dialogWidth + "px",
            height: dialogHeight,
            close: function(event, ui) {
                $(this).dialog("destroy");
                $(".externalSite").remove();
                $(".ui-widget-overlay").remove();
            }
        });

        $(".ui-dialog").has('iframe').before("<div class='ui-widget-overlay'></div>");

        function dialogOverlayResize() { $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001"); }

        $(window).resize(function() { dialogOverlayResize(); });
        dialogOverlayResize();

    });

    // Register Colour

    var registerColours = ["#f4792a", "#39ba8b", "#f7b810", "#d9378d", "#00a8b1"];
    var colourPos = 0;

    $('.registerCta').css({ backgroundColor: registerColours[0] });
    changeColour()

    function changeColour() {
        $('.registerCta').animate({ backgroundColor: registerColours[colourPos] }, 1000, null, function() {
            colourPos += 1;
            if (colourPos >= registerColours.length) {
                colourPos = 0;
            }
            setTimeout(function() { changeColour(); }, 2500);
        });

    }

    //Scroller	
    $("#exhibitorList").liScroll({ travelocity: 0.07 });

    //Sectors
    $(".sectorList li a").hover(function() {
        $(this).children('span').animate({ top: 0 });
    }, function() {
        $(this).children('span').animate({ top: 150 });
    });

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    var VIDEO_ID = 'o20D9cgZiws';
    
    swfobject.embedSWF("http://www.youtube.com/e/" + VIDEO_ID + "?enablejsapi=1&version=3&playerapiid=ytplayer",
                       "ytapiplayer", "540", "300", "8", null, null, params, atts);

    //Twitter Pod
     PopulateTwitterPod();
});

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
   if (newState == 1){
        $("div#primary .carousel ul.slider").trigger("pause");
        $("div#primary .carousel ul.slider").trigger("configuration", scroll.pauseOnHover, false);
        
   } else if (newState == 2){
        $("div#primary .carousel ul.slider").trigger("configuration", scroll.pauseOnHover, true);
        $("div#primary .carousel ul.slider").trigger('play');
   }
}
