if ( $.browser.msie ){
    document.execCommand("BackgroundImageCache", false, true);
}

/**
 * Add CSRF token to every AJAX request as the X-CSRFToken header
 */
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        var request_uses_safe_method = $.inArray(
            settings.type.toUpperCase(), ["HEAD", "GET", "OPTIONS", "TRACE"]);
        if (request_uses_safe_method !== -1) {
            return;
        }
        
        var host = document.location.host;   // host + port
        var protocol = document.location.protocol;
        var scheme_relative_origin = '//' + host;
        var origin = protocol + scheme_relative_origin;
        var url = settings.url;
        
        var is_same_origin = (
            // Same page
            url === origin ||
            url === scheme_relative_origin ||
            // Allowed absolute URL
            startswith(url, origin + '/') ||
            // Allowed scheme relative URL
            startswith(url, scheme_relative_origin + '/') ||
            // Relative URL
            !(/^(\/\/|http:|https:)/i.test(url))
            );
        if (is_same_origin) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});


startswith = function (str, prefix) {
    return str.substr(0, prefix.length) === prefix;
};

var restyle_file_uploads = function () {
    if(!is_running_ie6()){
        $(':input:file').not('.original_upload').each(function() {
            var $file_input = $(this);
            var $replacement = $('<input/>', {'class': 'replacement', disabled: 'disabled'});
            var $button = $('<span/>', {'class': 'upload_button', text: 'Browse'});
            
                $file_input.addClass('original_upload').wrap('<span class="file_upload_wrap"></span>');
                $file_input.after($replacement, $button);

                $(document).on('change', $file_input, function () {
                    $replacement.val($file_input.val());
                });
        });
    }
};

/**
 * Setup bindings for premium resources
 */
var setup_premium_resources_bindings = function () {
    if (IS_AUTHENTICATED) {
        $('.intercept_premium_resource').each(function() {
            var $link = $(this);
            
            // Bind intercept
            var content_type = $link.data('content-type');
            var $intercept_markup = $('#' + content_type + '-intercept');
            $link.modal_dialog({body : $intercept_markup, width: 500});
            
            // Record access to the premium resource
            $link.click(function (event_object) {
                $.get($link.data('record-access-url'));
            });
        });
    }
};


/**
 * Setup content intercepts.
 */
var setup_intercepts = function () {
    setup_premium_resources_bindings();
    
    if (IS_AUTHENTICATED) {
        $('a.intercept_approval_required_url')
            .css({opacity: 0.5})
            .modal_dialog({body: $('#approval_required_intercept'), width: 600});
        $('a.intercept_network_membership_required').modal_dialog({
            body: $('#network_membership_required_intercept'),
            width: 400
            });
    } else {
        $login_intercept = $('#popup_signup_or_login_form');
        $('a.intercept_login_required,a[href^="' + LOGIN_URL + '"]')
            .modal_dialog({
                body: $login_intercept,
                width: 674
            })
            .click(function(event_object) {
                var href_qs = $.deparam.querystring($(this).attr('href'));
                $login_intercept
                    .find('input[name="next"]')
                    .attr('value', href_qs.next);
            });
    }
}


