var pollingInterval = 1000 * 180; // 3 min
var nearBottomOfPage = false;
var pageInFocus = true;

// Hope this doesn't bollocks anything...
String.prototype.trim = function() { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }

// stop jQuery conflicting with Prototype
// (better solution: get rid of Prototype)
jQuery.noConflict();

// detect IE <= 6
if ( navigator.appVersion.indexOf( 'MSIE' ) != -1 ) {
	ie_vers = parseFloat( navigator.appVersion.split( 'MSIE' )[1] );
	if ( ie_vers <= 6 ) {
		var OLD_BROWSER = true;
	}
}

jQuery(document).ready( function() {
    setTimeout( 'putToolboxRight()', 1000 );
    doPolling();
} );

var pollingLoop = setTimeout( 'doPolling()', pollingInterval );

if ( jQuery.browser.msie == true ) {
    jQuery( document ).bind( 'focusout', function() { pageInFocus = false; } );
    jQuery( document ).bind( 'focusin', function() { 
        pageInFocus = true;
        clearTimeout( pollingLoop );
        doPolling();
    } );
} else {
    jQuery( window ).bind( 'blur', function() { pageInFocus = false; } );
    jQuery( window ).bind( 'focus', function() {
        pageInFocus = true;
        clearTimeout( pollingLoop );
        doPolling();
    } );
}

function doPolling() {
    if ( undefined === window.userId ) {
        return;
    }
    
    if ( !pageInFocus ) {
        pollingLoop = setTimeout( 'doPolling()', pollingInterval );
        return;
    }

    if ( undefined !== window.pollLock && pollLock ) {
	    pollingLoop = setTimeout( 'doPolling()', pollingInterval );
        return;
	}
	pollLock = true;
    clearTimeout( pollingLoop );

	// tasks for every polling round
	checkForNewCounts();
        
    if ( jQuery( '.areas_list' ).length ) {
        updateAreaLists();
    }
    
    if ( 
        ( undefined !== window.areaId || undefined !== window.viewType ) && 
        undefined !== window.pageNum &&
        pageNum == 1 && jQuery( '.threads_list' ).length &&
        !jQuery.browser.msie
    ) {
        updateThreadsList();
    }

	if ( !nearBottomOfPage || undefined === window.threadId ) {
        pollingLoop = setTimeout( 'doPolling()', pollingInterval );
        return;
    }

    // tasks for polling rounds when near the bottom of a thread
    checkForNewMessages();

    pollingLoop = setTimeout( 'doPolling()', pollingInterval );
}

jQuery( window ).scroll( function() {
	if ( undefined !== window.doingScroll && doingScroll ) {
		return;
	}
	doingScroll = true;
	
    var distFromBottom = jQuery( document ).height() 
        - jQuery( window ).height() 
        - jQuery( window ).scrollTop();

    nearBottomOfPage = ( distFromBottom <= 1000 );

    putToolboxRight();

	doingScroll = false;
} );

function putToolboxRight() {
	if ( jQuery.browser.msie == true && jQuery.browser.version < 6 ) {
		return;
	}

	var tbox = jQuery( '#toolbox' );
	var pbox = jQuery( '#personalbox' );

	if ( !tbox.length || !pbox.length ) {
		return;
	}

	// make sure tbox has a sane 'top' value to start with
	if ( tbox.css( 'top' ) == 'auto' ) {
		tbox.css( 'top', tbox.offset().top + 'px' );
	}

	// if tbox partially off bottom, move it back up to all
	// visible or as far as can without overlapping pbox

	tbox_top = tbox.offset().top
	bottom_of_tbox = ( tbox_top + tbox.height() + 20 );

	pbox_top = pbox.offset().top
	bottom_of_pbox = ( pbox_top - jQuery( window ).scrollTop() ) + pbox.height() + 30;

	window_height = jQuery( window ).height();

	// alert('window height: ' + window_height);
	// alert('bottom of toolbox: ' + bottom_of_tbox);

	if ( bottom_of_tbox > (window_height + jQuery(window).scrollTop()) ) {

		window_difference = ( bottom_of_tbox - window_height );
		var new_tbox_top = tbox_top - window_difference;

		// Move it down if it goes up too far
		if ( new_tbox_top < bottom_of_pbox ) {
			new_tbox_top = bottom_of_pbox;
		}

		tbox.stop().animate( { 'top': new_tbox_top }, 150 );

	}

	if ( bottom_of_pbox > tbox_top ) {
		tbox.stop().animate( { 'top': bottom_of_pbox }, 150 );
	}

}

function checkForNewCounts() {
    if ( undefined !== window.checkingForNewCounts && checkingForNewCounts ) {
        return;
    }
    checkingForNewCounts = true;
	
    jQuery.post(
        '/parts/forum/threads/loadnewcounts', {},
        function( responseText ) { 
			Result = eval( responseText );

            if ( Result[0] != 'success' ) {
                return;
            }
            
			if ( Result[1] ) {
			    jQuery( '.unreadcounts' ).html( Result[1] );
		    }
		    
			if ( Result[2] ) {
			    var message = 'You have ';
			    for ( i = 0; Result[2][i]; i++ ) {
			        switch( Result[2][i] ) {
			            case 'help':
			                message += 'new responses to <a href="/help/requests/yours">your help requests</a>';
			                break;
			            case 'started':
			                message += 'new responses to <a href="/forum/discussions/yours">discussions you started</a>';
			                break;
			            case 'private':
			                message += 'new <a href="/forum/discussions/private">private messages</a>';
			                break;
			            case 'tracked':
			                message += 'new messages in <a href="/forum/discussions/tracked">discussions you are tracking</a>';
			                break;
		            }
	
	                if ( Result[2].length == i + 2 ) {
	                    message += ' and ';
                    } else if ( Result[2].length > i + 1 ) {
    		                message += ', ';
    	            } else {
    	                message += '.';
	                }
	            }
	            
				jQuery( 'body' ).append( '<div class="alertbox">' + message + '</div>' );
				jQuery( '.alertbox' ).fadeIn( 1000, function() {
				    setTimeout( 'deleteAlertBox()', 20000 );
				} );

			}

			jQuery( '.toolbox .indicator' ).stop().fadeOut( 3000 );
      		pollLock = false;
            checkingForNewCounts = false;
        }
    );
}

