var QUICK_SEARCH_TIMER = null;
var MENU_TIMER = null;
// define a cache for the profile tips:
var PROFILE_CACHE = new Object;
var PROFILE_TIP_TIMER = null;

function partition(sep) {
    /* S.partition(sep) -> [head, sep, tail]

    Searches for the separator sep in S, and returns the part before it,
    the separator itself, and the part after it.  If the separator is not
    found, returns S and two empty strings.
    */
    var split_index = this.indexOf(sep);
    if (split_index == -1) {
        return new Array(this, '', '');
    }
    return new Array(this.substr(0, split_index),
                     sep,
                     this.substr(split_index + sep.length));
}

String.prototype.partition = partition;

function restyle_file_uploads()
{
	//swap values for input type="file" for restyled solution:
    $(':input:file').each(function() {
        $(this).addClass("originalUpload").wrap('<span class="fileUpload_wrap"></span>')
        .after('<input class="uploadReplacement" type="text" /><span class="uploadButton">Browse</span>');
    });

    $('div.fileUpload span.fileUpload_wrap input.originalUpload').change(function(){
		$(this).siblings('input.uploadReplacement').val($(this).val());
    });
    
}


switch_tab_timeout = null;
leave_tabs_timeout = null;
$(document).ready(function() {	

    //make parent tabs stay highlighted when hovering over children in content navigation
    startup = function()
    {
        $('div.memberSearchBox form input.memberSearchGo').hide();

        restyle_file_uploads();
        
        var $tabs = $('.contentsHead>ul>li');
        
        $tabs.mousemove(function(){
            var $menuItem = $(this);
            
            clearTimeout(leave_tabs_timeout);
            leave_tabs_timeout=null;
            
            function switch_tab()
            {            
                var $menuLevel = $menuItem.children('ul.secondLevel');
    
                $menuLevel.hide();
                $menuItem.siblings('.active').removeClass('unfocused');
                $menuItem.children('a').removeClass('active');
                $menuItem.parent().children('.active').children('ul.secondLevel').show();
    
                $menuItem.siblings().children('ul.secondLevel').hide();
                $menuItem.siblings().children('a').removeClass('active');
                $menuItem.siblings('.active').addClass('unfocused');
                $menuItem.removeClass('unfocused');
                
                $menuItem.children('ul.secondLevel').show();
                $menuItem.children('a').addClass('active');
            }
            
            if (switch_tab_timeout!==null) {
                clearTimeout(switch_tab_timeout);
                switch_tab_timeout=null;
            }
            switch_tab_timeout = setTimeout(switch_tab, 200);
            
        });
        
        $tabs.mouseout(function(){
            
            var $this = $(this);
            var $menu = $('.contentsHead>ul');        
            
            leave_tabs_timeout = setTimeout(function(){
                           
                clearTimeout(switch_tab_timeout);
                switch_tab_timeout=null;
                
                $tabs.removeClass('unfocused');
                $tabs.children('a').removeClass('active');
                
                $menu.find('ul.secondLevel').hide();
                $menu.children('li.active:first').children('ul.secondLevel').show();
    
            }, 200);    
        });
        
        // handle network news collapses clicks
        $('span.foldDay').click(function() {
            $(this).toggleClass('down').toggleClass('up')
                   .parent().toggleClass('folded')
                   .find('ul.dayNews').slideToggle();
        });
    
        // handle the search dropdown:
        $('#quickSearch').focus(function() {
            $('div.searchDropDown').show();//slideDown('fast');
        }).blur(function() {
            QUICK_SEARCH_TIMER = window.setTimeout(closeQuickSearchDropDown, 500);
        });
    
        $('div.searchDropDown :input').click(function() {
            window.clearTimeout(QUICK_SEARCH_TIMER);
        });
        	

        
        // style the my networks form more nicely:
        $('#myNetworksForm').hide();
        var $myNetworksSelect = $('#myNetworksStyledSelect');
        var $myNetworksDropDown = $('#myNetworksDropDown');
        $myNetworksDropDown.hide();
        $myNetworksSelect.show().children('span,a').click(function(e) {
            e.stopPropagation();
            $myNetworksDropDown.slideToggle('fast');
            return null;
        });
        //make sure clicking on the document closes the dropdown
        $(document).click(function(){
            $($myNetworksDropDown).slideUp('fast');
        });
        
        // show the dismiss button on the message box if it exists:
        var $dismissButton = $('.platformFeedback .dismissBtn');
        if ($dismissButton.length) {
            $dismissButton.show().one('click', function(e) {
                e.preventDefault();
                $platformFeedback = $('.platformFeedback')
                $platformFeedback.fadeOut('slow', function() {
                    $platformFeedback.remove();
                });
            });
        }
        
        // setup profile tips
        initProfileTips();
        
        // bind tooltips to all links, images and buttons
        $('a, img, button, rd, acronym, input, .contentNewIndicator span').tooltip({showURL: false});
        
        $('#subscriptionWarningMask').css({height: $(document).height()});
        $('div.warningBox a.dismissWarning').click(function(event) {
            event.preventDefault();
            $.getJSON('/my-account/dismiss-message/',null, clearWarning);
        });
        
        // setup subscription graphics:
        $('.sub-graphic').hover(function(){
            $(this).css({paddingTop: '2px',
                         paddingBottom: '6px'});
        }, function(){
            $(this).css({paddingTop: '6px',
                         paddingBottom: '2px'});

        }).tooltip({showURL: false, track: true });
    }
    //startup();
    if (running_ie6) {
        setTimeout(startup, 10);   
    } else {
        startup();
    }
});

