/*global document: false, location: false, alert: false*/
/*global $ */

$(document).ready(function() {
    var isRTL = $('.wrapper').attr('dir') === 'rtl';

    // An ugly workaround for iOS where it doesn't trigger a mouseout event
    // when you click on the body of the page, thus not allowing the dropdowns
    // the header/nav dropdowns to close.
    if (navigator.userAgent.match(/iPad|iPhone|iPod/)) {
        $('.outer-wrapper').click(function(e) {
            var $target = $(e.target);
            if (!$target.hasClass('nav-dropdown') && !$target.parents('.nav-dropdown').length &&
                !$target.hasClass('header-dropdown') && !$target.parents('.header-dropdown').length) {
                $(document.body).click();
            }
        });
    }

    // Pull the nav content from the bottom of the page and move it into place.
    $('.nav-content>div').each(function(index, nav) {
        var $nav = $(nav),
            id = $nav.attr('id');
        $nav.appendTo('.' + id);
    });

// Navigation
    var $nav = $('.nav'),
        navz = $nav.css('z-index');
    $('.nav-item:has(.nav-dropdown)').hoverIntent({
        interval: 50,
        over: function() {
            $('.nav-item-link-selected').removeClass('nav-item-link-selected');
            $('.nav-dropdown').hide();

            // Hack to make sure the dropdown goes on top of everything
            $nav.css('z-index', 100000000);

            $(this).children('.nav-item-link').addClass('nav-item-link-selected');
            $(this).find('.nav-dropdown').show();
        },
        timeout: 350,
        out: function() {
            $(this).children('.nav-item-link').removeClass('nav-item-link-selected');
            $(this).find('.nav-dropdown').hide();

            if ($('.nav-dropdown:visible').length === 0) {
                $nav.css('z-index', navz);
            }
        }
    });

    // Don't do anything when clicking the nav links
    $('.nav-item-link:has(.nav-dropdown)').click(function() {
        return false;
    });

    // IE doesn't treat the select dropdown/input autocomplete as a child of the element and triggers a mouseout
    $('.nav-dropdown select, .nav-dropdown input').mouseleave(function(event) {
        event.stopPropagation();
    });

    // Other Industries
    var $other_links = $('.nav-dropdown-other-links');
    $('.nav-dropdown-other-industries-link').click(function() {
        $other_links.slideToggle('fast');

        return false;
    });

    // Header links dropdown
    var $header = $('.header'),
        headerz = $header.css('z-index');
    $('.header-tools-links>li').hoverIntent({
        interval: 50,
        over: function() {
            $('.header-tools-link-selected').removeClass('header-tools-link-selected');
            $('.header-dropdown').hide();

            // Hack to make sure the dropdown goes on top of everything
            $header.css('z-index', 100000000);

            $(this).children('.header-tools-link').addClass('header-tools-link-selected');
            $(this).find('.header-dropdown').show();
        },
        timeout: 350,
        out: function() {
            $(this).children('.header-tools-link').removeClass('header-tools-link-selected');
            $(this).find('.header-dropdown').hide();

            if ($('.header-dropdown:visible').length === 0) {
                $header.css('z-index', headerz);
            }
        }
    });

    // Don't do anything when clicking the header links
    $('.header-tools-account .header-tools-link, .header-tools-login .header-tools-link, .header-tools-register .header-tools-link').click(function() {
        return false;
    });

    // IE doesn't treat the select dropdown/input autocomplete as a child of the element and triggers a mouseout
    $('.header-dropdown select, .header-dropdown input').mouseleave(function(event) {
        event.stopPropagation();
    });


// General tabs handling
    $('.tabs a').click(function() {
        var $a = $(this),
            $li = $a.parent(),
            $pane = $($a.attr('rel'));

        if ($pane.length) {
            $li.parent().children().removeClass('selected-tab');
            $li.addClass('selected-tab');

            $pane.parent().children().removeClass('selected-tab-pane');
            $pane.addClass('selected-tab-pane');
        }

        return false;
    });


// Content slider for featured articles
    if ($('.featured-slider .featured-item').length > 1) {
        var slider = $('.featured-slider').bxSlider({
            rtl: isRTL,
            auto: true,
            pause: 10000,
            pager: true
        });
        $('.featured .bx-wrapper').hoverIntent({
            over: function() {
                slider.stopShow();

                // IE8 and below don't handle the alpha transparency of the buttons
                // properly and show black while it fades in
                if ($.browser.msie && $.browser.version < 9) {
                    $('.featured .bx-prev').show();
                    $('.featured .bx-next').show();
                }
                else {
                    $('.featured .bx-prev').fadeIn();
                    $('.featured .bx-next').fadeIn();
                }
            },
            out: function() {
                slider.startShow();

                if ($.browser.msie && $.browser.version < 9) {
                    $('.featured .bx-prev').hide();
                    $('.featured .bx-next').hide();
                }
                else {
                    $('.featured .bx-prev').fadeOut();
                    $('.featured .bx-next').fadeOut();
                }
            }
        });
    }


// Show a hint for text inputs
    $('.input-text').each(function() {
        var $input = $(this),
            $form = $(this.form),
            hint = $input.attr('data-hint');

        if (hint) {
            $input.focus(function() {
                $input.removeClass('input-text-hint');
                if ($input.val() === hint) {
                    $input.val('');
                }
            });
            $input.blur(function() {
                if ($input.val() === '' || $input.val() === hint) {
                    $input.val(hint);
                    $input.addClass('input-text-hint');
                }
            });

            $input.blur();
        }

        $form.submit(function() {
            if ($input.val() === hint) {
                $input.val('');
            }
        });
    });


// Show a hint for password inputs
    $('.input-password').each(function() {
        var $input = $(this),
            hint = $input.attr('data-hint');

        if (hint) {
            // Can't just do all this in the .input-text code by just switching
            // type=password to type=text due to security
            var fake_input = $('<div></div>').append($input.clone()).html().replace(/type\s*=\s*["']?password(\s*["'])?/ig, 'type="text"'),
                $fake_input = $(fake_input).hide().val(hint).addClass('input-text-hint').attr('name', '');

            $input.after($fake_input);

            $fake_input.focus(function() {
                $fake_input.hide();
                $input.show().focus();
            });
            $input.blur(function() {
                if ($input.val() === '') {
                    $input.hide();
                    $fake_input.show();
                }
            });

            $input.blur();
        }
    });


// Datepicker
    $('.datepicker').each(function() {
        var $dp = $(this);
        var format = $dp.attr('data-datepicker-format') || 'yy-mm-dd';

        $dp.datepicker({
            dateFormat: format
        });
    });


// Social media bar
    if ($('.social-bar').length) {
        $.getJSON('/static/json/twitter-' + (isRTL ? 'ar' : 'en') + '.json', function(data) {
            // HTML escape text (note: doesn't escape quotes)
            var esc = function(text) {
                return $('<div/>').text(text).html();
            };

            // JavaScript version of AME::UI::limit()
            var limit = function(str, len) {
                if (str && len && str.length > len) {
                    var orig = str;
                    str = str.substr(0, len - 3);

                    if (!orig.substr(len - 3, 1).match(/\s/) && str.match(/\s/)) {
                        str = str.replace(/\w+$/, '');
                    }
                    str = str.replace(/\s+$/, '');
                    str += '...';
                }

                return str;
            };

            var html = '<ul class="social-bar-recs">';
            for (var i = 0; i < data.length; i++) {
                var t = data[i],
                    l,

                    user = t.twitter_user,
                    article = t.article_title,
                    category = t.category_title,

                    max_length = 80;

                if (user.length + article.length + category.length >= max_length) {
                    user = limit(user, 20);
                }
                if (user.length + article.length + category.length >= max_length) {
                    l = max_length - user.length - article.length;
                    category = limit(category, l > 20 ? l : 20);
                }
                if (user.length + article.length + category.length >= max_length) {
                    l = max_length - user.length - category.length;
                    article = limit(article, l);
                }

                html += '<li><a href="http://twitter.com/' + esc(t.twitter_user) + '" title="' + esc(t.twitter_user) + '" target="_blank">' + esc(user) +
                        '</a> ' + (isRTL ? '&#1610;&#1606;&#1589;&#1581; &#1576;&#1602;&#1585;&#1575;&#1569;&#1577;' : 'recommends') + ' <a href="' + t.article_url + '" title="' + esc(t.article_title) + '">' + esc(article) +
                        '</a> ' + (isRTL ? '&#1575;&#1604;&#1605;&#1606;&#1588;&#1608;&#1585; &#1601;&#1610;' : 'posted in') + ' <a href="' + t.category_url + '" title="' + esc(t.category_title) + '">' + esc(category) + '</a></li>';
            }
            html += '</ul>';
            $('.social-bar').prepend(html);

            var slider = $('.social-bar-recs').bxSlider({
                rtl: isRTL,
                mode: 'vertical',
                auto: true,
                pause: 10000
            });
            $('.social-bar .bx-wrapper').hoverIntent({
                over: function() {
                    slider.stopShow();
                },
                out: function() {
                    slider.startShow();
                }
            });
        });
    }


// Upcoming events widget
    var $eventsWidget = $('#upcoming-events');
    if ($eventsWidget.length) {
        var $eventsCountry = $('#upcoming-events-country'),
            $eventsIndustry = $('#upcoming-events-industry'),
            $eventsCount = $('#upcoming-events-text-link span'),
            $eventsCountLink = $('#upcoming-events-text-link'),
            $eventsCountNone = $('#upcoming-events-text-none'),
            eventsTimeOffset = 18000,   // 4 hour offset from UTC
            eventsList = [],            // List of all events
            eventsCountry = '',         // Currently selected Country
            eventsIndustry = '';        // Currently selected Industry

        var updateEventCount = function(year, month) {
            if (!year || !month) {
                var d = new Date();
                year = d.getFullYear();
                month = d.getMonth() + 1;
            }

            var daysInMonth = 32 - new Date(year, month - 1, 32).getDate(),
                start = new Date(0),
                end = new Date(0),
                eventsCount = 0,
                eventsListLength = eventsList.length;

            start.setUTCDate(1);
            start.setUTCMonth(month - 1);
            start.setUTCFullYear(year);

            end.setUTCDate(daysInMonth);
            end.setUTCMonth(month - 1);
            end.setUTCFullYear(year);

            var starttime = start.getTime() / 1000 - eventsTimeOffset,
                endtime = end.getTime() / 1000 - eventsTimeOffset;
            for (var i = 0; i < eventsListLength; i++) {
                if ((
                        (eventsList[i].start < starttime && eventsList[i].end > endtime) ||
                        (eventsList[i].start >= starttime && eventsList[i].start <= endtime) ||
                        (eventsList[i].end >= starttime && eventsList[i].end <= endtime)
                    ) &&
                    (eventsCountry.length === 0 || eventsList[i].country === eventsCountry) &&
                    (eventsIndustry.length === 0 || eventsList[i].industry === eventsIndustry)) {
                    eventsCount++;
                }
            }

            if (eventsCount > 0) {
                $eventsCount.text(eventsCount);
                $eventsCountLink.show();
                $eventsCountNone.hide();
            }
            else {
                $eventsCountLink.hide();
                $eventsCountNone.show();
            }

            var url = '/cgi-bin/events/widget.cgi?Date=' + month + '-' + year;
            if (eventsCountry.length) {
                url += ';Country=' + encodeURIComponent(eventsCountry);
            }
            if (eventsIndustry.length) {
                url += ';Industry=' + encodeURIComponent(eventsIndustry);
            }
            $eventsCountLink.attr('href', url);
        };

        var updateEvents = function() {
            eventsCountry = $eventsCountry.length ? $eventsCountry.find('option:selected').val() : '';
            eventsIndustry = $eventsIndustry.length ? $eventsIndustry.find('option:selected').val() : '';

            $eventsWidget.datepicker('refresh');
            updateEventCount();
        };

        $eventsWidget.datepicker({
            dateFormat: 'dd-mm-yy',
            beforeShowDay: function(date) {
                var events = [],
                    eventTitles = [],
                    eventsListLength = eventsList.length;

                // The calendar is in the user's local time, but we want to
                // always display things the same as the server timezone
                // (UTC+4/GMT-4).  We hack around this issue by changing the
                // user's local time into UTC time.
                var fake_date = new Date(0);
                fake_date.setUTCDate(date.getDate());
                fake_date.setUTCMonth(date.getMonth());
                fake_date.setUTCFullYear(date.getFullYear());

                var unixtime = fake_date.getTime() / 1000 - eventsTimeOffset;
                for (var i = 0; i < eventsListLength; i++) {
                    if (eventsList[i].start <= unixtime && eventsList[i].end >= unixtime &&
                        (eventsCountry.length === 0 || eventsList[i].country === eventsCountry) &&
                        (eventsIndustry.length === 0 || eventsList[i].industry === eventsIndustry)) {
                        eventTitles.push(eventsList[i].title);
                        events.push(eventsList[i]);
                    }
                }

                if (events.length) {
                    return [true, 'upcoming-events-tip', '<ul class=bullets><li>' + eventTitles.join("</li><li>") + '</li></ul>'];
                }
                else {
                    return [false, ''];
                }
            },
            onChangeMonthYear: function(year, month) {
                updateEventCount(year, month);
            },
            onSelect: function(dateText) {
                var url = '/cgi-bin/events/widget.cgi?Date=' + encodeURIComponent(dateText);
                if (eventsCountry.length) {
                    url += ';Country=' + encodeURIComponent(eventsCountry);
                }
                if (eventsIndustry.length) {
                    url += ';Industry=' + encodeURIComponent(eventsIndustry);
                }
                window.location = url;
            }
        });

        $eventsCountry.change(updateEvents);
        $eventsIndustry.change(updateEvents);

        $.getJSON('/static/json/events.json', function(data) {
            eventsList = data;
            updateEvents();
            updateEventCount();
        });

        // A bit of a hack to get tipTip to re-setup
        $eventsWidget.mouseover(function() {
            // When the month changes, .ui-datepicker-calendar gets re-created
            // by the datepicker code.
            var $dp = $eventsWidget.find('.ui-datepicker-calendar');
            if (!$dp.data('tipped')) {
                $dp.data('tipped', true);
                $eventsWidget.find('.upcoming-events-tip').tipTip();
            }
        });
    }


// News country filter
    $('.country-filter').change(function() {
        var $select = $(this);
        if ($select.val().length) {
            location.href = $select.val();
        }
    }).val('');


// Article Extra Toggle
    $('.article-toggle').click(function() {
        var $link = $(this),
            $content = $($link.attr('href'));

        $content.slideToggle();

        return false;
    });


// Article gallery lightbox 
    $('.article-image a').click(function() {
        var $link = $(this);

        $.modal('<iframe src="'+ $link.attr('href') + '" width="1060" height="620" frameborder="0" scrolling="no" allowtransparency="true"></iframe>', {
            opacity: 90,
            zIndex: 10000000
        });

        return false;
    });


// Article lightbox
    $('.gallery-previews a').click(function() {
        var $a = $(this),
            image = $a.attr('data-image'),
            $prev = $('.gallery-images li:visible'),
            $next = $(image);

        if ($prev.attr('id') !== $next.attr('id')) {
            $prev.hide();
            $next.fadeIn();
        }

        return false;
    });

// Article floating social media box
    var $social_bar_horiz = $('.article-social-bar'),
        $social_bar = $('.article-social-bar-floating');
    if ($social_bar.length) {
        // Want to use $social_bar.offset().top, but it being absolute
        // positioned, it doesn't always start off at the original position at
        // the top of the page.  Cheat by using the position of the other
        // social bar, which should be in the same position.
        var pos = $social_bar_horiz.offset().top,
            $outer_wrapper = $('.outer-wrapper'),
            $window = $(window);

        var scrollHandler = function() {
            if ($window.scrollTop() > pos) {
                $social_bar.css({ position: 'fixed', top: '15px' });
            }
            else {
                $social_bar.css({ position: 'absolute', top: 'auto' });
            }
        };

        var checkWidth = function() {
            // .wrapper width + .article-social-bar-floating offset width * 2
            if ($outer_wrapper.width() >= 1060 + 99 * 2) {
                // slideUp/Down triggers a bug in IE7/8
                if ($.browser.msie && $.browser.version < 9) {
                    $social_bar_horiz.hide();
                }
                else {
                    $social_bar_horiz.slideUp();
                }
                $social_bar.show();
                if (!pos) {
                    pos = $social_bar.offset().top;
                }
                scrollHandler();
                $window.bind('scroll', scrollHandler);
            }
            else {
                if ($.browser.msie && $.browser.version < 9) {
                    $social_bar_horiz.show();
                }
                else {
                    $social_bar_horiz.slideDown();
                }
                $social_bar.hide();
                $window.unbind('scroll', scrollHandler);
            }
        };

        checkWidth();
        $window.resize(checkWidth);
    }
});

function wp_validate() {
    var phone = $('#prof_phone').val();
    if (!phone) {
        alert('You are required to enter your phone number before you can download this paper.');
        return false;
    }
    else if (phone !== 'exists' && !phone.match(/^\+\d{11,14}$/)) {
        alert('Please enter your phone number in international format with no spaces or hyphens or brackets.');
        return false;
    }
    if ($('#agree:checked').length === 0) {
        alert('You are required to accept the terms and conditions before you can download this paper.');
        return false;
    }
    return true;
}

