/**
 * ePharma
 * version 0.1
 */

/**
 * Epharma
 *
 * @version   1.00.101125
 * @author    LBi Lost Boys
 */

var EPHARMA = (function($) {

  var EPHARMA = {

    init: function() {

        // global ie6 boolean
        this.isIE6 = /msie\s?6/i.test(navigator.userAgent);

        // global to detect all microsoft internet explorers
        this.isIE = /msie/i.test(navigator.userAgent);
        if (this.isIE) {
            this.versionIE = parseFloat(navigator.appVersion.split("MSIE")[1]);
        }
        this.isWebkit = /applewebkit/i.test(navigator.userAgent);
        this.isChrome = /chrome/i.test(navigator.userAgent);
        this.isMobile = ($(window).width() < 640);
        this.isTouch = !!('ontouchstart' in window);

        this.initSimpleMenu();
        this.initEqualized();
        this.initTabs();
        this.initMediaBar();
        this.initDiagnosticPath();
		this.initSimpleSlider();
        this.initMultiplePath();
        this.initFormValidation();
        this.initVideoIframes();
		this.tableCss();
        if (this.isMobile) {
            this.initMobile();
        }

        this.dialogs = new LBi.Dialogs({
            dialogClass: LBi.CenteredDialog,
            nomove: true
        });

        this.vids = []; // to pause videos in IE
        this.dialogs.register('video');
        this.setUpDialogListeners();

        $('input.slider').slider({
           /* settings */
        });

        $('#ecme-module audio').mediaelementplayer({audioWidth: 730});
		
		
		// Make buttons not clickable when header overlaps
		$('#header-mobile').mouseup(function(e){
			e.stopPropagation();
			e.preventDefault();	
		})		
		
        // loadPlayers, quick fix for problem of IE, Chrome and Safari
        // not letting mediaplayer stop, see also stopVideo.
        this.loadPlayers();

        // original solution instead of loadPlayers():
        //$('.figure video, .figure audio').mediaelementplayer();

        var informationBar = $('#information-bar');
        if (informationBar.length > 0) {
            informationBar.find('a[rel=collapse]').click(function(e) {
                e.preventDefault();

                var parent = $(this).closest('.info-detail').hide();
                var li     = informationBar.find('a.more[href*='+parent[0].id+']').parent();
                li.removeClass('active');
            });

            informationBar.find('.info-detail').hide();
            informationBar.find('.more').click(function (e) {
                e.preventDefault();
                var li = $(this).closest('li');
                if (li.hasClass("active")) {
                    li.removeClass("active").siblings().removeClass('active');
                    informationBar.find('.info-detail').hide();
                    $(''+this.hash).hide();
                } else {
                    li.addClass("active").siblings().removeClass('active');
                    informationBar.find('.info-detail').hide();
                    $(''+this.hash).show();
                }
            });
            informationBar.find('.more').each(function() {
                if (this.hash == location.hash) {
                    $(this).click();
                }
            });
        }

    },

/**
 *init & push mediaelementplayers
 */
    loadPlayers: function() {
        var self = this;
        var vs = $('video');
        self.vids = [];
        $.each(vs, function(key, val){
            self.vids.push(new MediaElementPlayer(val));
        });
    },

    initMediaBar: function() {
		$('.mediabar-id-classe').attr('id','mediabar');
        $('.mediabar').mediabar({
            scroll: 1,
            clipSelector: "ol.slides",
            itemSelector: "ol.slides > li"
        });
    },

    initDiagnosticPath: function() {
        if ($('#nav-diagnostic').length == 0) {
            return;
        }
        var diagnosticPath = new DiagnosticPath();
        $('a.dp-trigger').click(diagnosticPath.start.bind(diagnosticPath));
    },

	initSimpleSlider: function() {
		if ($('#nav-page').length == 0) {
			return;
		}
		var diagnosticPath = new SimpleSlider();
		$('a.dp-trigger').click(diagnosticPath.start.bind(diagnosticPath));
	},

    initMultiplePath: function(){
        var path = $('.multiple-path').eq(0);
        if(path.length && window.MultiplePath) {
            this.multiplePath = new MultiplePath(path);
        }
    },

    initSimpleMenu: function() {

        $('#nav-main ul:first').simpleMenu({
            switchDelay:    100,
            closeDelay: 500,
            menuSelector: 'div.nav_sub',
            animation: LBi.Animation.SLIDE
        });

        if (!this.isMobile) {
            $('#nav-main ul:first > li:has(.nav_sub) > a').click(function(e) {
                e.preventDefault();
            });
        }
    },

    initEqualized: function() {

        var equal = new LBi.EqualizedNodes({
            selector: '.equalized',
            children: '.column .equal'
        });
    },

    initTabs: function() {

        if ($('#alternating-header').length > 0) {
            $('#alternating-header ul.slides li').each(function() {
                $(this).find('div.column:last').addClass("last");
            });
            var self = this;
            $('#alternating-header').hover(
                function() {
                    self.hpHeaderHovered = true;
                },
                function() {
                    self.hpHeaderHovered = false;
                }
            );
            this.hpTabs = new LBi.Tabs({
                activeClass: 'active',
                selector: '#alternating-header ul.nav',
                relation: 'tab',
                animation: LBi.Animation.TOGGLE,
                duration: 500
            });
            setInterval(this.rotateHomepageTabs.bind(this), 8000);
        }
    },

    initVideoIframes: function() {
        // Pause youtube videos
        var ytVids = $(".dialog .youtube iframe");
        for (var i = 0; i < ytVids.length; i++) {
            var vid = $(ytVids[i]);
            if (vid.attr('id') == '') {
                vid.attr('id', 'youtube' + i);
            }
        }
        var vimeoVids = $(".dialog .vimeo iframe");
        for (var i = 0; i < vimeoVids.length; i++) {
            var vid = $(vimeoVids[i]);
            if (vid.attr('id') == '') {
                vid.attr('id', 'vimeo' + i);
            }
            var src = vid.attr('src');
            if (src.indexOf('api=') == -1) {
                var api = 'api=1';
                if (src.indexOf('?') == -1) {
                    api = '?' + api;
                } else {
                    api = '&' + api;
                }
                vid.attr('src', src + api);
            }
        }
    },

    rotateHomepageTabs: function(e) {
        // Check if an overlay is shown, if so do not rotate the tabs
        if ($(".overlay:visible").length == 0) {
            if (this.hpHeaderHovered) {
                return;
            }
            var nav = $('#alternating-header ul.nav');
            var activeNavItem =  nav.find('li.active:first');
            var next = (activeNavItem.next().length > 0) ? activeNavItem.next() : nav.find('li:first');
            next.find('a:first').click();
        }
    },

    initFormValidation: function() {
        $('form').h5Validate().find('p.error').hide();
    },

    setUpDialogListeners: function(){
        $('.dialog-video .close').live('click', this.stopVideo.bind(this));
        $('.dialog-video .cancel').live('click', this.stopVideo.bind(this));
        $('.overlay').live('click', function(){
            if ($('.dialog-video').is(':visible')) {
                this.stopVideo();
            }
        }.bind(this));
    },

    stopVideo : function(){
        // Only for ipad
        if (this.isWebkit) {
            // different versions of webkit, but all have issues...
            // Pause youtube videos
            var ytVids = $(".dialog .youtube iframe");
            for (var i = 0; i < ytVids.length; i++) {
                var vid = ytVids[i];
                if (!$(vid).is(':visible')) {
                    continue;
                };
                try {
                    var yt = new YT.Player(vid.id);
                    yt.pauseVideo();
                } catch(e) {
                    LBi.log('Cannot pause the video:', yt, e);
                }
                // hack to make sure Safari stops displaying the
                // vid (note that this messes up Chrome, no idea if this
                // is webkit-version or browser-specific)
                if (!this.isChrome) {
                    $(vid).attr('src', $(vid).attr('src'));
                };
            }
            // Pause vimeo videos
            var vimeoVids = $(".dialog .vimeo iframe");
            for (var i = 0; i < vimeoVids.length; i++) {
                var vid = vimeoVids[i]; // iframe
                if ($(vid).parent('.dialog').css('display') == 'none') {
                    continue;
                };
                try {
                    var vimeo = new Froogaloop(vid.id);
                    vimeo.api('pause');
                    vimeo.api('seekTo', 0);
                } catch(e) {
                    LBi.log('Cannot pause the video:', vimeo, e);
                }
            }
        } else if (this.isIE) {
            // IE has another set of issues, older versions (< 9) do not
            // support window.postMessage, which is required for Froogaloop,
            // and 9 requires Vimeo movies to be explicitly stopped
            var self = this;
            $(".dialog .vimeo iframe").each(function() {
                if (self.versionIE < 9) {
                    this.src = this.src;
                } else {
                    try {
                        var vimeo = new Froogaloop(this.id);
                        vimeo.api('pause');
                        vimeo.api('seekTo', 0);
                    } catch(e) {
                        LBi.log('Cannot pause the video:', vimeo, e);
                    }
                };
            });
            $(".dialog .youtube iframe").each(
                function() {
                    this.src = this.src;
                });
        };
        // IE, Chrome and Safari need to be told that the MP4 video should stop
        for (var v in this.vids) {
            var vid = this.vids[v];
            try {
                vid.pause();    // stop() won't work in IE/is not standard
            } catch(e) {
                LBi.log('Cannot pause the video:', vid, e);
            }
        }
    },
	
	tableCss : function(){
		var tables = $('table');

		tables.each(function(){
			var cellpadding = $(this).attr('cellpadding');
			var border = $(this).attr('border');
			var align = $(this).attr('align');			
			$(this).removeAttr('cellpadding');
			$(this).removeAttr('border');
			$(this).removeAttr('align');
			
			$(this).find('td, th').css({'border-style':'solid', 'padding':cellpadding+'px','border-width':border+'px','text-align':align})
		})
	},

    /**
     * Initializes the mobile extra's.
     */
    initMobile: function() {
        this.isWebkit534 = $.browser.webkit && $.browser.version >= 534;
        // Init mobile nav
        this.setupMobileNav();
    },

    /**
     * Initializes the mobile top navigation.
     */
    setupMobileNav: function() {
        this.mobileNav = $('#header-mobile');
        this.mobileNavOffset = 0;

        // For iOS5 (webkit v544 and higher) we leave the nav bar position fixed
        if (!this.isWebkit534) {
            // Set the mobile nav to absolute position
            this.mobileNav.css('position', 'absolute');
            this.mobileNavOffset = this.mobileNav.offset().top;
            this.setMobileNav();
            $(window).bind('scroll', this.setMobileNav.bind(this));
        }
        this.mobileNav.find('a').bind('click', this.handleMobileNavClick.bind(this));
    },

    /**
     * Sets the mobile nav to the top of the screen.
     */
    setMobileNav: function() {
        var top = $(document).scrollTop() - this.mobileNavOffset;
        this.mobileNav.css('top', top + 'px');
    },

    /**
     * Handle the mobile navigation click.
     * @param {Event} e the event
     */
    handleMobileNavClick: function(e) {
        e.preventDefault();
        // Get target link
        var target = $(e.target);
        if (!target.is('a')) {
            target = target.closest('a');
        }
        // Scroll to the element that has the id of the hash
        var hash = target.attr('href').replace('#', '');
        if (hash != '') {
            var top = $('[id=' + hash + ']').offset().top - this.mobileNav.height();
            $(document).scrollTop(top);
        } else {
            $(document).scrollTop(0);
        }
        // Set the mobile nav to the correct position
        if (!this.isWebkit534) {
            this.setMobileNav();
        }
    }
  };


setTimeout(function(){
  $(function() {
    EPHARMA.init();
  });
}, 200);

  return EPHARMA;

})(jQuery);

