﻿//wrap code in a closure to allow use of $
(function ($) {

    //create AKQA namspace if not already defined
    AKQA = AKQA || {};

    AKQA.Modals = (function () {

        var self = {};
        var visible = false;
        var loading = false;
        var autoHideControls = (AKQA.DeviceManager.isiOS()) ? false : 'slide';
        var autoHideDelay = 1500;
        var veilOpacity = 1.0;
        var closeOnCompletion = true;
        var popHistoryOnClose = true;

        //loader
        self.Loader = (function () {
            return {
                show: function (callback) {
                    $loader = $('.modal .loader');
                    if ($loader.length === 0) {
                        $loader = $('<div class="loader"><div class="spinner"></div></div>');
                        $('.modal .controls').before($loader);
                        $loader.hide();
                    }
                    $loader.bind('mouseover mousemove', function () {
                        return false;
                    });
                    AKQA.AnimationManager.fadeTo($loader, 1, 400, 0, callback);
                    //$loader.fadeIn(callback);
                    return false;
                },
                hide: function (callback) {
                    AKQA.AnimationManager.fadeTo($('.modal .loader'), 0, 400, 0, callback);
                    //$('.modal .loader').fadeOut(callback);
                    return false;
                }
            };
        } ());

        //auto-hide controls
        autoHideTimer = null;
        function _autoHideControls() {
            $(document).mousemove(function (event) {
                $container = $('.modal .modal-content');
                $controller = $('.modal .controls');
                if ($container.parents('body').length == 0) {
                    $(document).unbind('mousemove', arguments.callee);
                    clearTimeout(autoHideTimer);
                    autoHideTimer = null;
                    return;
                }
                var pos = $container.offset();
                var mouse = { x: event.pageX, y: event.pageY };
                if (mouse.x >= pos.left &&
				mouse.x <= pos.left + $container.width() &&
				mouse.y >= pos.top &&
				mouse.y <= pos.top + $container.height()) {
                    if (autoHideControls == 'slide') {
                        $controller.slideDown();
                    } else {
                        $controller.fadeIn();
                    }
                    clearTimeout(autoHideTimer);
                    autoHideTimer = null;
                }
                var pos = $controller.offset();
                if (!loading && !autoHideTimer && (mouse.x < pos.left ||
				mouse.x > pos.left + $controller.width() ||
				mouse.y < pos.top ||
				mouse.y > pos.top + $controller.height())
            ) {
                    autoHideTimer = setTimeout(function () {
                        if (autoHideControls == 'slide') {
                            $controller.slideUp();
                        } else {
                            $controller.fadeOut();
                        }
                    }, autoHideDelay);
                }
            });

            //autoshow controls
            if (autoHideControls == 'slide') {
                $('.modal .controls').slideDown();
            } else {
                $('.modal .controls').fadeIn();
            }
        }

        //generic modal view loader
        self.showModal = function (url, callback) {

            var modalData = false;
            var veilShown = false;
            var alreadyShown = false;
            function showModal() {
                if (modalData && veilShown && !alreadyShown) {
                    alreadyShown = true;
                    $modal = $('<div class="modal"></div>');
                    $modal.close = self.close;
                    $('body').append($modal);
                    callback.call($modal, modalData);
                    if (AKQA.DeviceManager.isiOS()) {
                        $('.veil').height($(document).height());
                    }
                    AKQA.MManager.refreshPage();
                    AKQA.FontManager.refreshPage();
                }
            }

            //load page via ajax
            $.get(url, function (data) {
                modalData = data;
                showModal();
            });

            //show modal veil
            $('body').append('<div class="veil"></div>');
            $('.veil').hide();
            AKQA.AnimationManager.fadeTo($('.veil'), veilOpacity, 400, 0, function () {
                veilShown = true;
                showModal();
            });
        }

        //open video page in a modal
        self.showVideo = function (url, callback) {

            //play in modal
            self.showModal(url, function (data) {

                //get video details
                if (AKQA.DeviceManager.isIE()) {
                    //fix for IE9, which isn't supported by this jQuery version
                    var $container = $('<div class="modal-content video"></div>');
                    var videoTag = data.match(/<video(.|\n|\r)*/i)[0];
                    var videoURL = videoTag.match(/<source.*src="([^"]+)"/i)[1];
                    var $placeholder = $(videoTag.match(/<p[^<]+<\/p>/i)[0]);
                } else {
                    var $container = $('.modal-content', data);
                    var videoURL = $container.find('video').attr('src') || $container.find('source').attr('src');
                    var $placeholder = $container.find('p');
                    $container.empty();
                }

                //build video player and controls
                this.append($container);
                var player = $container.videoplayer({
                    flashUrl: '/library/flash/AKQAVideoPlayer.swf',
                    expressInstallUrl: '/library/flash/AKQAVideoPlayer.swf',
                    videoURL: videoURL,
                    flashVars: $.extend({
                        skinURL: '/library/flash/AKQAVideoPlayerSkin.swf',
                        autoHideDelay: autoHideDelay,
                        closeJSFunction: 'AKQAcloseModal'
                    }, (closeOnCompletion) ? {
                        videoEndJSFunction: 'AKQAvideoEnd'
                    } : {}),
                    flashParams: {
                        bgColor: '#000000'
                    },
                    customControls: true,
                    closeButton: true,
                    autoplay: true,
                    useFlashIfAvailable: !AKQA.DeviceManager.isSafari(),
                    placeholder: $placeholder,
                    autoHideControls: autoHideControls,
                    autoHideDelay: autoHideDelay,
                    cssPrefix: ''
                }).bind('close', self.close).bind('ready', function () {
                    self.Loader.hide();
                }).hide().fadeIn(callback);

                //close on end
                if (closeOnCompletion) {
                    player.bind('ended', self.close);
                }

                //show loader
				if (!(AKQA.DeviceManager.isiOS() && AKQA.DeviceManager.isHandset())) {
					self.Loader.show();
				}
            });
        }

        //open gallery page in modal
        self.showImages = function (url, callback) {
            self.showModal(url, function (data) {

                //loading
                loading = true;

                //selected index
                var selectedIndex = 0;

                //load image
                function loadImage(url) {

                    function showImage(url) {
                        $image = $('<img src="' + url + '">').hide();
                        $('.modal .image img').stop(true, true);
                        AKQA.AnimationManager.fadeTo($('.modal .image img'), 0, 400, 0, function () {
                            $(this).remove();
                        });
                        $('.modal .image').append($image);
                        self.Loader.hide();
                        loading = false;
                        AKQA.AnimationManager.fadeTo($image, 1, 400, 0);
                    }

                    var image = new Image();
                    image.src = url;
                    if (image.complete) {
                        showImage(url);
                    } else {
                        self.Loader.show();
                        loading = true;
                        $(image).load(function () {
                            showImage(url);
                        });
                    }

                    return false;
                }

                //update controls
                function updateControls() {
                    $('.modal .gallery .back, .modal .gallery .forward').removeClass('disabled');
                    $('.modal ul .selected').removeClass('selected');
                    $('.modal li a').eq(selectedIndex).addClass('selected');
                }

                //get images
                var images = $('.modal-content.gallery li a', data).map(function () {
                    return $(this).attr('rel');
                });

                //build gallery and controls
                $container = $('.modal-content', data);
                $container.find('.controls').prepend('<button class="close">Close</button>');
                $container.find('.image').empty();
                this.append($container);

                //close button
                $('.modal .gallery .close').click(self.close);

                //hijack links
                $('.modal .gallery li a').each(function (i) {
                    $(this).click(function () {
                        loadImage(this.rel);
                        selectedIndex = i;
                        updateControls();
                        return false;
                    });
                });

                //back/forward
                function back() {
                    var index = selectedIndex - 1;
                    if (index < 0) {
                        index = images.length - 1;
                    }
                    $('.modal .gallery li a').eq(index).click();
                    return false;
                }
                function forward() {
                    var index = selectedIndex + 1;
                    if (index >= images.length) {
                        index = 0;
                    }
                    $('.modal .gallery li a').eq(index).click();
                    return false;
                }

                //back/forward buttons
                $('.modal .gallery .back').click(back);
                $('.modal .gallery .forward').click(forward);

                //click image to cycle
                if (AKQA.DeviceManager.isiOS()) {
                    $('.modal .gallery .image').swipe({
                        swipeLeft: forward,
                        swipeRight: back
                    });
                }
                $('.modal .gallery .image').click(forward).attr('title', 'Next image');

                //show loader
                self.Loader.show();

                //load first image and set controls
                loadImage(images[selectedIndex]);
                updateControls();

                //auto-hide controls
                //_autoHideControls();
            });
        }

        //show map
        self.showMap = function (url, callback) {
            self.showModal(url, function (data) {

                if (AKQA.DeviceManager.isIE()) {
                    //build container
                    var $container = $('<div class="modal-content map">' +
                                            '<div class="image"></div>' +
                                            '<div class="controls"></div>' +
                                       '</div>');
                    //get map image source
                    var map = data.match(/<div class="modal-content(.|\n|\r)*/i)[0];
                    var img = map.match(/<img [^>]+/i)[0];
                    var url = img.match(/src="([^"]+")/i)[1];
                } else {
                    //get container
                    var $container = $('.modal-content', data);
                    
					if (!AKQA.DeviceManager.isHandset()) {
						var $img = $container.find('.image img');
						//get map image source and remove image
						var url = $img.attr('src');
						$img.remove();
					}
                }

                //build map and controls
                $container.find('.controls').append('<button class="close">Close</button>');
                this.append($container);

                //close button
                $container.find('.close').click(self.close);
				
				if (!AKQA.DeviceManager.isHandset()) {
					//get map settings
					var zoom = parseInt(decodeURI(url.match(/zoom=([^&]+)/)[1]));
					var address = decodeURI(url.match(/center=([^&]+)/)[1]);
				
					//load address and map
					var map = null;
					var geocoder = new google.maps.Geocoder();
					geocoder.geocode({ address: address }, function (results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							//create map
							map = new google.maps.Map($container.find('.image')[0], {
								zoom: zoom,
								center: results[0].geometry.location,
								mapTypeId: google.maps.MapTypeId.ROADMAP,
								mapTypeControl: false
							});
							//create marker
							var marker = new google.maps.Marker({
								position: results[0].geometry.location,
								map: map
							});
						}

						//hide loader
						self.Loader.hide();

						//auto-hide controls
						// _autoHideControls();
					});

					//show loader
					self.Loader.show();
				}
            });
        }

        //show privacy policy
        self.showPrivacyPolicy = function (url, callback) {
            self.showModal(url, function (data) {

                //detect if url was used to open modal
                popHistoryOnClose = !!document.location.href.match(/privacy-policy$/);

                //build content
                $container = $('<div class="modal-content terms">' +
                               '<div class="copy"></div>' +
                               '<div class="controls"></div>' +
                           '</div>');
                $container.find('.copy').append($('#copy', data).html());
                $container.find('.controls').append('<button class="close">Close</button>');
                this.append($container);

                //close button
                $('.modal .terms .close').click(self.close);
            });
        }

        //show modal
        self.show = function (type, url) {
            var fn = 'show';
            $.each(type.split('-'), function () {
                fn += this.substr(0, 1).toUpperCase() + this.substr(1).toLowerCase();
            });
            if (this[fn]) {
                this[fn](url);
            } else {
                alert('Unknown modal function "' + fn + '"');
            }
        }

        //close modal
        self.close = function (popHistory) {
            self.Loader.hide();
            AKQA.AnimationManager.fadeTo($('.modal'), 0, 400, 0, function () {
                $(this).remove();
            });
            AKQA.AnimationManager.fadeTo($('.veil'), 0, 400, 0, function () {
                $(this).remove();
                popHistory = (typeof popHistory == 'undefined') ? popHistoryOnClose : popHistory;
                if (popHistory) {
                    var url = $.address.value().split('/');
                    url.pop();
                    url = url.join('/');
                    $.address.value(url);
                }

                if (AKQA.DeviceManager.isiOS()) {
					AKQA.Utility.adjustFooter(); // Ensures footer comes back into view after modal closes
                }

            });
            return false;
        }
        var cancelClose = false;
        $('.veil, .modal').live('click', function () {
            if (!cancelClose) {
                self.close();
            }
            cancelClose = false;
        });
        $('.modal .modal-content').live('click', function () {
            cancelClose = true;
        });

        //flash callbacks
        window.AKQAcloseModal = self.close;
        window.AKQAvideoEnd = self.close;

        return self;

    } ());

} (jQuery.noConflict()));
