﻿(function($) {

    var helper = {},

		current,
		sites,
		contactSite,
		selectedContactListItem,
		currentContactID,
		timer,
		uiLoaded,
		isVisible,
		settings,
		currentFilter,

		firefoxMacMapHack;

    $.directoryMe = {
        defaults: {
            proxyUrl: "/CrossDomain.ashx"
        }
    };

    $.fn.extend({
        directoryMe: function(options) {
            settings = $.extend({}, $.directoryMe.defaults, options);

            this.click(function() {
                show();
                return false;
            });
        }
    });

    function initialize() {

        injectRequiredTags();
        setStaticVariables();
        fillUI(getStaticUITags());
        moveWebcastObjectAndRegisterItsEvents();
        registerUIEvents();
        $('#SearchContact').watermark();
    }

    function getStaticUITags() {

        var str = '';
        str += '<div id="ContactList">';
        str += '    <div id="Search">';
        str += '        <label for="SearchContact">';
        str += '            Rechercher un contact<\/label>';
        str += '        <input type="text" id="SearchContact" name="SearchName" \/>';
        str += '        <a href="#" id="ResetSearchFilter" title="Effacer le filtre"><span><\/span>Effacer le';
        str += '            filtre<\/a>';
        str += '    <\/div>';
        str += '    <!-- \/Search -->';
        str += '    <div id="Contacts" style="display: none;">';
        str += '    <\/div>';
        str += '    <div id="ContactsLoading">';
        str += '        <p>';
        str += '            Loading...<\/p>';
        str += '    <\/div>';
        str += '    <!-- \/Contacts -->';
        str += '<\/div>';
        str += '<!-- \/ContactList -->';
        str += '<div id="ContactInfo" class="vcard">';
        str += '    <span id="ContactVCard"><\/span>';
        str += '    <!-- \/ContactVCard -->';
        str += '    <div id="ContactInfoExplanation">';
        str += '        <h2>';
        str += '            Pages Blanches<\/h2>';
        str += '        <p class="Subtitle">';
        str += '            Chercher un contact dans le personnel HEIG-VD<\/p>';
        str += '        <p>';
        str += '            Le service des pages blanches permet de rechercher des personnes qui travaillent';
        str += '            à la HEIG-VD.<\/p>';
        str += '        <p>';
        str += '            Dans sa forme la plus simple, il permet de retrouver une personne en introduisant';
        str += '            une partie du nom ou du prénom.<\/p>';
        str += '        <p>';
        str += '            Notez qu\'il est également possible de rechercher quelqu\'un par initiales (3 lettres';
        str += '            en majuscules), par nom de département, par lieu de travail (St-Roch, Cheseaux ou';
        str += '            Y-Parc), par bureau ou encore par téléphone.<\/p>';
        str += '        <a href="#" id="DirectoryMeShowWebcast"><span>Show Webcast<\/span><\/a>';
        str += '    <\/div>';
        str += '    <div id="ContactInfoContent" style="display: none;">';
        str += '    <\/div>';
        str += '    <div id="DirectoryMeClose">';
        str += '        <a href="#" title="Fermer"><span><\/span>Fermer l\'annuaire<\/a><\/div>';
        str += '<\/div>';
        str += '<!-- \/ContactInfo -->';
        str += '<div id="MapContainer">';
        str += '    <div id="Map">';
        str += '    <\/div>';
        str += '    <a id="CloseMap" href="#">Fermer la carte<\/a>';
        str += '<\/div>';
        str += '<div id="DirectoryMeWebcastWrapper">';
        str += '<\/div>';
        str += '<div id="DirectoryMeWebcast">';
        str += '    <div class="Header">';
        str += '        <h2>';
        str += '            <span><\/span>Tutorial Page Blanches<\/h2>';
        str += '        <a href="#" id="CloseTutorial" title="Fermer le tutorial"><span><\/span>Fermer le tutorial<\/a>';
        str += '    <\/div>';
        str += '    <div class="Movie">';    
        str += '    <\/div>';
        str += '<\/div>';

        return str;
    }

    function injectRequiredTags() {
        $('body').prepend(
            '<div id="DirectoryMeWrapper"></div>' +
            '<div id="DirectoryMeContainer"></div>');

        $("#DirectoryMeWrapper").
	        hide().
	        css("opacity", 0);

        $("#DirectoryMeContainer").
	        hide().
	        css("top", -800);
    }

    function setStaticVariables() {
        uiLoaded = false;
        isVisible = false;
        sites = {
            StRoch: { lon: 46.78117371810515, lat: 6.647372245788574 },
            Cheseaux: { lon: 46.778852027708766, lat: 6.659806966781616 },
            YParc: { lon: 46.7646478625706, lat: 6.6464924812316895 }
        };

        firefoxMacMapHack =
            (BrowserDetect.browser == "Firefox" && BrowserDetect.OS == "Mac");
    }

    function show() {

        if (!uiLoaded) {
            initialize();
            uiLoaded = true;
        }

        startAnimatingPanel();
    }

    function hideMap() {
        $('#MapContainer').hide();
    }

    function showCallback() {

        contactsLookup();
        showElementHiddenForAnimation();

        isVisible = true;
    }

    function showElementHiddenForAnimation() {
        $('#ContactInfoContent').show();
        $('#Contacts').show();
    }

    function hideElementsForAnimation() {

        $('#ContactInfoContent').hide();
        $('#Contacts').hide();

        $('#ContactsLoading').hide();

        hideMap();
    }

    function hide() {

        hideElementsForAnimation();

        $("#DirectoryMeContainer").
	        animate({ top: 50 }, 500).
            animate({ top: 80 }, 300).
            animate({ top: -800 }, 400, function() {
                $(this).hide();
            });

        $("#DirectoryMeWrapper").
            animate({ opacity: 0 }, 1000, function() {
                $(this).hide();
            });

        isVisible = false;
    }

    function setProgressBarVisibility(show) {
        (show) ?
            $('#ContactsLoading').show() :
            $('#ContactsLoading').hide();
    }

    function startAnimatingPanel() {
        setProgressBarVisibility(true);

        $("#DirectoryMeWrapper").
            show().
            animate({ opacity: 0.8 }, 3000);

        $('#DirectoryMeContainer').
            show().
            css("top", -800).
            animate({ top: 80 }, 400).
            animate({ top: 50 }, 300).
            animate({ top: 60 }, 500, function() {
                showCallback();
            });
    }

    function registerUIEvents() {

        $("#DirectoryMeClose").click(function() {
            hide();
            return false;
        });

        $("#ResetSearchFilter").click(function() {
            $('#SearchContact').val('').focus();
            hideMap();
            contactsLookup();
            return false;
        });

        $("#SearchContact").keyup(function(e) {

            if (e) {
                if (e.keyCode == 13)
                    return;

                controlContactsLookupTrigger();
            }
        });
    }

    function controlContactsLookupTrigger() {
        if (!timer) {
            timer = $.timer(600, function(timer) {

                timer.stop();
                timer = null;

                contactsLookup();
            });
        }
        else
            timer.reset(600);
    }

    function contactsLookup() {
        var filter = $('#SearchContact').hasClass('Empty') ? '' : $('#SearchContact').val();

        if (currentFilter != filter) {

            $('#MapContainer').hide();

            $.ajax({
                url: resolveProxyUrl("ContactsList/" + filter),
                async: true,
                dataType: "text",
                success: function(data) {
                    contactsListCallback(data);
                },
                error: function() {
                    alert("An error occured while retrieveing contacts.");
                }
            });

            currentFilter = filter;
        }
    }

    function contactsListCallback(data) {
        setProgressBarVisibility(false);

        $("#Contacts").show().html(data);
        registerEventsOnContacts();
    }

    function registerEventsOnContacts() {
        $("#Contacts > ul > li > ul > li").click(function() {
            onContactClick.call(this);
            return false;
        });
    }

    function moveWebcastObjectAndRegisterItsEvents() {

        $('#DirectoryMeWebcastWrapper').
            remove().
            insertAfter("#DirectoryMeContainer").
            css("opacity", 0);

        $('#DirectoryMeWebcast').
            remove().
            insertAfter("#DirectoryMeWebcastWrapper");

        $('#DirectoryMeShowWebcast').click(function() {
            $('#DirectoryMeWebcastWrapper').
                show().animate({ opacity: 0.8 }, 1000);
            $('#DirectoryMeWebcast').show();
            showWebcast();
        });

        $('#CloseTutorial').click(function() {
            // Remove Silverlight content
            $('#DirectoryMeWebcast .Movie').html('');
            $('#DirectoryMeWebcastWrapper').
                animate({ opacity: 0 }, 1000, function() {
                    $(this).hide();
                });
            $('#DirectoryMeWebcast').hide();
        });
    }

    function showWebcast() {

        var webcastUri = resolveProxyUrl("Tutorial");

        $.get(webcastUri, function(data) {
            // Inject Silverlight content
            $('#DirectoryMeWebcast .Movie').html(data);
        });
    }

    function fillUI(data) {
        $("#DirectoryMeContainer").html(data);
    }

    function resolveProxyUrl(action) {
        if (action && action.lastIndexOf("/") == action.length - 1)
            action = action.substring(0, action.length - 1);

        return settings.proxyUrl + "/" + action;
    }

    function onContactClick() {

        var a = $(this).children('a');
        var id = $(a[0]).attr('id');

        if (id && id.indexOf('PersonID_') > -1) {
            id = id.substring('PersonID_'.length);
        }

        if (id && id != currentContactID) {

            selectCurrentContact(false);

            selectedContactListItem = this;
            currentContactID = id;

            showContact(id);

            selectCurrentContact(true);
        }
    }

    function getLongLat() {

        switch (contactSite) {
            case "St-Roch":
                return sites.StRoch;
                break;

            case "Y-Parc":
                return sites.YParc;
                break;

            default:
                return sites.Cheseaux;
                break;
        }
    }

    function showContact(id) {

        var contactUri = resolveProxyUrl("Contact/" + id);

        $.get(contactUri, function(data) {

            var contactData = $(data).filter('div#ContainerContactData');
            var vCardData = $(data).filter('div#ContainervCard');

            var data = $(data).filter('div#Data');
            var site = $.trim(data.find('#Site').html());

            contactSite = site;

            $('#ContactVCard').html(vCardData.html());
            $('#ContactVCard > a').show();
            $('#ContactInfoExplanation').hide();
            $('#ContactInfoContent').show();
            $('#ContactInfoContent').html(contactData.html());
            hideMap();

            $('#ContactPicture').load(function() { $(this).fadeIn('slow'); }).hide();

            $('#Address').click(function() {
                showMap();
                return false;
            });
        });
    }

    function showMap() {
        var coords = getLongLat();

        $('#MapContainer').show();

        if (helper.firefoxMacMapHack)
            $('#Contacts').css("overflow", "hidden");

        var map = new GMap2(document.getElementById("Map"));
        var center = new GLatLng(coords.lon, coords.lat);
        map.setCenter(center, 15);
        var marker = new GMarker(center, { draggable: false });
        map.addOverlay(marker);

        var addressOffset = $('#Address').offset();
        var containerOffset = $('#DirectoryMeContainer').offset();

        var left = addressOffset.left - containerOffset.left - 306;
        var top = addressOffset.top - containerOffset.top - 43;

        $('#MapContainer').css({ left: left, top: top });

        $('#CloseMap').click(function() {
            hideMap();

            if (firefoxMacMapHack)
                $('#Contacts').css("overflow", "auto");

            return false;
        });
    }

    function selectCurrentContact(isSelected) {
        var el = selectedContactListItem;

        if (isSelected) {
            $(el).addClass('Selected');
        }
        else {
            $(el).removeClass('Selected');
        }
    }

})(jQuery);
