// define a cache for the profile tips:
var PROFILE_CACHE = {};
var PROFILE_TIP_TIMER = null;
var INITIAL_WG_SELECTOR_VAL;
var FIELD_WIDTHS = {};

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;


switch_tab_timeout = null;
leave_tabs_timeout = null;
$(function () {

    var startup = function() {
        $('div.memberSearchBox form input.memberSearchGo').hide();

        restyle_file_uploads();
        
        // setup profile tips
        $('a.profile_link').live({
            mouseenter:
                function(){
                    
                    $profile_link = $(this);
                    
                    $profile_link.after('<div id="membertip"><p><strong>'
                        + $profile_link.html()
                        + '</strong></p><p id="job">'
                        + $profile_link.attr('data-job')
                        + '</p><p id="company">'
                        + $profile_link.attr('data-company')
                        + '</p></div>'
                        );

                    if( $(window).scrollTop() > $profile_link.offset().top - 75 ){
                        $('div#membertip').addClass('below');
                    }
                    $('div#membertip').show();
                    
                },
            mouseleave:
                function(){
                    $('div#membertip').remove();
                }
        });
        
        $('#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'});

        });
        if (!is_running_ie6()) {
            $('#dropdowns>li>div, #group_menu>li>div').hide();
            $('#dropdowns>li, #group_menu>li').each(function () {
                var $li = $(this);
                var $child = $li.children('div');
                $li.hoverIntent(function () {
                    $child.show();
                }, function () {
                    $child.hide();
                });
            });
        }
    };
    if ($.browser.msie) {
        setTimeout(startup, 200);
    } else {
        startup();
    }
});

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

/*
 * 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
 */

$(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();

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

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$/, '');
			FIELD_WIDTHS[$this.attr('id')] = $this.width();
    
            // 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 ($.browser.msie) {      
        setTimeout(do_helpers, 200);
    } else {
        do_helpers();
    }
    
}

function positionFloatingHelpers(event) {
    /*
     * postiion 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]);
			var fieldWidth = FIELD_WIDTHS[origField.attr('id')] || 300;
			
			// 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 + fieldWidth + 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();
        }
    }
}
