// Create function to create virtual local namespace and immediately run it.
(function(){
    // Init object
    var dvids =
    {
    };

    // Assign to global namespace
    window.dvids = dvids;
})();

dvids.auth = {
    events: {
        loginSuccess: 'loginSuccess',
        loginFailure: 'loginFailure',
        logout:       'logout',
        requestLogin: 'requestLogin',
        query       : 'query'
    },
    requestLogin: function() {
        $.event.trigger(dvids.auth.events.requestLogin);
    },
    login: function (email, password, rememberMe, callback) {
        $.post('/login', {'email': email, 'password': password, 'remember_me': rememberMe}, function(data, textStatus, xhr) {
            callback(data);

            if (data.errors || data.formErrors) {
                $.event.trigger(dvids.auth.events.loginFailure, data);
            } else {
                $.event.trigger(dvids.auth.events.loginSuccess, data);
            }

            return data;
        });
    },
    logout: function(callback) {
        $.get('/logout', {}, function(data, textStatus, xhr) {
            callback(data);

            $.event.trigger(dvids.auth.events.logout);
        });
    },
    getAuth: function() {
        $.getJSON('/auth/query', {}, function(data, textStatus, xhr) {
            $.event.trigger(dvids.auth.events.query, data);
        });
    }
}

$(function() {
    var carousel_for_videos = false;

    function slideSwitch(tab, rel) {
        var active = $('#' + tab + ' div.active');
        var next = $('#' + rel);
        if (next.attr('id') != active.attr('id')) {
            active.addClass('last-active');

            next.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, 1000, function() {
                    active.removeClass('active last-active');
                });
        }
    }

    function slideSwitchVideo(tab, rel) {
        var active = $('#' + tab + ' div.active');
        var next = $('#' + rel);

        if (next.attr('id') != active.attr('id')) {
            active.removeClass('active').hide(function() {
                next.addClass('active').show(function() {
                    // fix broken behavior in video-js
                    var elements = next.find('video');
                    var player = elements[0].player;
                    $(player.box).width('');
                    $(player.element).height('');
                    player.positionBox();
                });
            });
        }
    }

    $(".carousel_body").jcarousel({
        buttonNextHTML: '<a class="rightbtn"></a>',
        buttonPrevHTML: '<a class="leftbtn"></a>',
        scroll: 1,
        visible: 5,
        wrap: "circular"
    });

    $(".carousel_body ul li a").click(function(){
        slideSwitch('tab1', $(this).attr('rel'));
        return false;
    });

    $('#featuredimage a').click(function(){
        $('#featuredvideo a').removeClass('selected');
        $(this).addClass('selected');

        $('#tab1').fadeIn();
        $('#tab2').hide();

        return false;
    });

    $('#featuredvideo a').click(function(){
        $('#featuredimage a').removeClass('selected');
        $(this).addClass('selected');
        $('#tab2').fadeIn(function() {
            if (!carousel_for_videos) {
                carousel_for_videos = true;
                $(".carousel_body_video").jcarousel({
                    buttonNextHTML: '<a class="rightbtn_video"></a>',
                    buttonPrevHTML: '<a class="leftbtn_video"></a>',
                    scroll: 1,
                    visible: 5,
                    wrap: "circular"
                });

                VideoJS.setup(null);

                $(".carousel_body_video ul li a").click(function(event){
                    slideSwitchVideo('tab2', $(this).attr('rel'));
                    return false;
                });
            }
        });
        $('#tab1').hide();

        return false;
    });

    $('#newsfield').click(function() {
        $('#latestnews').removeClass('selected');
        $(this).addClass('selected');

        $('#tab3').show();
        $('#tab4').hide();

        return false;
    });

    $('#latestnews').click(function() {
        $('#newsfield').removeClass('selected');
        $(this).addClass('selected');

        $('#tab4').show();
        $('#tab3').hide();

        return false;
    });

    $('#login').click(function(){
        $('#login_container').fadeIn("medium");
        return false;
    });

    $('#login_links_cms').click(function(){
        $('#admintools_container').fadeIn("medium");
        return false;
    });

    $(document).bind(dvids.auth.events.requestLogin, function(){
        $('#login_container').fadeIn("medium");
        if($.browser.safari){ bodyelem = $("body") } else{ bodyelem = $("html,body") }
        $(bodyelem).animate({scrollTop:0}, 'slow');
    });

    $('#login_container input:text, #login_container input:password').focus(function() {
        $(this).addClass('focus');
    });

    $('#login_container input:text, #login_container input:password').blur(function() {
        $(this).removeClass('focus');
    });

    function showLinks(data) {
        $('#logged_in_user').html(data.name);
        $('#login_links').hide();
        $('#login_current').fadeIn('fast');
        if (data.groupId == 14 || data.groupId == 1) {
            $('#login_mydvids').fadeIn('fast');
        }
        if (data.groupId != 2 && data.groupId != 12 && data.groupId != 13) {
            $('#login_links_cms').fadeIn('fast');
        }
        if (data.groupId == 1 || data.groupId == 3 || data.groupId == 4 || data.groupId == 8 || data.groupId == 10 || data.groupId == 14) {
            $('#login_links_direct').fadeIn('fast');
        }
    }

    $('#login_container form').submit(function() {
        $('#login_container input').removeClass('formerror');
        $('#login_errors').html('');
        dvids.auth.login($('#login_email').val(), $('#login_password').val(), $('#login_remember_me').is(':checked'), function(data) {
            if (data.errors) {
                var msg = '';
                for (i=0; i < data.errors.length; i++) {
                    msg += '<li>' + data.errors[i] + '</li>';
                }
                $('#login_errors').html(msg).fadeIn('medium');
            } else if (data.formErrors) {
                var msg = '';
                for (field in data.formErrors) {
                    element = $('#login_' + field);
                    element.addClass('formerror');
                }
            } else {
                // user authenticated
                $('#login_container').fadeOut('fast');

                showLinks(data);

                // clean up
                $('#login_container input').removeClass('formerror');
                $('#login_errors').html('');

                $('#login_email').val('Your e-mail address');
                $('#login_password').val('');
            }
        });

        return false;
    });

    $('#closelogin').click(function(){
        $('#login_container').fadeOut("fast");
        $('#login_password').val('');
        $('#login_errors').remove();

        return false;
    });

    $('#closeadmintools').click(function(){
        $('#admintools_container').fadeOut("fast");
        return false;
    });

    $('#login_email').click(function() {
        if ($(this).val() == 'Your e-mail address') {
            $(this).val('');
        }
    });

    $('#logout').click(function() {
        dvids.auth.logout(function(data) {
            $('#login_current').hide();
            $('#login_links_cms').hide();
            $('#login_links_direct').hide();
            $('#admintools_container').hide();
            $('#login_mydvids').hide();
            $('#login_links').fadeIn();
        });
        return false;
    });

    $('#toplink > .right').hide();

    // populate auth cache
    dvids.auth.getAuth();

    $(document).bind(dvids.auth.events.query, function(event, data) {
        if (data.loggedIn === true) {
            showLinks(data);
        } else {
            $('#login_links').fadeIn();
        }
    });

    featuredcontentslider.init({
        id: "slider1",  //id of main slider DIV
        contentsource: ["inline", ""],  //Valid values: ["inline", ""] or ["ajax", "path_to_file"]
        toc: "#increment",  //Valid values: "#increment", "markup", ["label1", "label2", etc]
        nextprev: ["", ""],  //labels for "prev" and "next" links. Set to "" to hide.
        revealtype: "click", //Behavior of pagination links to reveal the slides: "click" or "mouseover"
        enablefade: [true, 0.1],  //[true/false, fadedegree]
        autorotate: [true, 5000],  //[true/false, pausetime]
        onChange: function(previndex, curindex){  //event handler fired whenever script changes slide
            //previndex holds index of last slide viewed b4 current (1=1st slide, 2nd=2nd etc)
            //curindex holds index of currently shown slide (1=1st slide, 2nd=2nd etc)
        }
    });

    if ($('#term').html() != null) {
        $('#searchfield').val($('#term').html());
    }

    var datePickerOptions = {
        dateFormat: 'yymmdd',
        maxDate: '+0d',
        minDate: new Date(1991, 4, 24),
        changeMonth: true,
        changeYear: true
    }

    $('#id_search_custom_date_start').datepicker(datePickerOptions);
    $('#id_search_custom_date_end').datepicker(datePickerOptions);

    $('#id_search_custom_date_go').click(function() {
        var qs = '';
        var baseUrl = $(this).attr('rel');
        var start = $('#id_search_custom_date_start').val();
        var end = $('#id_search_custom_date_end').val();

        if (start.length == 0 && end.length == 0) {
            $('#id_search_custom_date_start').addClass('error').focus();
            return;
        }

        if (start.length > 0) {
            qs += '&filter[date]=' + start;
        }

        if (end.length > 0) {
            qs += '-' + end;
        }

        window.location.href = baseUrl + qs;
    });

    $('#nff_by_unit').change(function(event) {
        if ($(this).val().length > 0) {
            window.location.href = '/units/' + encodeURIComponent($(this).val());
        }
    });

    $('#search_by_cocom').change(function(event) {
        if ($(this).val().length > 0) {
            window.location.href = '/cocom/' + encodeURIComponent($(this).val());
        }
    });

    $('#search_by_country').change(function(event) {
        if ($(this).val().length > 0) {
            window.location.href = '/search/country/' + encodeURIComponent($(this).val());
        }
    });

    $('#submitcocom').click(function(event) {
        event.preventDefault();
        if ($('#cocom').val().length > 0) {
            window.location.href = '/search/cocom/' + encodeURIComponent($('#cocom').val());
        }
    });

    $('#holiday_select').change(function(event) {
        if ($(this).val().length > 0) {
            window.location.href = '/holiday/' + encodeURIComponent($(this).val());
        }
    });

    var showEditLink = function(event, data){
        var tagPerms = [1, 4, 6, 8];  // permissions to edit tags
        if($.inArray(data.groupId, tagPerms) != -1) {
            $('#editTagLink').show();
        }
    };

    var admintoolsLoaded = false;
    var userId = '';

    $(document).bind(dvids.auth.events.query, function(event, data) {
        userId = data.id;
    });

    $(document).bind(dvids.auth.events.loginSuccess, function(event, data) {
        userId = data.id;
    });

    $('#login_links_cms a').click(function(event){
        event.preventDefault();
        if (! admintoolsLoaded) {
            $('#admintools_container').load('/ajax/admintools/' + userId);
            admintoolsLoaded = true;
        }
    });

    $(document).bind(dvids.auth.events.query, showEditLink);
    $(document).bind(dvids.auth.events.loginSuccess, showEditLink);
    $(document).bind(dvids.auth.events.logout, function(){
        $('#editTagLink').hide();
    });

    // search referral highlighting on asset detail pages
    if (document.referrer.length > 0) {
        var query = document.referrer.substring(document.referrer.lastIndexOf('?') + 1);
        var vars = query.split('&');

        var q = '';

        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=');
            if (pair[0] == 'q') {
                q = pair[1];
                break;
            }
        }

        if (q.length > 0) {
            q = q.replace(/\+/g, ' ');

            var words = q.split(' ');

            for (var i = 0; i < words.length; i++) {
                // title
                $('.innerheaders').highlight(words[i]);

                $('.imagedescription').highlight(words[i]);
                $('.videodescription').highlight(words[i]);

                // body text
                $('#newsbody').highlight(words[i]);

                $('#tags').highlight(words[i]);
            }
        }
    }

    /****DETECT IF BROWSER IS OBSOLETE****/
    if($.browser.msie){
        var version = $.browser.version.substr(0, $.browser.version.indexOf('.')); // get version number
        var cookie = $.cookie('ie6-obsolete-confirm');
        if(version <= 6 && cookie != 'true') {
            $('body').append('<div id="ie-message">Your browser is obsolete. Please click <a href="/about/faq#faq36" target="_new" style="text-decoration:underline;">here</a> to learn how to resolve this issue.  [<a id="ie6-obsolete-close" href="#" style="color: black;">Close</a>]</div>');
            $('#ie6-obsolete-close').click(function(event) {
                event.preventDefault();
                $('#ie-message').remove();
                $.cookie('ie6-obsolete-confirm', 'true');
            });
        }
    }

    /****GEO ALERT MESSAGE****/
    var checkGeoAlert = function(){
        var geo_alert_expire = 1;

        // only display geo alert modal if there is a message available and the cookie has not yet expired.
        if(!$.cookie('geo_alert')){
            $.cookie('geo_alert', 'true', {expires: geo_alert_expire});

            $.ajax({
                url: '/ajax/geoalert',
                success: function(data){
                    if(data.status == 'true'){
                        // assign header and body of modal
                        $('#geo_alert_header').html('Members in the ' + data.region_display + ' area!');
                        $('#geo_alert_body').html(data.message);

                        geoAlertModal = $.modal( // display modal
                            $('#geo_alert_container').html(), // html to be included
                            {closeHTML: ''}// no ext button
                        );
                    }
                }
            });
        }
    }
    $(document).bind(dvids.auth.events.loginSuccess, checkGeoAlert);
    /********/

    // init the country/state/city autocomplete - wrapped in function in the case (ie member options tab menu) that it needs
    // to be called again after content has been added to the page and after the document.ready() function is called in this file.
    initLocodeDropDown();

    /****Check for Redirects - based on member id****/
    dvids.redirectCheck = function(event, data){
        var url = '';
        switch(data.id){
            case 1005003: // survey member
                url = "http://admin.dvidshub.net/?script=members/members_survey.php&which=1";
                break;
            case 1000957: // training member
                url = "http://admin.dvidshub.net/?script=members/members_training.php";
                break;
            case 1026110: // norsat request member
                url = "http://admin.dvidshub.net/?script=members/members_norsatrequest.php";
                break;
        }

        if(url){
            $(location).attr('href',url);
        }
    }

    $(document).bind(dvids.auth.events.loginSuccess, dvids.redirectCheck);
    /**************************/
});