function clearWarning(data) {
    $('#subscriptionWarningMask, div.warningBox').fadeOut('fast', function() {
        $(this).remove();
    });
}

function showTip(data, $over) {
    /* postition and set up the profile tip */
    
    var $profileTip = $('#memberTooltip');
        
    var $profileName = $profileTip.find('span.profileName');
    var $profilePosition = $profileTip.find('span.profilePosition');
    var $profileCompany = $profileTip.find('span.profileCompany');
    var $profileImage = $profileTip.find('img.profile');
    
    $profileTip.hide();
    
    $profileName.text(data.first_name + ' ' + data.last_name);
    $profilePosition.text(data.role);
    
    if (data.username != 'deleteduser') {
        $profileCompany.text(data.company);
    }
    else {
        $profileCompany.text('');
    }
    
    if (data.photo === null) {
        $profileImage.hide();
    }
    else {
        $profileImage.attr({'src': data.photo,
                            'alt': data.first_name + " " + data.last_name
                           }).show();
    }
    
    if ($.browser.msie) {
        // make sure the height is correct:
        $profileTip.children('iframe').height($profileTip.height());
    }
    
    // position the box:
    positionProfileTip($over);
    
    // set the timer going to hide the tip:
    PROFILE_TIP_TIMER = window.setTimeout(hideTip, 2000);
}
function hideTip() {
    // kill hide timer:
    window.clearTimeout(PROFILE_TIP_TIMER);
    $('#memberTooltip').hide();
}
function positionProfileTip($over, username) {
    /* position the profile tip taking into account where there mouse is with
    /* respect to the edges of the screen */
    var overOffset = $over.offset();
    var current_x = overOffset.left;
    var current_y = overOffset.top;
    
    var $profileTip = $('#profile-tip-'+username);
    
    var $contents = $('#contents');
    var $pointer = $profileTip.find('span.pointer');
    
    var contentsOffset = $contents.offset();
    var contentsLeft = contentsOffset.left;
    var contentsRight = contentsLeft + $contents.width();
    
    var profileTipHeight = 81;
    var profileTipWidth = 310;
    
    if ((current_x + profileTipWidth) > contentsRight) {
        // the mouse is too near the right hand edge to display left ranged
        var newLeft = current_x - profileTipWidth + 94;
        $pointer.css({'left': profileTipWidth - 67 + "px"});
    }
    else {
        // the mouse is far enough away from the right edge to display left ranged
        var newLeft = current_x - 52;
        $pointer.css({'left': "52px"});
    }
    
    $profileTip.css({'left':newLeft + 'px', 'top':current_y-profileTipHeight-5 + 'px'});
    
    
    //position tooltip vertically to avoid place off bottom or top of screen
    if( ($(window).scrollTop() + profileTipHeight) > current_y ) {
		$profileTip.find('.contents .downArrow').hide();
		$profileTip.find('.contents .upArrow').show();
		$profileTip.css({marginTop: '115px'});
    } else {
		$profileTip.find('.contents .downArrow').show();
		$profileTip.find('.contents .upArrow').hide();
		$profileTip.css({marginTop: '0'});
    }
    
}