$(function () {
    $("#forgot_password").parent('li').prev('li').css({marginBottom:0});
    if(is_running_ie6()){
        $(document).on('click', 'button', function () {
           $('button').not($(this)).attr("disabled","disabled");
            setTimeout(function () {
                $('button').removeAttr('disabled');
            }, 300);
        });

    }

    // disable forms from being submitted twice in quick succession
    $(document).on('submit', 'form', function(e){
        $form = $(this);
        var submitted = $form.data('submitted');
        if(!submitted){
            $form.data('submitted', true);
            $form.addClass("submitted");
            setTimeout(function(){
                $form.removeData('submitted');
                $form.removeClass("submitted");
            },5000);
            return true;
        }else{
            return false;
        }
    });

    $("#news_ticker").show(); // show the newsticker for ie6 users with js enabled

    /* Add Javascript functionality to the quick search box */
    var $search_dropdown = $('fieldset#search_scope_dropdown');
    var $search_input = $('#search_input');
    var search_scope_closing_timer = null;
    var close_search_scope_dropdown = function () {
        $search_dropdown.fadeOut('fast');
    };
    
    $search_input.focus(function () {
        clearTimeout(search_scope_closing_timer);
        $search_dropdown.fadeIn('fast');
    })
    .blur(function () {
        search_scope_closing_timer = setTimeout(close_search_scope_dropdown, 150);
    });
    $search_dropdown.click(function () {
        setTimeout(function () {
            $search_input.focus();
        }, 13);
    });
    
    // Ensure that the top-level login form clears the initial value on 
    // focus and restores it on blur if no changes have been made
    $('#header_login input').each(function () {
        var $field = $(this);
        $field.data('initial', $field.val())
            .focus(function () {
                if($field.val() === $field.data('initial')) {
                    $field.val('');
                }
            })
            .blur(function () {
                if (!$field.val()) {
                    $field.val($field.data('initial'));
                }
            });
    });
    var $header_login_form = $('#header_login'); 
    $header_login_form.on('submit', function (event_object) {
        var $form = $(this);
        var has_empty_input = false;
        $('#header_login_email, #header_login_password').each(function () {
            if (!$(this).val()) {
                has_empty_input = true;
                return false;
            }
        });
        
        if (has_empty_input) {
            event_object.preventDefault();
            $(this).qtip({
                position: {
                    my: 'center right',
                    at: 'center left',
                    adjust: {
                        y: 1
                    }
                },
                content: {
                    text: 'Please fill in both fields'
                },
                style: {
                    classes: 'ui-tooltip-red'
                },
                show: {
                    ready: true
                },
                hide: {
                    event: false
                }
            })
        }
    }).on('keydown', ':input', function () {
        $header_login_form.qtip('destroy');
    });
    
    $("a#footer_feedback").modal_dialog({
        width: 450,
        on_ajax_load: make_ajax_form
    });
    $(".tell_a_colleague_link").modal_dialog({
        width: 400,
        on_ajax_load: make_ajax_form
    });
    $('.contactEmailPopup').modal_dialog({
        width: 500,
        on_ajax_load: make_ajax_form
    });
    
    // Detect hover intent on the navigation menus
    $('.nav_dropdown').hide();
    var MENU_TIMEOUT = 250;
    var setup_closetimer = function ($menu_item, closing_timeout) {
        $menu_item.data('closetimer', setTimeout(function () {
            $menu_item.siblings('.nav_dropdown').hide();
            $menu_item.removeData('closetimer');
            $menu_item.parent().removeClass('hovering');
         }, closing_timeout || MENU_TIMEOUT));
    };
    
    $('nav>ul>li>a').hover(function () {
        var $menu_item = $(this);
        var $menu_parent = $menu_item.parent();
        setup_closetimer($menu_parent.siblings().children('a'), 1);
        var closetimer = $menu_item.data('closetimer');
        if (closetimer) {
            clearTimeout(closetimer);
        } else {
            $menu_item.siblings('.nav_dropdown').css({display: 'block'});
        }
        $menu_parent.addClass('hovering');
    }, function () {
        setup_closetimer($(this));
    }).click(function (evt) {
        if (is_mobile_device()) {
            $menu_item = $(this);
            if (!$menu_item.hasClass('hovering') && $menu_item.siblings('.nav_dropdown').length) {
                evt.preventDefault();
                $menu_item.addClass('hovering').trigger('mouseenter');
            }
        }
    });

    $('.nav_dropdown').hover(function () {
        var $dropdown = $(this);
        clearTimeout($dropdown.siblings('a').data('closetimer'));
        $dropdown.parent().addClass('hovering'); // make the parent tab look
                                                    // active
    }, function () {
        setup_closetimer($(this).siblings('a'));
    });
    
    setup_intercepts();
    
    // Add tooltips to profiles:
    if(!is_running_ie6()){
        $('.profile_link').qtip({
            content: {
                text: function () {
                    var $profile_link = $(this);
                    return '<img src="' + $profile_link.data('photo') + '" width="20" height="20" />'
                        +'<h6>' + $profile_link.text() + '</h6>'
                        +'<p class="job">' + $profile_link.data('job') + '</p>'
                        +'<p class="company">' + $profile_link.data('company')+ '</p>';
                }
            },
            position : {
                my: 'bottom left',
                at: 'top right',
                viewport: $(window)
            },
            style: {
                classes: 'ui-tooltip-profile ui-tooltip-rounded ui-tooltip-shadow'
            }
        });
    }
    // Ensure that the groups dropdown is grouped into columns when there are
    // many groups for ease of use
    var $groups_menu = $('#my-working-groups');
    var $group_items_wrapper = $groups_menu.children('ul');
    var $group_items = $group_items_wrapper.children('li');
    var $gi_length = $group_items.length;
    var MENU_WRAP_CUTOFF = (($gi_length/10)<1.5?$gi_length:parseInt($gi_length/4)+1);
    var $current_group = null;
    var new_group_count = 0;
    // Only do wrapping if there are more than 10 items
    if ($gi_length > MENU_WRAP_CUTOFF) {
        $group_items.each(function (index, item) {
            // Create a new group to hold the menu items:
            if (index % MENU_WRAP_CUTOFF === 0) {
                $current_group = $('<ul class="new_groups_col"/>').appendTo($groups_menu);
                new_group_count += 1;
            }
            $(item).detach().appendTo($current_group);
        });
        
        // Hide the original group
        $group_items_wrapper.remove();
        
        // Set the width on the parent
        //$groups_menu.children('a.menu_title').width($current_group.outerWidth() * new_group_count);
        

        if (new_group_count > 3) {
            var $menuitem1width = $('.global_navigation .menu_item:eq(0)').width();
            $groups_menu.parent().css('left', -$menuitem1width);
        }
        if(!is_running_ie6()){
            $groups_menu.find('.new_groups_col').css({'min-height':(30*(parseInt($gi_length/4)+1))});
        }
    }
    var col_width = 231;
    if(new_group_count>1) col_width = col_width*new_group_count;
    $groups_menu.parent().css({'width':col_width});
    $groups_menu.find('.new_groups_col:last').css({'border-right':0,'margin-right':0});


    // Add a tooltip the to my profile link
    if(!is_running_ie6()){
        $('#top_nav').find('[data-tooltip]').qtip({
            content: {
                attr: 'data-tooltip'
            },
            position : {
                my: 'top center',
                at: 'bottom center',
                viewport: $(window),
                adjust: {
                    y: 5
                }
            },
            style: {
                classes: 'ui-tooltip-dark ui-tooltip-rounded ui-tooltip-shadow'
            }
        });
    }
    
    if(!is_running_ie_older_than_9()) {
        $('select.use-styled-select').selectmenu({
            style: 'dropdown', 
            menuWidth: 280, 
            width: 280, 
            maxHeight: 200
        });
    }
    // Ensure that all file inputs are restyled
    setInterval(restyle_file_uploads, 500);

    // Noticiation messages
    var $notification_messages = $('ul.messages');
    $notification_messages.on('click', '.close', function (event_object) {
        event_object.preventDefault();
        var $parent_li = $(this).parent(); 
        if ($parent_li.siblings().length === 0) {
            $notification_messages.remove();
        } else {
            $parent_li.remove();
        }
    });
});