var geoAlertModal;
var currentState;
function initLocodeDropDown()
{
    /****[COUNTRY/SUBDIV: Dynamic Dropdown triggering the Subdiv]****/
    $('#country').change(function(event, currentSubdiv) {
        $.get('/ajax/statelist', {'country': $(this).val()},
        function(data) {
            $('#subdiv').empty();
            // using $.param to check to see if the data object contains any properties.  this function creates
            // a serialized representation of an array or object.  If no serialize representation exists, then we know it has no properties
            if($.param(data)){
                $.each(data, function(key, value) {
                    $('#subdiv').
                      append($("<option></option>").
                      attr("value",key).
                      text(value));
                });
            }else{
                $('#subdiv').
                    append($("<option></option>").
                    attr("value","").
                    text("- N/A -"));
            }

            // if a current subdiv is passed in, (possibly through jQuery's trigger function), then select that state
            // once the state select element is repopulated
            if(currentSubdiv) {
                $('#subdiv').selectOptions(currentSubdiv);
            }

        }, 'json');
    });

    /**************************************************************/

    $('#city').autocomplete({
        minLength: 2,
        source: function(request, response) {
            var params = {
                'city': request.term,
                'state': $('#subdiv').val(),
                'country': $('#country').val()
            }

            $.getJSON('/ajax/citylist', params, function(data, status, xhr) {
                response(data);
            });
        }
    });

    // triggering the change event on the country select box if a state has already been selected.  This is stored in a global variable
    // called currentState which is declared outside this on ready handler and set in the stateSelect() view helper.  Only trigger change event if a currentState is set
    if(currentState){
        $('#country').trigger('change', [currentState]);
    }
}

/****Initialize jCarousel for current webcast alert ****/
dvids.currentWebcastAlert = {}
dvids.currentWebcastAlert.carousel_initCallback = function(carousel){
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}

dvids.currentWebcastAlert.initCarousel = function(){
    $('#cw_carousel').jcarousel({
        vertical: true,
        auto: 2,
        scroll: 1,
        wrap: 'last',
        initCallback: dvids.currentWebcastAlert.carousel_initCallback
    });
}
/**************************************************/

/****Initialize jCarousel for front page alert ****/
dvids.frontPageAlert = {}
dvids.frontPageAlert.carousel_initCallback = function(carousel){
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}

dvids.frontPageAlert.initCarousel = function(){
    $('#fp_carousel').jcarousel({
        vertical: true,
        auto: 2,
        scroll: 1,
        wrap: 'last',
        initCallback: dvids.frontPageAlert.carousel_initCallback
    });
}
/**************************************************/