function initProfileTips() {
    /* set up all profile tips for this page */
    $('#memberTooltips').remove();
    $(document.body).append($('<div id="memberTooltips"></div>'));
    var $tooltips = $('#memberTooltips');
    
    DOWNLOADED_PROFILES = {};
    var $defaultTooltip = $('.defaultMemberTooltip').clone();
    $defaultTooltip.removeClass('.defaultMemberTooltip');
    
    
    $('.tip').each(function(i, tip_link){

        var $tip_link = $(tip_link);
        var username = $tip_link.find('input[name=username]').val();        
        
        
        if (DOWNLOADED_PROFILES[username] === undefined)
        {
            DOWNLOADED_PROFILES[username] = false;
            $defaultTooltip.attr('id', 'profile-tip-'+username);            
            $tooltips.append($defaultTooltip.clone());
            
            var $tip = $tooltips.find('#profile-tip-'+username);
            
            $tip.removeClass('.defaultMemberTooltip');
            $tip.addClass('memberTooltip');
        } else {
            var $tip = $tooltips.find('#profile-tip-'+username);            
        }
        
                
        $tip_link.hover(function(){
            
            $('.memberTooltip').hide();
            positionProfileTip($tip_link, username);
            if (!DOWNLOADED_PROFILES[username])
            {
                DOWNLOADED_PROFILES[username] = true;
                $.get('/profiles/'+username+'/mini/', function(html){
                    $tip.html(html);                    
                    positionProfileTip($tip_link, username);
                });
            }
            $tip.show();
            
        }, function(){
            $tip.hide();
        });
		
		return true;
    });
    
}

function closeQuickSearchDropDown() {
    QUICK_SEARCH_TIMER = null;
    $('div.searchDropDown').slideUp('fast');
}


/*  requires jQuery 1.3.2+
 *  Tidies up the help text and error message on forms which have the addHelper
 *  class.
 *
 *  Any help text or error message will appear on focus and disappear on blur
 *  Error messages take priority over help text i.e. help text will not be
 *  displayed for that field when there is an error
 */

$(document).ready(function() {

    // hide all help text and error messages:
    $('form.addHandler ul.errorlist, form.addHandler span.helpText').hide();
    
    // Re-show errors regarding file input
    $('ul.errorlist').each(function(i, el){
        if($(this).parent().parent().find('input[type=file]').length) {
            $(this).show();        
        }
    });    

    // set up field handlers:
    $('form.addHandler :input').focus(handleFieldFocus).blur(handleFieldBlur);

    setUpHelpers();
    
    on_scroll_timeout = null;
    on_scroll = function() {
        if (on_scroll_timeout!==null) {
            clearTimeout(on_scroll_timeout);
        }
        on_scroll_timeout = setTimeout(positionFloatingHelpers, 100);
    }

    $(window).scroll(on_scroll).resize(on_scroll);
});

function setUpHelpers() {
    /* For each field that contains help text, a help text div will be created
     * and initially hidden. The focus and blur events will trigger the display
     * of these.
     * For each field that has an error, an error message div will be created
     * and initially hidden. The focus and blur events will trigger the display
     * of these.
     * Error messages have priority over help text.
     * In addition, replace the default error message warning to make more sense
     * in the JS defined context.
     */
    do_helpers = function()
    {
        $('form.addHandler div.topLevelError p:last').html('Please click in the <span>red highlighted fields</span> for hints.')
    
        $('form.addHandler :input[type!=file]').each(function() {
            var $this = $(this);
            var fieldName = $this.attr('name').replace(/_0$/, '');
    
            // get the error and help text associated with this input:
            var errorMsgs = $('#error_'+fieldName);
            var helpText = $('#help_'+fieldName);            
			
            if (errorMsgs.length > 0) {
                $('body').append('<div class="floatingErrorMessage" id="floaterror_'+fieldName+'"><div class="content">'+errorMsgs.text()+'</div><div class="bottom">&nbsp;</div></div>');
            }
            if (helpText.length > 0) {
                $('body').append('<div class="floatingHelpText" id="floathelp_'+fieldName+'"><div class="content">'+helpText.html()+'</div><div class="bottom">&nbsp;</div></div>');
            }
            return true;
        });
    
        // hide all help text and position correctly:
        $('div.floatingHelpText, div.floatingErrorMessage').hide();
        positionFloatingHelpers();
		
		// call any code that needs to be run after this set (if available):
		try {
			postHelperSetup();
		}
		catch(e) {
			// pass
		}
    }
	
    if (running_ie6) {        
        setTimeout(do_helpers, 20);
    } else {
        do_helpers();
    }
    
}