// ***************************************************************************
// Utility functions for array handling
// ****************************************************************************

function contains(value) {
    /*
     * A.contains(value) -> bool
     * 
     * Return true if value is found in A, false otherwise.
     */
    for (var i=0; i<this.length; i++) {
        if (this[i] == value) {
            return true;
        }
    }
    return false;
}
Array.prototype.contains = contains;

// ***************************************************************************
// Utility function for string handling
// ****************************************************************************

function join(array) {
    /*
     * S.join(array) -> string
     * 
     * Return a string which is the concatenation of the strings in the array.
     * The separator between elements is S.
     */
    if (typeof(array) !== typeof([])) {
        throw 'array must be iterable';
    }
    if (!array.length) return '';
    var joined = array[0];
    if (array.length==1) return joined;
    for (var item=1; item<array.length; item++) {
        joined += this + array[item];
    }
    return joined;
}


/**
 * S.strip([chars]) -> string
 * 
 * Return a copy of the string S with leading and trailing whitespace removed.
 * If chars is given and not None, remove characters in chars instead.
 */
function strip(chars) {
    if (chars === undefined) {
        return this.replace(/^\s+/,'').replace(/\s+$/,'');
    }
    var new_this = this;
    if (new_this.startswith(chars)) {
        new_this = new_this.substr(chars.length);
    }
    if (new_this.endswith(chars)) {
        new_this = new_this.substr(0, new_this.length - chars.length);
    }
    return new_this;
}

