$(document).ready(function() {
    if (isIpad()) {
        ipadInit();
    } else if (isIphone()) {
        iphoneInit();
    } else if (isAndroid()) {
        androidInit();
    } else {
        // Hide textual descriptions.
        $('body').addClass('regular');
        $('.extra').hide();
        $('.video > h2').hide();

        // Images flicker in FF when we animate content (the scrollbars are
        // redrawn). Changing the min-height seems to fix this. We use the browser
        // property rather than feature detection here to make sure that we're
        // targetting Mozilla based browsers.
        if ($.browser.mozilla) {
            var body = $('body#main-0');
            body.css('min-height', body.height() + 600);
        }

        // Alter position of description and title elements depending on position
        // in grid.
        var videoList = $('.video');
        for (var i = 0, ii = videoList.size(); i < ii; i++) {
            var title = $('.title', videoList[i]);
            var description = $('.description', videoList[i]);

            var position = (i + 1) - (Math.floor(i / 4) * 4);
            var titleLeft, descriptionLeft;
            switch (position) {
                case 1:
                    titleLeft = '240px';
                    descriptionLeft = '480px';
                    break;
                case 2:
                    titleLeft = '-240px';
                    descriptionLeft = '240px';
                    break;
                case 3:
                    titleLeft = '240px';
                    descriptionLeft = '-480px';
                    break;
                case 4:
                    titleLeft = '-240px';
                    descriptionLeft = '-720px';
                    break;
            }
            title.css('left', titleLeft);
            description.css('left', descriptionLeft);
        }

        // Show/hide descriptions and titles.
        $('img.cover').hover(function() {
            $('img.title, img.description').hide();
            $(this).siblings().show();
            $('.video').css('z-index', 10);
            $(this).parents('.video').css('z-index', 1000);
        }, function() {
            $('img.title, img.description').hide();
        });
        $('img.title').mouseover(function() {
            $(this).hide();
        });

        $('.player').live('mouseover', function() {
            $('.video.playing img.title, .video.playing img.description').show();
            $('.video:not(.playing)').css('z-index', 10);
            $('.video.playing').css('z-index', 1000);
        });
        $('.player').live('mouseout', function() {
            $('.video.playing img.title, .video.playing img.description').hide();
        });

        $('.video a.init-video').click(function(event) {
            event.preventDefault();
            var element = $(this);
            var parent = element.parents('.video');

            if (parent.hasClass('playing')) {
                // Element is already playing.
                return;
            }

            var player = $('.player');
            if (player.size()) {
                if (parent.siblings('.playing').size()) {
                    player.remove();
                    showPlayer(element, false);
                } else {
                    $('#video-content').hide();
                    player.slideUp(function() {
                        player.remove();
                        showPlayer(element, true);
                    });
                }
            } else {
                showPlayer(element, true);
            }
            $('.video.playing').removeClass('playing');
            parent.addClass('playing');
        });

        function getReadMoreURL(id, element) {
            if (typeof(urls) != 'undefined' && id in urls) {
                return urls[id];
            }
            return $(element).attr('href');
        }

        var lastScroll = null;
        function showPlayer(element, slide) {
            lastScroll = window.pageYOffset;
            $('#content').addClass('active');

            element = $(element);
            var id = element.parents('.video').attr('id').substring('video-'.length);
            var parent = element.parents('.row');
            var player = $('<div class="player"></div>');
            var closeMarkup = '<a id="close-player" href="#"><img src="./images/icons/x.png" alt="an x"/></a>';

            player.append(closeMarkup);
            player.append($('.video-menu', element.parents('.video')).clone());
            player.append(getEmbedCode(getIdentifier(element.attr('href'))));
            parent.after(player);

            if (slide) {
                player.hide();
                player.slideDown(function() {
                    $.scrollTo(parent, 300);
                });
            }

            $('#close-player').click(function(event) {
                event.preventDefault();
                $('#content').removeClass('active');
                $('.video.playing').removeClass('playing');
                $('#video-content').hide();
                $(this).parents('.player').slideUp(function() {
                    $(this).remove();
                    // Browser detection again.
                    if (!$.browser.msie && lastScroll !== null) {
                        $.scrollTo(lastScroll, 300);
                    }
                });
            });

            $('.video-menu #share-url-field').click(function() {
                $(this).select();
            });

            function getIdentifier(url) {
                return url.substring('http://www.youtube.com/watch?v='.length)
            }
            function getEmbedCode(identifier) {
                return [
                    '<div id="video-content">',
                    '<object width="680" height="400">',
                    '<param name="movie" value="http://www.youtube.com/v/', identifier, '&hl=en_US&fs=1&color1=0x3a3a3a&color2=0x999999&hd=1"></param>',
                    '<param name="allowFullScreen" value="true"></param>',
                    '<param name="allowscriptaccess" value="always"></param>',
                    '<param name="wmode" value="transparent"></param>',
                    '<embed src="http://www.youtube.com/v/', identifier, '&hl=en_US&fs=1&color1=0x3a3a3a&color2=0x999999&hd=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="680" height="400" wmode="transparent"></embed>',
                    '</object>',
                    '</div>'
                ].join('\n');
            }
        }

        (function() {
            function loadVideo(id) {
                if (id) {
                    $('a.init-video', $(id)).click();
                }
            }
            var mainId = parseInt($('body').attr('id').substr('main-'.length));
            if (!isNaN(mainId) && mainId != 0) {
                window.location.href = "#video-" + mainId;
            }
            if ('onhashchange' in window) {
                window.onhashchange = function() {
                    loadVideo(window.location.hash);
                }
            }
            loadVideo(window.location.hash);
        })();
    }
});