function deleteAlertBox() {
    jQuery( '.alertbox' ).fadeOut( 1000, function() {
        jQuery( '.alertbox' ).remove();
    } );
}

function searchContent() {
    var category = jQuery( '#category' ).val();
    var type = jQuery( '#type' ).val();
    var token = jQuery( '#search_content' ).val();

    // don't sent through dumb search strings like "Search new"
    if ( token.substr( 0, 6 ) == 'Search' ) {
		token = '';
	}

    Drafts.search( 1, token, { category: category, type: type } );
    Completed.search( 1, token, { category: category, type: type } );
    Live.search( 1, token, { category: category, type: type } );
    Old.search( 1, token, { category: category, type: type } );

}

function changePage( evt, List, searchbox, extras ) {
	var Event = getEvt( evt );
	var Elm = getTarget( Event );

	if ( Event.preventDefault ) {
		Event.preventDefault();
	} 
	Event.returnValue = false;

	while ( Elm.tagName != 'A' ) {
		Elm = Elm.parentNode;
	}

	var page = Elm.href.match( /\d+$/ )[0];
	var token = jQuery( searchbox ).val();

	// don't sent through dumb search strings like "Search new"
	if ( token.substr( 0, 6 ) == 'Search' ) {
		token = '';
	}

	List.search( page, token, extras );
}

function whichList( Elm ) {
	while ( !jQuery( Elm ).is( '.list' ) ) {
		Elm = Elm.parentNode;
	}
	return Lists[Elm.id];
}

function getEvt( evt ) {
	return ( evt ) ? evt : ( ( event ) ? event : null );
}

function getTarget( evt ) {
	return ( evt.target ) ? evt.target : ( ( evt.srcElement ) ? evt.srcElement : null );
}

function cancelBubble( evt ) {
	var Event = getEvt( evt );
	Event.cancelBubble = true;
}

function selectDate( eleName ){
	var cal = new calendar3( jQuery( "#" + eleName + " input" ).get(0), jQuery( "#" + eleName + " div" ).get(0) );
	cal.popup();
	return false;
}

function rateContent( faq_id, rating ){
    jQuery.post(
        '/parts/content/rate',
        { content_id: faq_id, rating: rating },
        function( responseText ) {}
    );
	jQuery( "#faq_container #rate_options_" + faq_id ).html( rating == 1 ? "Yes" : 'No. Please check out <a href="/support/">more support options here</a>.' );
}


function loginBoxReveal(){
	jQuery( "#sidebar_login_link" ).attr( "href", "javascript:void(0);" );
	if( jQuery.browser.msie && parseInt( jQuery.browser.version ) == 7 )
		jQuery( "#sidebar_login" ).css( "display", "inline" );
	else
		jQuery( "#sidebar_login" ).slideDown();
	return false;
}

function getURLParameter( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function deleteFilterSet( filterId ) {
    var filterLink = jQuery( '#filter_' + filterId );
    var filterName = filterLink.text();

    if ( 
        !confirm( "Are you sure you want to delete your saved filter '" + filterName + "'?" ) 
    ) {
        return;
    }
    
    jQuery( filterLink ).text( 'Deleting...' );

    jQuery.post(
        '/parts/forum/threads/deletefilter',
        { filter_id: filterId },
        function( responseText ) { 
			Result = eval( responseText );

            if ( Result[0] != 'success' ) {
                alert( 'Error: ' + Result[0] );
                return;
            }
            
            jQuery( '#saved_filter_sets' ).html( Result[1] );
        }
    );
}

function doSearch(){
	jQuery( ".input_js_enabled" ).val( parseInt( getURLParameter("js") ) == 0 ? 0 : 1 );
}

function addVideoBehavior() {
	if(!jQuery('.more-videos').size()) return;

	jQuery(".more-videos").each(function() {
		jQuery(this).css('display', 'none');

		videos = jQuery(this).find('.video');
		count = videos.size();
		plural = (count != 1) ? 's' : '';

		jQuery(this).after('<div class="unloaded show-more">Show ' + count + ' more video' + plural + '</div>');

	});

	more_links = jQuery('.unloaded');

	more_links.click(function() {
		link = jQuery(this);
		toggle = link.hasClass('show-more') ? 'show-less' : 'show-more';
		link.removeClass('show-more').removeClass('show-less');

		link.addClass(toggle);

		more_vids = link.prev();
		videos = more_vids.find('.video');
		count = videos.size();
		plural = (count != 1) ? 's' : '';
		if(toggle == 'show-more') {
			link.text('Show ' + count + ' more video' + plural);
			more_vids.slideUp();
		} else {
			link.text('Hide ' + count + ' video' + plural);
			more_vids.slideDown();
		}

	});

	section = self.document.location.hash.substring( 1 );
	if(section) {
		jQuery.scrollTo( "#" + section, 500, { easing: 'swing', offset: -20 } );
	}
}

jQuery(document).ready(function() {
	addVideoBehavior();
});