var string_format = function (data) {
    var template = this.toString();
    var rendered_template = template.replace(/{{\s*(.*?)\s*}}/g, function(m, n) {
        var node = data;
        $.each(n.split('.'), function (i, symbol){
            node = node[symbol] || '';
        });
        return node;

    });

    return rendered_template;
};
String.prototype.strip = strip;
String.prototype.join = join;
String.prototype.f = string_format; 


// ****************************************************************************
// Utility functions for the user agent handling
// ****************************************************************************

/**
 * Determine whether the current device is a mobile device
 */
var is_mobile_device = function () {
    var tests = ["iPhone", "iPad", "iPod"],
        _is_mobile_device = false;
    
    // If this value has previously been calculated in this session use this
    // rather than re-calculate it, otherwise work it out
    if (typeof this.cached === 'undefined') {
        $.each(tests, function (index, test) {
            if (navigator.platform.indexOf(test) !== -1) {
                _is_mobile_device = true;
                return false;
            }
        });
        this.cached = _is_mobile_device;
    }
    
    return this.cached;
};


/**
 * Determine whether the current browser is Internet Explorer 6
 */
var is_running_ie6 = function () {
    return $.browser.msie && parseInt($.browser.version.substr(0, 1)) < 7;
};
var is_running_ie8 = function () {
    return $.browser.msie && parseInt($.browser.version.substr(0, 1)) === 8;
};
var is_running_ie_older_than_9 = function () {
    return $.browser.msie && parseInt($.browser.version.substr(0, 1)) < 9;
};


/**
 * Display a message as a page-level notification.
 * 
 * @param level Type of message. One of 'debug', 'success', 'info', 'error', or
 *        'warning'.
 * @param message The message to display.
 */
var show_notification = function (level, message, clear_others) {
    if($.browser.msie && $.browser.version <= 6) {
        window.alert(message);
    } else {
        var $message = $('<li>', {'class': level});
        var $icon = $('<img>', {src: STATIC_IMAGES_URL + '/icons/notification/' + level + '.png'});
        var $close = $('<span>', {'class': 'close', text: 'X'})
            .click(function (e) {
                e.preventDefault();
                $message.fadeOut(200);
            });
        $message.append($icon, message, $close);
        
        var $messages = $('ul.messages');
        
        // In the case where the messages ul is not defined, add it to the DOM
        if (!$messages.length) {
            $messages = $('<ul/>', {'class': 'messages'}).prependTo($('body'));
        }
        
        if (clear_others) {
            $messages.children().remove();
        }
        $messages.append($message);
    }
};