function getVideoDetails(video) {
    var id = video.attr('id').substring('video-'.length);
    var title = $('h2', video).text();
    var description = $('.textual-description', video).text();
    var readMoreURL = $('.read-more', video).attr('href');
    return {
        id: id,
        title: title,
        description: description,
        readMoreURL: readMoreURL
    };
}

function ipadInit() {
    $('body').addClass('ipad');
    $('.video a').click(function(event) {
        event.preventDefault();
        var details = getVideoDetails($(this).parent());

        var dark = $('<div id="dark"></div>');
        dark.hide();

        var content = $('<div id="dark-content"></div>');
        var url = $('.download a', $(this).parent()).eq(1).attr('href');
        url = url.replace("/2020/", "/2020/mob/");
        var video = $('<video controls="controls" width="768" height="432"><source type="video/mp4" src="' + url + '" width="768" height="432"/></video>');
        var anchor = $('<a id="close-dark" href="#">Close</a>');
        anchor.click(function(event) {
            event.preventDefault();
            $('#eBodyContainer').show();
            $('#dark').remove();
        });

        content.append(video);
        content.append(anchor);
        dark.append(content);

        $('#eBodyContainer').hide(0, function() {
            $('body').append(dark);
            dark.show();
        });
    });
    $('#column-1').each(function() {
        $(this).html('');
        var videoContainer = $('<div id="about-video-container"></div>');
        for (var i = 1; i <= 5; i++) {
            var url = 'http://www.ericsson.com/blob/mov/campaigns/2020/mob/2' + i + '.mov';
            var video = $('<video controls="controls" width="480" height="295"><source type="video/mp4" src="' + url + '" width="480" height="295"/></video>');
            videoContainer.append(video);
        }
        $(this).append(videoContainer);
    });
}

function iphoneInit() {
    $('body').addClass('iphone');
    $('.video > a').each(function() {
        var details = getVideoDetails($(this).parent());
        var url = $('.download a', $(this).parent()).eq(1).attr('href');
        url = url.replace("/2020/", "/2020/mob/");
        url = url.replace(".mov", "_iphone.mov");
        $(this).attr('href', url);
    });
    $('.video').each(function() {
        var p = $('<p class="expand"></p>');
        var a = $('<a href="#">Show description</a>');
        a.click(function(event) {
            event.preventDefault();
            $('.extra', $(this).parents('.video')).show();
            $(this).remove();
        });
        p.append(a);
        $(this).append(p);
    });

}

function androidInit() {
    $('body').addClass('android');
    $('.video').each(function() {
        var p = $('<p class="expand"></p>');
        var a = $('<a href="#">Show description</a>');
        a.click(function(event) {
            event.preventDefault();
            $('.extra', $(this).parents('.video')).show();
            $(this).remove();
        });
        p.append(a);
        $(this).append(p);
    });
    var videos = [
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/xKUbwnvwpqA&hl=en_US&fs=1&hd=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/xKUbwnvwpqA&hl=en_US&fs=1&hd=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/k2UuIccbnUM?version=3"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/k2UuIccbnUM?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="240" height="150"></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/4Wm_c4J9GMA?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/4Wm_c4J9GMA?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/wC01i9wYnJw?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/wC01i9wYnJw?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>'
    ];
    var videoContainer = $('<div id="about-video-container"></div>');
    $('#column-1').each(function() {
        $(this).html('');
        for (var i = 0; i < videos.length; i++) {
            var video = videos[i];
            videoContainer.append(video);
        }
        $(this).append(videoContainer);
    });
}

function androidInit() {
    $('body').addClass('android');
    $('.video').each(function() {
        var p = $('<p class="expand"></p>');
        var a = $('<a href="#">Show description</a>');
        a.click(function(event) {
            event.preventDefault();
            $('.extra', $(this).parents('.video')).show();
            $(this).remove();
        });
        p.append(a);
        $(this).append(p);
    });
    var videos = [
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/xKUbwnvwpqA&hl=en_US&fs=1&hd=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/xKUbwnvwpqA&hl=en_US&fs=1&hd=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/k2UuIccbnUM?version=3"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/k2UuIccbnUM?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="240" height="150"></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/4Wm_c4J9GMA?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/4Wm_c4J9GMA?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>',
        '<object width="240" height="150"><param name="movie" value="http://www.youtube.com/v/wC01i9wYnJw?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/wC01i9wYnJw?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="240" height="150"></embed></object>'
    ];
    var videoContainer = $('<div id="about-video-container"></div>');
    $('#column-1').each(function() {
        $(this).html('');
        for (var i = 0; i < videos.length; i++) {
            var video = videos[i];
            videoContainer.append(video);
        }
        $(this).append(videoContainer);
    });
}

function isAndroid() {
    return navigator.userAgent.indexOf('Android') != -1;
}

function isIpad() {
    return navigator.userAgent.indexOf('iPad') != -1;
}

function isIphone() {
    return navigator.userAgent.indexOf('iPhone') != -1;
}

