var CandiPlayer = {};

CandiPlayer.com = function () {
    var oData;
    var oOverlay;
    var oPlayer;
    var oPreviewCar;
    var oPreviewInfo;
    var oThumbCar;
    var nCurrentIndex = 0;
    var nSlideSpeed = 750;
    var bPreviewAnimate = false;
    var bThumbAnimate = false;
    var oPagination;
    var bLastScreen = false;
    var bFirstRun = true;
    var nPageHeight;
    var oBrowse = 'all';

    //Private methods
    function buildLayout() {

        bFirstRun = false;
        nPageHeight = $('#page').height();

        //Build player wrapper
        $('body')
			.append('<div id="overlay"></div>')
			.append('<div id="candi-player"></div>');

        oOverlay = $('#overlay');
        oPlayer = $('#candi-player');

        //Build containing modules for player
        oPlayer
			.append('<div class="top-bar"><a href="">close</a></div>')
			.append('<div class="preview-carousel"></div>')
			.append('<div class="preview-info clearfix"></div>')
			.append('<div class="thumb-carousel"></div>');

        oPreviewCar = $('.preview-carousel');
        oPreviewInfo = $('.preview-info');
        oThumbCar = $('.thumb-carousel');
        buildPreviewCar();
        buildPreviewInfo();

        oThumbCar
			.append('<div class="draw-top active" id="d_all"><p>BROWSE ALL</p></div><div class="draw-content"></div>')
			.append('<div class="draw-top" id="d_brand"><p>' + oData.caseStudy.client + '</p></div><div class="draw-content"></div>')
			.append('<div class="draw-top" id="d_service"><p>' + oData.caseStudy.service + '</p></div><div class="draw-content last"></div>');

        oThumbCar.find('.draw-content').append('<a class="left" href="#">left</a><div class="thumb-window"><div class="thumb-list"></div></div><a class="right" href="#">right</a>');

        for (var i = 0; i < oData.thumbList.length; i++) buildThumbs(i);

        oThumbCar.find('.draw-content').eq(0).css({ 'width': 855 }).addClass('open');

        //Center player and setup resize function to center player on browser resize
        centerImage(oPlayer);
        $(window).resize(function () {
            centerImage(oPlayer);
        });

        bindClicks();
        oOverlay.css({ 'height': nPageHeight }).fadeIn(function () {
            $(this).removeAttr('style').css({ 'height': nPageHeight }).show();
        });

        //Open the correct thumb drawer
        var index = oBrowse === 'all' ? 0 : oBrowse === 'brand' ? 1 : oBrowse == 'service' ? 2 : 0;
        if (index > 0) {
            // open the draw
            var oThis = $(oThumbCar.find('.draw-top')[index]).click();
        }

        //Wait for thumbs to load in then trigger intro animation
        var iCount = 1;
        if (navigator.appName == 'Opera') animationIntro();
        else {
            oPlayer.find('.thumb img').load(function () {
                if (iCount < $('.thumb-list img').length) iCount++
                else animationIntro();
            });
        }
    };

    function animationIntro() {
        oPreviewInfo.css({ 'margin-top': '-100px' }).hide();
        oThumbCar.css({ 'margin-top': '-161px' }).hide();
        $('.top-bar').show();
        oPreviewCar.css({ 'margin-top': '-40px' });
        oPlayer.css({ 'top': '140px' });

        // We animate differently for IE as the pretty animation is clunky
        if (navigator.appName == 'Microsoft Internet Explorer') {
            oPlayer.fadeIn(function () {
                oPlayer.animate({ 'top': 100 }, 500);
                oPreviewCar.animate({ 'margin-top': 0 }, 500);
                oPreviewInfo.show().animate({ 'margin-top': 0 }, 200);
                oThumbCar.show().animate({ 'margin-top': 0 }, 200);
                oPreviewInfo.data('height', oPreviewInfo.height()).css({ 'height': '69px' });
                showPagination();

                // Set the correct width of the draw in IE
                var wt = $(oThumbCar.find('.draw-top').eq(2).find('p')).width();
                // IE returns height and width as opposites so the following only applies to IE
                if (wt < 24) $(oThumbCar.find('.draw-top').eq(2).find('p')).css({ 'left': '9px', 'width': '108px' }); else $(oThumbCar.find('.draw-top').eq(2).find('p')).css({ 'left': '3px', 'width': '119px' });
            });
        }
        else {
            oPlayer.fadeIn(function () {
                oPlayer.animate({ 'top': 100 }, 1000);
                oPreviewCar.animate({ 'margin-top': 0 }, 1000);
                oPreviewInfo.show().animate({ 'margin-top': 0 }, 1000);
                oThumbCar.show().animate({ 'margin-top': 0 }, 1000);
                oPreviewInfo.data('height', oPreviewInfo.height()).css({ 'height': '69px' });
                showPagination();
            });
        }

        // Make sure the browser is scrolled to the top
        $(document).scrollTo(0, 0);
    };


    function buildPreviewCar() {
        //RP - 20111020: fix if no images are available
        if (oData.caseStudy.images.length > 0) {
            oPreviewCar.html('<img class="viewed" src="' + oData.caseStudy.images[0].image + '" width="950" height="336" />');
        }
        else {
            oPreviewCar.html('<img class="viewed" width="950" height="336" />');
        }
        //RP - 20111020: fix if no images are available

        //Add browsing arrows to preview carousel
        oPreviewCar
			.append('<a class="arrow-left" href="">left</a><a class="arrow-right" href="">right</a>')
			.append('<div class="pagination"><ul></ul></a>');

        //setup pagination
        oPagination = oPreviewCar.find('.pagination');
        for (var i = 0; i < oData.caseStudy.images.length; i++) {
            oPagination.find('ul').append('<li><a href="#">' + (i + 1) + '</a></li>');
        };
        updatePagination();
    };

    function buildPreviewInfo() {
        var quote = oData.caseStudy.quote.text.length > 0 ? '<div class="quote"><div class="top"></div><p class="text">' + oData.caseStudy.quote.text + '</p><p class="qoutee"> - ' + oData.caseStudy.quote.quotee + '<br/>' + oData.caseStudy.quote.position + '</p></div>' : '';
        var insight = oData.caseStudy.overview.insight!=null ? '<h3>Insight</h3><p>' + oData.caseStudy.overview.insight + '</p>' : '';

        oPreviewInfo
			.html('<div class="left-col"></div><div class="right-col"></div><a class="show-hide-cs show" href="#">Show case study</a>')
			.find('.left-col').append('<div class="project-titles"><p>Client: <span>' + oData.caseStudy.client + '</span></p><p>Project: <span>' + oData.caseStudy.project + '</span></p><p>Service: <span>' + oData.caseStudy.service + '</span></p></div>' + quote).end()
			.find('.right-col').append('<p class="intro">' + oData.caseStudy.intro + '</p><div class="overview"><h3>Answer</h3><p>' + oData.caseStudy.overview.answer + '</p>' + insight + '<h3>Solution</h3><p>' + oData.caseStudy.overview.solution + '</p><h3>Results</h3><p class="results"></p></div>');

        for (var i = 0; i < oData.caseStudy.overview.results.length; i++) {
            oPreviewInfo.find('.overview p.results').append('<span>' + oData.caseStudy.overview.results[i].listItem + '</span>');
        };
    };

    function buildThumbs(i) {
        for (var j = 0; j < oData.thumbList[i].thumbs.length; j++) {
            oThumbCar.find('.draw-content').eq(i).find('.thumb-list').append('<div class="thumb"><img src="' + oData.thumbList[i].thumbs[j].thumb + '" width="139" height="90" /><div class="overlay"></div><div class="thumb-info"> <p class="client">' + oData.thumbList[i].thumbs[j].client + '</p> <p>' + oData.thumbList[i].thumbs[j].project + '</p><p>' + oData.thumbList[i].thumbs[j].service + '</p> </div></div>');
        };

        if (oData.thumbList[i].thumbs.length < 6) {
            oThumbCar.find('.draw-content').eq(i).find('.left').replaceWith('<div class="left noLink"></div>');
            oThumbCar.find('.draw-content').eq(i).find('.right').replaceWith('<div class="right noLink"></div>');
        }

        //Fading in text for thumb carousel
        $('.draw-content .thumb').hover(
            function () {
                $(this).find('.overlay, .thumb-info').fadeIn('slow');
            },
            function () {
                $(this).find('.overlay, .thumb-info').stop(true, true).fadeOut('fast');
            }
        );
    };

    function loadNewContent() {
        nCurrentIndex = 0;
        bLastScreen = false;
        buildPreviewCar();
        buildPreviewInfo();
        // We don't reload the thumbs for the active thumb drawer
        var bse = $('.draw-top.active').attr('id');
        if (bse != 'd_brand') {
            oThumbCar.find('.draw-top').eq(1).find('p').html(oData.caseStudy.client);
            oThumbCar.find('.draw-content').eq(1).find('.thumb-list').empty();
            buildThumbs(1);
        }
        if (bse != 'd_service') {
            oThumbCar.find('.draw-top').eq(2).find('p').html(oData.caseStudy.service);
            if (navigator.appName == 'Microsoft Internet Explorer') {
                // Set the position based on the size of the text! (only in IE)
                var wt = $(oThumbCar.find('.draw-top').eq(2).find('p')).width();
                //console.log('height:' + $(oThumbCar.find('.draw-top').eq(2).find('p')).height() + '  width: ' + $(oThumbCar.find('.draw-top').eq(2).find('p')).width());
                // IE returns height and width the opposite way around to other browsers!
                if (wt < 24) $(oThumbCar.find('.draw-top').eq(2).find('p')).css({ 'left': '9px', 'width': '108px' }); else $(oThumbCar.find('.draw-top').eq(2).find('p')).css({ 'left': '3px', 'width': '119px' });
            }
            oThumbCar.find('.draw-content').eq(2).find('.thumb-list').empty();
            buildThumbs(2);
        }
        showPagination();
        oPreviewCar.fadeTo(500, 1);
        oPreviewInfo.fadeTo(500, 1, function () {
            bindClicks();

            // open the correct thumb drawer
            var index = oBrowse === 'all' ? 0 : oBrowse === 'brand' ? 1 : oBrowse == 'service' ? 2 : 0;
            if (index > 0) oThumbCar.find('.draw-top')[index].click();

            //Must display full height content to get real height, this isn't noticable to the user
            oPreviewInfo.removeAttr('style');
            //Grab height and strink height down to hidden state
            oPreviewInfo.data('height', oPreviewInfo.height()).css({ 'height': '69px' });
        });
    };

    function fadeOutContent(sProjectRequest) {
        //  oThumbCar.find('.draw-top').eq(0).click();
        if ($('.show-hide-cs').hasClass('hide')) $('.show-hide-cs').click();
        unbindClicks();
        oPreviewCar.fadeTo(500, 0);
        oPreviewInfo.fadeTo(500, 0, function () {
            loadData(sProjectRequest);
        });
    };

    function loadData(sRequestedData, browse) {
        $.ajax({
            //Params for AJAX request
            type: 'GET',
            url: '/json/' + sRequestedData + '.json',
            dataType: 'json',

            //Sucessful callback
            success: function (data) {
                _gaq.push(['_trackEvent', 'CandiPlayer', 'view-case-study', data]);
                //Assign variable for global usage
                oData = data;
                oBrowse = browse;
                //Run different method depending on first load of data loaded with in player
                if (bFirstRun) buildLayout();
                else loadNewContent();
            },
            error: function (e) {
                alert('Failed to load data\nStatus: ' + e.statusText);
            }
        });
    };

    function hidePagination() {
        oPagination.animate({ 'bottom': '-35px' });
    };

    function showPagination() {
        oPagination.animate({ 'bottom': '0' });
    };

    function bindClicks() {
        oPreviewCar.find('a.arrow-left').bind('click', function () {
            if (!bPreviewAnimate && nCurrentIndex > 0 && !bLastScreen) {
                nCurrentIndex--;
                slideImage(950);
            }
            else if (!bPreviewAnimate && bLastScreen) hideLastScreen();
            return false;
        });

        oPreviewCar.find('a.arrow-right').bind('click', function () {
            if (!bPreviewAnimate && nCurrentIndex < oData.caseStudy.images.length - 1) {
                nCurrentIndex++;
                slideImage(-950);
            }
            else if (!bPreviewAnimate && nCurrentIndex == oData.caseStudy.images.length - 1) showLastScreen();
            return false;
        });

        oPagination.find('a').bind('click', function () {
            if (!bPreviewAnimate) {
                var tempIndex = nCurrentIndex;
                nCurrentIndex = $(this).parent().index();
                if (nCurrentIndex != tempIndex && nCurrentIndex < tempIndex) slideImage(950)
                else if (nCurrentIndex != tempIndex && nCurrentIndex > tempIndex) slideImage(-950);
            }
            return false;
        });

        oPreviewInfo.find('a.show-hide-cs').bind('click', function () {
            if ($(this).hasClass('show')) {
                $(this).removeClass('show').addClass('hide').html('Hide case study');
                oPreviewInfo.animate({ 'height': oPreviewInfo.data('height') });
                if (nPageHeight < oPreviewInfo.data('height') + 770) oOverlay.css({ 'height': oPreviewInfo.data('height') + 770 });
            }
            else if ($(this).hasClass('hide')) {
                $(this).removeClass('hide').addClass('show').html('Show case study');
                oPreviewInfo.animate({ 'height': '69px' }, function () {
                    oOverlay.css({ 'height': nPageHeight });
                });
                //scroll to top of page
                $.scrollTo(0, 400);
            }
            return false;
        });

        oThumbCar.find('.draw-top').bind('click', function () {
            var oThis = $(this);
            if (!bThumbAnimate && !oThis.next().hasClass('open')) {
                bThumbAnimate = true;
                oThis.parent().find('.active').removeClass('active');
                oThis.addClass('active');

                oThumbCar.find('.open').removeClass('open').animate({ 'width': 0 }, 1000);
                $(this).next().addClass('open').animate({ 'width': 855 }, 1000, function () {
                    bThumbAnimate = false;
                });
            };
        });

        oThumbCar.find('a.left').bind('click', function () {
            if (!bThumbAnimate) scrollThumbs('right', $(this));
            return false;
        });

        oThumbCar.find('a.right').bind('click', function () {
            if (!bThumbAnimate) scrollThumbs('left', $(this));
            return false;
        });

        oThumbCar.find('.thumb').bind('click', function () {
            var sProjectRequest = RemoveInvalidFileNameChars($(this).find('p:eq(1)').text().split(' ').join(' '));
            fadeOutContent(sProjectRequest);
        });

        $('.top-bar a').bind('click', function () {
            closePlayer();
            return false;
        });

        // Close on overlay click
        $('#overlay').bind('click', function () {
            closePlayer();
        });
    };

    function bindLastPageClick() {
        $('.simular-cs').bind('click', function () {
            var sProjectRequest = RemoveInvalidFileNameChars($(this).find('.info p:eq(1)').text().split(' ').join(' '));
            fadeOutContent(sProjectRequest);
        });
    };

    function RemoveInvalidFileNameChars(string) {
        for (var i = 0, output = '', invalid = '"<>|:*?\/'; i < string.length; i++)
            if (invalid.indexOf(string.charAt(i)) == -1)
                output += string.charAt(i);
        return output;
    }

    function unbindClicks() {
        oPreviewCar.find('a.arrow-left').unbind('click');
        oPreviewCar.find('a.arrow-right').unbind('click');
        oPagination.find('a').unbind('click');
        oPreviewInfo.find('a.show-hide-cs').unbind('click');
        oThumbCar.find('.draw-top').unbind('click');
        oThumbCar.find('a.left').unbind('click');
        oThumbCar.find('a.right').unbind('click');
        oThumbCar.find('.thumb').unbind('click');
        $('.simular-cs').unbind('click');
        $('.top-bar a').unbind('click');
    };

    function scrollThumbs(direction, elem) {
        var oThumbStrip = elem.parent().find('.thumb-list');
        var nThumbAmount = oThumbStrip.find('.thumb').length;
        var nThumbShift = parseInt(oThumbStrip.css('marginLeft'));
        var oThumbViewWidth = oThumbStrip.parent().width();
        var nThumbStripWidth = nThumbAmount * (139 + 20) - 20;
        var oShiftAmount = 477;

        if (direction == 'left' && nThumbShift > nThumbStripWidth * -1 + oThumbViewWidth) {
            bThumbAnimate = true;
            //need to look at this again, dosen't make much sense, but works!
            if (nThumbShift - oShiftAmount < (nThumbStripWidth * -1) + oThumbViewWidth) oShiftAmount = nThumbStripWidth - oThumbViewWidth - (nThumbShift * -1) + 6;
            oThumbStrip.animate({ 'margin-left': nThumbShift - oShiftAmount }, 1000, function () {
                bThumbAnimate = false;
                /*TODO: We need something like this in place to disable the carousel arrows at either end: if (nThumbShift == 0) {
                elem.replaceWith('<div class="right noLink"></div>');
                } else {
                elem.replaceWith('<a class="right" href="#"></a>');
                }*/
            });
        };

        if (direction == 'right' && nThumbShift < 0) {
            bThumbAnimate = true;
            if (nThumbShift + oShiftAmount > 0) oShiftAmount = nThumbShift * -1;
            oThumbStrip.animate({ 'margin-left': nThumbShift + oShiftAmount }, 1000, function () {
                bThumbAnimate = false;
                console.log('right:' + nThumbShift);
                /*if (nThumbShift <= nThumbStripWidth * -1 + oThumbViewWidth) {
                elem.replaceWith('<div class="left noLink"></div>');
                } else {
                elem.replaceWith('<a class="left" href="#"></a>');
                }*/
            });
        };
    };

    function showLastScreen() {
        bLastScreen = true;

        oPreviewCar.prepend('<div class="last-screen new"><p class="top-line">More like ' + oData.caseStudy.client + ' ' + oData.caseStudy.project + ' (' + oData.caseStudy.service + ')</p></div>');
        for (var i = 0; i < oData.caseStudy.simular.length; i++) {
            $('.last-screen').append('<div class="simular-cs box0' + (i + 1) + '"><img src="' + oData.caseStudy.simular[i].thumb + '" width="139" height="90" /><div class="info"><p class="client">' + oData.caseStudy.simular[i].client + '</p><p>' + oData.caseStudy.simular[i].project + '</p><p>' + oData.caseStudy.simular[i].service + '</p></div><div class="overlay"><div class="fade"></div><div class="overlay-info"><p class="client">' + oData.caseStudy.simular[i].client + '</p><p>' + oData.caseStudy.simular[i].project + '</p><p>' + oData.caseStudy.simular[i].service + '</p></div></div></div>');
        }

        $('.simular-cs').hover(
            function () { $(this).find('.overlay').stop(true, true).fadeIn(400); },
            function () { $(this).find('.overlay').stop(true, true).fadeOut(400); }
        )

        $('a.show-hide-cs').fadeOut();

        // remove box shadow and add it again after as it causes stuttering in IE
        $('#candi-player').css({ 'box-shadow': 'none' });
        oPreviewInfo.animate({ 'height': '0', 'margin-bottom': '10px' }, function () { $('#candi-player').css({ 'box-shadow': '3px 3px 5px #000' }); });
        bindLastPageClick();
        slideImage(-950);
        hidePagination();
    };

    function hideLastScreen() {
        bLastScreen = false;
        $('a.show-hide-cs').fadeIn();
        oPreviewInfo.animate({ 'height': '69px', 'margin-bottom': '35px' }, function () { $('#candi-player').css({ 'box-shadow': '3px 3px 5px #000' }); });
        slideImage(950);
        showPagination();
    };

    function slideImage(slideAmount) {
        bPreviewAnimate = true;
        checkArrows();
        //IE7 overlay shrinking fix
        oOverlay.css({ 'height': nPageHeight });
        //Add loading animation here
        if (!bLastScreen) {
            oPreviewCar.prepend('<img class="new" src="' + oData.caseStudy.images[nCurrentIndex].image + '" width="950" height="336" />').find('img').load(function () {
                oPreviewCar.find('.viewed').animate({ 'margin-left': slideAmount }, nSlideSpeed, 'swing', function () {
                    $(this).remove();
                    oPreviewCar.find('.new').removeClass('new').addClass('viewed');
                    bPreviewAnimate = false;
                });
            });
            updatePagination();
        }
        else {
            oPreviewCar.find('.viewed').animate({ 'margin-left': slideAmount }, nSlideSpeed, 'swing', function () {
                $(this).remove();
                oPreviewCar.find('.new').removeClass('new').addClass('viewed');
                bPreviewAnimate = false;
            });
        }
    };

    function updatePagination() {
        oPagination.find('.active').removeClass('active');
        oPagination.find('a').eq(nCurrentIndex).addClass('active'); ;
    };

    function checkArrows() {
        if (nCurrentIndex == 0) oPreviewCar.find('a.arrow-left').fadeOut()
        else oPreviewCar.find('a.arrow-left').fadeIn();

        if (bLastScreen) oPreviewCar.find('a.arrow-right').fadeOut()
        else oPreviewCar.find('a.arrow-right').fadeIn();
    };

    function centerImage(elem) {
        elem.css({ left: (document.documentElement.clientWidth / 2) - (elem.width() / 2) });
    };

    function closePlayer() {
        oPreviewInfo.animate({ 'margin-top': '-100px' }, function () {
            $(this).remove();
        });
        oThumbCar.animate({ 'margin-top': '-161px' }, function () {
            $(this).remove();
        });
        oPreviewCar.animate({ 'margin-top': '-40px' });
        oPlayer.animate({ 'margin-top': '40px' }, function () {
            $(this).css({ 'margin-top': '80px' }).fadeOut(function () {
                $(this).remove();
            });
            oOverlay.fadeOut(function () {
                $(this).remove();
            });
            $('.top-bar').remove();
        });
        hidePagination();
        //reset some valible vars
        nCurrentIndex = 0;
        bPreviewAnimate = false;
        bThumbAnimate = false;
        bLastScreen = false;
        bFirstRun = true;
    };

    //Public methods
    return {
        init: function () {
            //When any element with the class 'cp' is clicked take the rel and load data
            $('.cp').click(function () {
                // Log it in analytics
                var rel = this.getAttribute('rel');
                _gaq.push(['_trackEvent', 'CandiPlayer', 'open', rel]);
                var browse = rel.slice(rel.indexOf('?') + 1).split('=')[1];
                loadData(rel.split('?')[0], browse); return false;
            });

            //RP - 20111021: load candi player by querystring project name: /work?project=projectname          
            if (window.location.href.indexOf("/work/") != -1) {
                var project = $.getCaseStudyProjectName();
                if (project != undefined && project != '') {
                    project = project.replace(/-/g, ' ');
                    _gaq.push(['_trackEvent', 'CandiPlayer', 'open-direct', project]);
                    loadData(project, $.getUrlVar('browse'));
                }
            }
            //RP - 20111021: load candi player by querystring project name  
        }
    };
} ();
	
$(function(){
	//Initiate Player
	CandiPlayer.com.init();
});

//RP - 20111021: method to grab querystring parameters
$.extend({    
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    },
    getCaseStudyProjectName: function () {      
        var splitPath = RemoveTrailingSlash(window.location.href).split('/');
        if (splitPath.length > 0 && splitPath[splitPath.length - 1] != 'work' && splitPath[splitPath.length - 1] != '#') {
          return splitPath[splitPath.length - 1];            
        }
        return undefined;
    }
    
});

function RemoveTrailingSlash (str) {
   if (str.substr(-1) == '/') {
       return str.substr(0, str.length - 1);
   }
   return str;
}
//RP - 20111021: method to grab querystring parameters    
