﻿var NGCOA = {},
    _gaq = [];

NGCOA.Navigation = {
    $nav: null,
    init: function () {
        this.$nav = $("#nav > ul > li").mouseover(this.onMouseover).mouseout(this.onMouseout);
    },
    onMouseover: function () {
        $(this).addClass("hover").find("ul").show();
    },
    onMouseout: function () {
        $(this).removeClass("hover").find("ul").hide();
    }
}

NGCOA.Banners = {
    $bannersContainer: null,
    bannerTimerId: null,
    currentBanner: 1,
    numberOfBanners: 1,
    animating: true,
    duration: 8000,
    fadeDuration: 700,
    init: function () {
        this.$bannersContainer = $("#banners");        
        this.numberOfBanners = $("li", this.$bannersContainer).length;
        if (this.numberOfBanners > 1) {
            this.currentBanner = $(".active-banner", this.$bannersContainer).index() + 1;
            this.startBannerAnimation();
        }        
    },
    startBannerAnimation: function () {
        var me = NGCOA.Banners;
        me.animating = true;
        me.bannerTimerId = setInterval(function () {
            me.currentBanner++;
            if (me.currentBanner > me.numberOfBanners) {
                me.currentBanner = 1;
            }
            me.loadBanner(false);
        }, me.duration);
    },
    loadBanner: function (continueRotation) {
        var me = NGCOA.Banners;
        // fade current banner out, fade supplied banner in
        $(".active-banner", me.$bannersContainer).removeClass("active-banner").fadeTo(me.fadeDuration, 0.0, function () {
            $(this).addClass("hide");
            $("li:eq(" + (me.currentBanner - 1) + ")", me.$bannersContainer).addClass("active-banner").css("opacity", "0.0").removeClass("hide").fadeTo(me.fadeDuration, 1.0);
        });
        if (continueRotation) {
            me.startBannerAnimation();
        }
    }
};

NGCOA.Localization = {
    currentLocaleID: "4105",
    init: function () {
        this.currentLocaleID = $("#localeID").val();
        $("#langToggle").click(this.onLanguageToggleClick);
    },
    get: function () {
        return this[this.currentLocaleID];
    },
    "4105": {
        voteSelectionRequired: "Please choose an option.",
        votingError: "There was a problem adding your vote."
    },
    "3084": {
        voteSelectionRequired: "Veuillez choisir une option.",
        votingError: "Il y a eu un problème pour ajouter votre vote."
    },
    onLanguageToggleClick: function (e) {
        e.preventDefault();
        var defaultUrl = $(e.target).attr("href"),
            folderID = $("#folderID").val() || '';

        if (folderID.length > 0 && !isNaN(folderID)) {
            $.ajax({
                type: 'POST',
                url: '/services.asmx/GetFolderDocumentToggleUrl',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: '{folderID: ' + parseInt(folderID) + ', currentLocaleID: ' + NGCOA.Localization.currentLocaleID + '}',
                success: function (data) {
                    window.location = data.d + window.location.search;
                },
                error: function () {
                    window.location = defaultUrl;
                }
            });
        } else {
            // no folderID (or we're at the root) - look to pathname to toggle
            var url = window.location.pathname;
            if (url && url.length > 0) {
                if (NGCOA.Localization.currentLocaleID === "3084") {
                    url = url.substring(6);
                } else {
                    url = '/fr-ca' + url;
                }
                window.location = url;
            } else {
                window.location = defaultUrl;
            }
        }
    }
};

NGCOA.isProduction = (function () {
    return (/ngcoa\.ca$/).test(window.location.hostname);
} ());

NGCOA.GoogleAnalytics = function (options) {
    var settings = $.extend({
        enabled: true,

        // Google account ID e.g. UA-0000000-00
        accountId: null,

        // clickable elements to attach events to
        elements: ['a', 'area'],

        // collection of link types, each of which may be 
        // identified and click-handled using custom logic
        linkTypes: {
            outbound: {
                cssClass: 'outbound',
                identify: function (obj) {
                    return !obj.href.match(/^mailto\:/) && (obj.hostname !== location.hostname);
                },
                onClick: function () {
                    _gaq.push(['_trackEvent', 'OutboundLink', 'Click', $(this).attr('href')]);
                }
            },
            download: {
                cssClass: 'download',
                identify: function (obj) {
                    var // download filetypes may be extended
                                                ext = ['pdf','xls','xlsx','doc','docx','ppt','pptx'],
                                                pattern = (function () {
                                                    var p = '';
                                                    $.each(ext, function (index, value) {
                                                        p += '\\.' + value + '|';
                                                    });
                                                    p = p.substring(0, p.length - 1);
                                                    return '(' + p + ')$';
                                                } ()),
                                                m = obj.href.match(new RegExp(pattern, 'i'));

                    return (m && m.length >= 1);
                },
                onClick: function () {
                    var url = $(this).attr("href"),
                        ext = url.split('.').pop().toUpperCase();
                    _gaq.push(['_trackEvent', 'Downloads', ext, url]);
                }
            }
        }
    }, options || {}),
              identifyElements = function () {
                  $.each(settings.linkTypes, function (key, obj) {
                      $.expr[':'][key] = obj.identify;
                      markElements(obj.cssClass);
                  });
              },
              markElements = function (className) {
                  $.each(settings.elements, function (index, value) {
                      $(value + ':' + className).addClass(className);
                  });
              },
              attachHandlers = function () {
                  $.each(settings.linkTypes, function (key, obj) {
                      $.each(settings.elements, function (index, value) {
                          $(value + ':' + key).click(obj.onClick);
                      });
                  });
              };

    identifyElements();

    if (settings.enabled === true) {
        if (!settings.accountId) {
            throw 'You must provide an account ID';
            return false;
        }
        attachHandlers();

        _gaq.push(['_setAccount', settings.accountId]);
        _gaq.push(['_trackPageview']);
        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        } ());
    }
};

$(function () {
    NGCOA.GoogleAnalytics({
        enabled: NGCOA.isProduction,
        accountId: 'UA-12110004-1'
    });
    NGCOA.Localization.init();
    NGCOA.Navigation.init();
    NGCOA.Banners.init();
    $("#q_go").removeClass("hide").click(function () {
        $(this).closest("form").submit();
    });
});

// LEGACY
var win = null;
function NewWindow(mypage, myname, w, h, scroll, pos) {
    if (pos == "random") { LeftPosition = (screen.width) ? Math.floor(Math.random() * (screen.width - w)) : 100; TopPosition = (screen.height) ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100; }
    if (pos == "center") { LeftPosition = (screen.width) ? (screen.width - w) / 2 : 100; TopPosition = (screen.height) ? (screen.height - h) / 2 : 100; }
    else if ((pos != "center" && pos != "random") || pos == null) { LeftPosition = 0; TopPosition = 20 }
    settings = 'width=' + w + ',height=' + h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=' + scroll + ',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
    win = window.open(mypage, myname, settings);
}

// expand + contract
function ExpCon(oid) {
    var tochange = document.getElementById(oid);

    if (tochange.style.display == "block") {
        tochange.style.display = "none";
    } else {
        tochange.style.display = "block";
    }
}

function SetHyperlinkPrefix(tb) {
    if (tb.value == '') {tb.value = 'http://'; }

    if (tb.createTextRange) {
        var FieldRange = tb.createTextRange();
        FieldRange.moveStart('character', tb.value.length);
        FieldRange.collapse();
        FieldRange.select();
    }
}

function ClearHyperlinkPrefix(tb) {
    if (tb.value == 'http://') {tb.value = ''; }
}
