/// <reference path="jquery-1.3.2-vsdoc2.js" />
/*global jQuery, $, window,swfobject */
"use strict";

$.fn.comboToggle = function () {
    return this.animate({opacity: 'toggle', height: 'toggle'});
};



// window.custom.practiceFusion
(function () {
    function init() {
        $(function () {
            $(".pflinktyperadio").click(function () {
                var selected = $(this).val(),
                    id = selected.split("-")[2];
                $(".pflinker-" + id + " div").slideUp();
                $("." + this.value).slideDown();
            });

            // Loop through each radio button to process the selected
            $(".pflinktyperadio").each(function () {
                var child = $(this),
                    selected,
                    id;

                if (child.is(":radio:checked")) {
                    selected = child.attr("value");
                    id = selected.split("-")[2];
                    $(".pflinker-" + id + " div").slideUp();
                    $("." + this.value).slideDown();
                }
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.practiceFusion = {
        init: init
    };
}());

// window.custom.customerReferralProgram
(function () {
    function init() {
        $(function () {
            // Toggle Details on Referral Page
            $('#referraldetails-toggle').click(function (event) {
                $('#referraldetails').comboToggle();
                event.preventDefault();
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.customerReferralProgram = {
        init: init
    };
}());

// window.custom.faqs
(function () {
    function init() {
        $(function () {
            $("ul.faqs li h4, ul.faqs li h5").click(function () {
                $(this).siblings('p').slideToggle("fast");
            });
            $("ul.newsletters li.item h4").click(function () {
                $(this).siblings('dl').slideToggle("fast");
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.faqs = {
        init: init
    };
}());

// window.custom.hint
(function () {
    function init() {
        $(function () {
            $(".hint").tooltip({
                track: true,
                delay: 0,
                showURL: false,
                showBody: " - ",
                fade: 250
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.hint = {
        init: init
    };
}());

// window.custom.jqm
(function () {
    function onHideFun(hash) {
        hash.w.hide();
        hash.w.html("");
        if (hash.o) {
            hash.o.remove();
        }
    }

    function init() {
        $(function () {
            // Homepage Videos
            var videoCount = 30,
                videoNumber;

            for (videoNumber = 1; videoNumber <= videoCount; videoNumber++) {
                $('#video_' + videoNumber + '_modal').jqm({ toTop: true, trigger: 'a.video_' + videoNumber + '_trigger', closeClass: "video_close", ajax: "@href", onHide: onHideFun });
            }
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.jqm = {
        init: init
    };
}());

// window.custom.demos
(function () {
    var GOGGLE_ANALYTICS_EVENT_CATEGORY = 'Demos Center',
        GOGGLE_ANALYTICS_EVENT_ACTION = 'Play Demo Video',
        config = {
            autoPlay: false,
            videos: [],
            youTubeId: null
        },
        youTubePlayer,
        youTubePlayerStates = {
            unstarted: -1,
            ended: 0,
            playing: 1,
            paused: 2,
            buffering: 3,
            videoCued: 5
        },
        playerOverlayElement,
        currentVideo,
        ensureHighestQuality = false,
        autoPlay = false;

    function findVideoByPropertyValue(property, value) {
        var i, v;
        for (i = 0; i < config.videos.length; i++)
        {
            v = config.videos[i];
            if (v[property] === value) {
                return v;
            }
        }
        return null;
    }

    function ensureHighestPlaybackQuality() {
        var availableQualities = youTubePlayer.getAvailableQualityLevels();
        if (availableQualities[0] && availableQualities[0] !== youTubePlayer.getPlaybackQuality()) {
            youTubePlayer.setPlaybackQuality(availableQualities[0]);
        }
    }

    function createGoogleAnalyticsEvent() {
        window.pageTracker._trackEvent(
            GOGGLE_ANALYTICS_EVENT_CATEGORY,
            GOGGLE_ANALYTICS_EVENT_ACTION,
            currentVideo.groupId + '/' + currentVideo.videoId
        );
    }

    function onYouTubePlayerStateChange(state) {
        switch (state) {
        case youTubePlayerStates.videoCued:
            if (autoPlay) {
                autoPlay = false;
                youTubePlayer.playVideo();
            }
            if (currentVideo.stillImageUrl) {
                playerOverlayElement.find('.still-image').attr('src', currentVideo.stillImageUrl);
                playerOverlayElement.show();
            } else {
                playerOverlayElement.hide();
            }
            break;

        case youTubePlayerStates.playing:
            playerOverlayElement.hide();
            if (ensureHighestQuality) {
                ensureHighestQuality = false;
                ensureHighestPlaybackQuality();
                createGoogleAnalyticsEvent();
            }
            break;
        }
    }

    function initializeYouTubePlayer(videoId, callback) {
        var containerId = 'youtube-player-container',
            playerId = 'youTubePlayer';

        window.onYouTubePlayerReady = function (readyPlayerId) {
            if (readyPlayerId === playerId) {
                if (callback) {
                    callback(playerId);
                }
            }
        };

        swfobject.embedSWF('http://www.youtube.com/v/' + videoId + 
                           '?rel=0&enablejsapi=1&playerapiid=' + playerId + '&fs=1&hd=1&showsearch=0&showinfo=0', 
                           containerId, '640', '505', '8', null, null,
                           { allowScriptAccess: 'always', wmode: 'opaque' }, { id: playerId });
    }

    function initializeYouTubeOverlay() {
        var player = $('#youtube-player-container');
        
        playerOverlayElement = $('<div class="youtube-player-overlay" style="width: 640px; height: 480px; background-image: url(/img/introducing-video-still.png); position: absolute; display: none; cursor: pointer;" />');
        playerOverlayElement.bind('click', function () {
            youTubePlayer.playVideo();
        });
        playerOverlayElement.bind('mouseenter', function () {
            playerOverlayElement.css('background-position', '-640px 0');
        });
        playerOverlayElement.bind('mouseleave', function () {
            playerOverlayElement.css('background-position', '0 0');
        });
        player.parent().prepend(playerOverlayElement);
    }

    function playVideo(video) {
        if (!currentVideo || currentVideo.groupId !== video.groupId || currentVideo.videoId !== video.videoId) {
            currentVideo = video;
            ensureHighestQuality = true;
            if (youTubePlayer.getPlayerState() === youTubePlayerStates.videoCued) {
                youTubePlayer.cueVideoById(video.youTubeId);
                onYouTubePlayerStateChange(youTubePlayerStates.videoCued);
            } else {
                youTubePlayer.cueVideoById(video.youTubeId);
            }
            $('#headline h1').text(video.h1);
            $('#headline h2').text(video.h2);
        }
    }

    function onTabClicked(event) {
        var anchor = $(this),
            demoPicker = $('#demo-picker');

        if (!anchor.parent('li').hasClass('on')) {
            demoPicker.find('.group-videos:visible').hide();
            demoPicker.find(anchor.attr('href')).show();
            demoPicker.find('.demo-picker-nav .on').removeClass('on');
            anchor.parent('li').addClass('on');
        }
        event.preventDefault();
    }

    function initializeTabs() {
        var demoPicker = $('#demo-picker'),
            nav = $('<ul class="demo-picker-nav" />').prependTo(demoPicker);

        // modify dom
        demoPicker.find('h3').each(function () {
            var h3 = $(this),
                li = $('<li />').appendTo(nav);
            h3.contents().appendTo(li);
            h3.remove();
        });

        // support tab selection
        nav.find('a').bind('click', onTabClicked);
        // set the active tab
        nav.find('a').eq(0).triggerHandler('click');
    }

    function selectTab(groupId) {
        $('#demo-picker .demo-picker-nav a[href="#' + groupId + '"]').triggerHandler('click');
    }

    function onHashChanged() {
        var video = (window.location.hash && window.location.hash.length > 0) ?
            findVideoByPropertyValue('hashUrl', window.location.pathname + window.location.hash) :
            findVideoByPropertyValue('youTubeId', config.youTubeId);

        selectTab(video.groupId);
        playVideo(video);
    }

    function ensurePlayerVisible() {
        var isViewPortLargerTallerThanPlayer,
            isPlayerCompletelyVisible,
            $window = $(window),
            $youTubePlayer = $(youTubePlayer);

        isViewPortLargerTallerThanPlayer = $window.height() > $youTubePlayer.outerHeight();
        if (isViewPortLargerTallerThanPlayer) {
            isPlayerCompletelyVisible = ($window.scrollTop() < $youTubePlayer.offset().top) && (($youTubePlayer.offset().top + $youTubePlayer.outerHeight()) < ($window.scrollTop() + $window.height()));
            if (!isPlayerCompletelyVisible) {
                $.scrollTo($('#demo-view'), 250);
            } 
        }
    }

    function onVideoLinkClicked(event) {
        var anchor = $(this),
            url = anchor.attr('href'),
            video = findVideoByPropertyValue('url', url);

        event.preventDefault();
        autoPlay = true;
        window.location.href = video.hashUrl;
        ensurePlayerVisible();
    }

    function onRequestButtonClick(event) {
        $('#demo-request').block({
            message: '<h1>Please wait...</h1>',
            css: {
                width: '80%'
            }
        });

        // post the form via ajax
        $('#demo-request form').ajaxSubmit({
            cache: false,
            dataType: 'text',
            error: function () {
                // resubmit the form without ajax so the user is aware of the error
                $('#demo-request form').submit();
            },
            success: function (data) {
                $('#demo-request').unblock().html(data);
                // TODO: scroll top of #demo-request into view
            }
        });

        event.preventDefault();
    }

    function init(options) {
        $.extend(config, options);
        $(function () {
            // tabs UI
            initializeTabs();
            // ajax form
            $('#demo-request button').live('click', onRequestButtonClick);
            // create overlays to show custom video thumbnails in youtube player
            initializeYouTubeOverlay();
            // load the video
            autoPlay = config.autoPlay;
            currentVideo = findVideoByPropertyValue('hashUrl', window.location.pathname + window.location.hash);
            if (currentVideo) {
                $('#headline h1').text(currentVideo.h1);
                $('#headline h2').text(currentVideo.h2);
            } else {
                currentVideo = findVideoByPropertyValue('youTubeId', config.youTubeId);
            }
            initializeYouTubePlayer(currentVideo.youTubeId, function (playerId) {
                youTubePlayer = $('#' + playerId)[0];
                youTubePlayer.addEventListener('onStateChange', 'window.custom.demos.onYouTubePlayerStateChange');
                
                // enable hash url support
                $(window).bind('hashchange', onHashChanged);
                $('#demo-picker a.playable-demo').bind('click', onVideoLinkClicked);
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.demos = {
        init: init,
        onYouTubePlayerStateChange: onYouTubePlayerStateChange
    };
}());

// window.custom.contact
(function () {
    var config = {
            isNotCurrentCustomerId: null,
            isCurrentCustomerId: null,
            jobTitleId: null,
            businessTypeId: null,
            postalCodeId: null,
            postalCodeValidatorId: null,
            referralSourceId: null,
            referralSourceValidatorId: null,
            sendContactFormButtonId: null
        };

    function onIsCurrentCustomerChanged(event) {
        var isCurrentCustomer = $('#' + config.isCurrentCustomerId).is(':checked'),
            selectors = [
                '#' + config.jobTitleId,
                '#' + config.businessTypeId,
                '#' + config.postalCodeId,
                '#' + config.referralSourceId
            ];

        $.each(selectors, function (index, selector) {
            if (isCurrentCustomer) {
                $(selector).parent('li').hide('fast');
            } else {
                $(selector).parent('li').show('fast');
            }
        });
        window.ValidatorEnable($('#' + config.postalCodeValidatorId)[0], !isCurrentCustomer);
        window.ValidatorEnable($('#' + config.referralSourceValidatorId)[0], !isCurrentCustomer);
        $('#' + config.postalCodeValidatorId).hide();
        $('#' + config.referralSourceValidatorId).hide();
        if ($(this).is(':radio')) {
            $(this).focus();
        }
    }

    function init(options) {
        $.extend(config, options);
        $(function () {
            $('#JavaScriptUnavailable').val('false');

            $('#' + config.sendContactFormButtonId).bind('click', function (event) {
                event.preventDefault();
            });

            $('#' + config.isNotCurrentCustomerId).bind('click', onIsCurrentCustomerChanged);
            $('#' + config.isCurrentCustomerId).bind('click', onIsCurrentCustomerChanged);
            onIsCurrentCustomerChanged();
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.contact = {
        init: init
    };
}());

// window.custom.pricing
(function () {
    function onAskButtonClick(event) {
        $('#pricing-request').block({
            message: '<h1>Please wait...</h1>',
            css: {
                width: '80%'
            }
        });

        // post the form via ajax
        $('#pricing-request form').ajaxSubmit({
            cache: false,
            dataType: 'text',
            error: function () {
                // resubmit the form without ajax so the user is aware of the error
                $('#pricing-request form').submit();
            },
            success: function (data) {
                $('#pricing-request').unblock().html(data);
            },
            complete: function (request) {
                $('#pricing-request').unblock();
            }
        });

        event.preventDefault();
    }

    function init() {
        $(function () {
            // ajax form
            $('#pricing-request button').live('click', onAskButtonClick);
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.pricing = {
        init: init
    };
}());

// window.custom.reviews
(function () {

    function initializeAnythingSlider() {
        $('.anythingSlider').fadeIn();

        $('.anythingSlider').anythingSlider({
            easing: "swing",
            autoPlay: false,
            animationTime: 0,              // How long the slide transition takes
            hashTags: true,                // Should links change the hashtag in the URL?
            buildNavigation: false         // If true, builds and list of anchor links to link to each slide
        });

        var videoCnt = $(".anythingSlider li:not(.cloned)").length,
            randomVid = Math.ceil(Math.random() * videoCnt);

        $('.anythingSlider').anythingSlider(randomVid);
        $('.anythingSlider').data('AnythingSlider').options.animationTime = 600;
    }

    function hasClass(element, classes) {
        for (var i = 0; i < classes.length; i++) {
            if (element.hasClass(classes[i])) {
                return true;
            }
        }
        return false;
    }

    function onFilterChanged() {
        var reviewTypeFilters = [],
            specialtyFilters = [],
            reviews;

        // populate filters
        $('#filter .review-type-filters input:checkbox:checked').each(function () {
            var filter = $(this).attr('id').split('-')[1];
            reviewTypeFilters.push(filter);
        });
        $('#filter .specialty-filters input:checkbox:checked').each(function () {
            var filter = $(this).attr('id').split('-')[1];
            specialtyFilters.push(filter);
        });
        // hide/show reviews
        reviews = $('.review');
        reviews.hide();
        if (reviewTypeFilters.length !== 0 && specialtyFilters.length !== 0) {
            reviews = reviews.filter(function () {
                // return true to show this element
                var self = $(this);
                return hasClass(self, reviewTypeFilters) && hasClass(self, specialtyFilters);
            });
            reviews.show();
        }
    }

    function onHashChanged(event) {
        var filter;

        filter = window.location.hash || '#/all';
        filter = filter.substr(2);
        //Remove the 'active' class from all the filter links
        $('#scope li a').removeClass('active');
        //Add it to this one.
        $('#scope li a[href="#' + filter +'"]').addClass('active');
        //If we clicked the "all" link...
        if (filter === 'all') {
            //Show all the feedback items
            $('#results .result-set').show();
        } else {
            //...then show just the ones who's ID matches the feedback items class
            $('#results .result-set').hide();
            $('.result-set#' + filter).fadeIn();
        }
    }

    function replaceHash(value) {
        var url = window.location.toString(),
            hashIndex = url.indexOf('#');

        if (hashIndex >= 0) {
            url = url.substr(0, hashIndex);
        }
        url = url + '#/' + value;
        window.location.replace(url);
    }

    function init() {
        $(function () {
            initializeAnythingSlider();

            $(window).bind('hashchange', onHashChanged);
            $(window).trigger('hashchange');

            $('#scope li a').click(function (event) {
                var currentHash = window.location.hash,
                    selection = $(this).attr('href').substr(1);

                if (currentHash !== '#/' + selection) {
                    $('#results .result-set').fadeOut();
                    replaceHash(selection);
                }
                event.preventDefault();
            });


            $('#filter input:checkbox').click(function () {
                onFilterChanged();
            });
            
            $("#checkboxall").click(function (event) {
                var isSelectingAll = $(this).text() === 'Select All';
                if (isSelectingAll) {
                    $('#tocheckall input:checkbox').attr('checked', 'checked');
                } else {
                    $('#tocheckall input:checkbox').removeAttr('checked');
                }
                $(this).text(isSelectingAll ? 'Deselect All' : 'Select All');
                onFilterChanged();
                event.preventDefault();
            });
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.reviews = {
        init: init
    };
} ());

// window.custom.home
(function () {
    function initializeAnythingSlider() {
        $('.anythingSlider').fadeIn();
        
        $('.anythingSlider').anythingSlider({
            easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: false,
            animationTime: 0,             // How long the slide transition takes
            hashTags: false,                // Should links change the hashtag in the URL?
            buildNavigation: false         // If true, builds and list of anchor links to link to each slide
        });
   
        var videoCnt = $(".anythingSlider li:not(.cloned)").length,
            randomVid = Math.ceil(Math.random() * videoCnt);
        $('.anythingSlider').anythingSlider(randomVid);
        $('.anythingSlider').data('AnythingSlider').options.animationTime = 600;
    }

    function init() {
        $(function () {
            var hint = 'Enter your email address...',
                inputElement = $('#subscribe-to-newsletter-form input[name=emailaddress]'),
                submitElement = $('#subscribe-to-newsletter-form input[type=submit]');

            inputElement.val(hint);
            inputElement.focus(function () {
                if ($(this).val() === hint) {
                    $(this).val('');
                }
            });
        
            submitElement.click(function (event) {
                if (inputElement.val() === hint) {
                    inputElement.val('');
                }
            });

            // Details Panel
            // Move to Bottom
            $('#detail_panel_wrap').hide();
            $('#content').append($('#detail_panel_wrap'));
            $('#detail_panel_wrap').show();
            $('#detail_panel_wrap').addClass('loaded');
            //Hide More detauils on page load
            $('.detail_panel_more, .detail_linkage_more').hide();

            //Click Read More
            $('.panel_more').click(function () {
                $(this).fadeOut('fast');
                $('.detail_panel_more, .detail_linkage_more').comboToggle();
                return false;
            });

            //Click Collapse
            $('.panel_less').click(function () {
                $('.detail_panel_more, .detail_linkage_more').comboToggle();
                $('.panel_more').fadeIn('fast');
                return false;
            });

            initializeAnythingSlider();
        });
    }

    // export api
    window.custom = window.custom || {};
    window.custom.home = {
        init: init
    };
}());