function positionFloatingHelpers() {
    /* postiions all the helpers correctly. depending on whether the wrapper is
     * positioned relatively or otherwise we need two sets of calculations
     */

    // get the offset of the form for measurement purposes:
    $('div.floatingHelpText, div.floatingErrorMessage').each(function() {
        // get the name of the related form element:
        var $this = $(this);
		
        try {
			var origField = $('#id_' + $this.attr('id').partition('_')[2]);
			
			// test to see whether we need to consider a tinyMCE version
			// replacement of this field instead:
			$tinyMCEField = $('#'+origField.attr('id')+'_parent');
			if ($tinyMCEField.length > 0) {
				// we've got a replacement so use this instead
				var origField = $tinyMCEField;
				
			}
			
			if (origField.length == 0) {
				// if the original field cannot be located, try to suffix _0 to
				// handle the case of multi-widgets
				origField = $('#id_' + $this.attr('id').partition('_')[2] + '_0');
			}
			
			var origFieldOffset = origField.offset();
			
			$this.css({'top': Math.floor(origFieldOffset.top - 15) + 'px',
					   'left': Math.floor(origFieldOffset.left + origField.width() + 10) + 'px'
			});
		}
		catch (e) {
			return true;
		}
		return true;
    });
}

function handleFieldFocus(e, $override_field) {
    /* when a field receives focus, display the help text or error text
     * depending on the rules set out above
     */

	if ($override_field !== undefined) {
		var $field = $override_field;
	}
	else {
		var $field = $(this);
	}
	
	var fieldName = $field.attr('name').replace(/_\d+$/, '');
	var $tinyMCEField = $("#"+$field.attr('id')+'_ifr');
	
	if ($tinyMCEField.length > 0) {
		// simulate a blur from this field when the document is clicked:
		$(document).one('click', function() {
			$field.blur();
		});
	}

    //IE6, IE7 and IE8 don't like fading transparent pixels, let's hope IE9 does!
    if ($.browser.msie && $.browser.version.substr(0,1)<9){
        if ($('#floaterror_'+fieldName).length > 0) {
            $('#floaterror_'+fieldName).show().css({'margin-left':'0px'});
        }
        else {
            $('#floathelp_'+fieldName).show().css({'margin-left':'0px'});
        }
    //Proper browsers can have their fade and eat it too
    }else{
        if ($('#floaterror_'+fieldName).length > 0) {
            $('#floaterror_'+fieldName).fadeIn();
        }
        else {
            $('#floathelp_'+fieldName).fadeIn();
        }
    }
}
function handleFieldBlur(e) {
    /* when a field loses focus, hide the help text or error text */

    var fieldName = $(this).attr('name').replace(/_\d+$/, '');

    if ($.browser.msie && $.browser.version.substr(0,1)<9){
        if ($('#floaterror_'+fieldName).length > 0) {
            $('#floaterror_'+fieldName).hide().css({'margin-left':'-10000px'});
        }
        else {
            $('#floathelp_'+fieldName).hide().css({'margin-left':'-10000px'});
        }
    }else{
        if ($('#floaterror_'+fieldName).length > 0) {
            $('#floaterror_'+fieldName).fadeOut();
        }
        else {
            $('#floathelp_'+fieldName).fadeOut();
        }
    }
}

$(function(){
   
    setTimeout(function(){
    
        var $messageAlert = $('#messageCount.messageAlert:first');
        if ($messageAlert.length) {
        
            var $flash = $messageAlert.find('img,span.number');
            var flashCount = 5;
            var flashTimer = setInterval(function(){
                $flash.fadeOut('fast', function(){ $flash.fadeIn('fast'); });
                if (!--flashCount) {
                    clearInterval(flashTimer);
                }                
            }, 750);
        }    
    }, 100);
    
});
