var the_dco = function(disable_popups) {
	var DCOffice = this;
	
    $(function() { 
    
        // attach prior activity overlay properties
        attach_prior_activity_event();
        
        // Set main element size in old versions of IE
        if (is_old_ie()) {
            set_main_width();
            $(window).resize(set_main_width);
        }

		// add 'disable popups' class to document links if the box in the user account is checked
		if(disable_popups == 'yes') {
			$('a[href^="/document"]').attr('disable_popups','on');
		}
        
        update_links();
 		if($('body').attr('class') == '/usc'){
			$('body').attr('class','/usc/search');
		}
        
        if (window.location.href.search(/.*(all-subjects)$/) != -1) {
            $('#main').attr('class','all-subjects-main');
        }
        
        /*dhtmlHistory.initialize();
        dhtmlHistory.addListener(historyChange);*/
        $.scrollTo(0);
        var anchor = unescape(self.document.location.hash.substring((1)));
        if (anchor.length > 0) {
            if (is_old_ie()) {
                $('div#main').scrollTo('#'+anchor,1000);
            }
            else {
                $.scrollTo('#'+anchor,1000,{offset:-138});
            }
        }
        
        setup_ticker();
		
		//listen for hash-change event, scroll to anchors or page top 
		$(window).hashchange(function(){
			if(is_old_ie()){
				if(window.location.hash != '' && window.location.hash != '#'){
					$('div#main').scrollTo(window.location.hash);
				}
				else{
					$('div#main').scrollTo(0);
				}
			}
			else{
				if(window.location.hash != ''){
					$.scrollTo(window.location.hash,{offset:-138});
				}
				else{
					$.scrollTo(0);
				}
			}
		}).hashchange();
        
        $(".pullout_links a").hover( 
            function() {
                if ($("#sidebar-module-content img[name='"+$(this).attr('id')+"']").attr('class') != 'active_page') {
                    $("#sidebar-module-content img[name='"+$(this).attr('id')+"']").attr('src','/images/o_arrow.gif');
                }
            },
            function() {
                if ($("#sidebar-module-content img[name='"+$(this).attr('id')+"']").attr('class') != 'active_page') {
                    $("#sidebar-module-content img[name='"+$(this).attr('id')+"']").attr('src','/images/o_blank.gif');
                }
            }
        );
        
        $("#expand").toggle( 
            function() {
                $("#sidebar-module-content").addClass("inactive");
                $(this).html('+');
            },
            function() {
                $("#sidebar-module-content").removeClass("inactive");
                $(this).html('-');
        });
        
        $('.top-nav-link').each( function() {
            if ($('body').attr('class') == $(this).attr('href')) { 
                $(this).children().attr('src', $(this).children().attr('src').replace("_off","_active"));
                $(this).addClass('active');
            }
        });
        
        $("#corporate-user-list tr:odd").css("background-color", "#bbbbbb");
        $("#corporate-user-list tr:even").css("background-color", "#cccccc");
        
        $("input[name='select_all']").click( function() {
            var checked_status = this.checked;
            $("input[name^=select_array]").each(function() {
                this.checked = checked_status;
            });
        });
        
        $('input[name="submit"]').click( function(){
            if ($('input[name="search"]').val() == '') {
                $('p.error', $(this).parent()).show();
                return false;
            }
            else {
                $('#usc-search form[name="toc_serach_form"]').submit();
            }
        });
        
        $('input[name="all47"]').click( function(){
            if ($(this).is('.open')) {
                $('table.chapter-content').each( function() {
                    $(this).slideUp();
                });
                $('.chapter-name a').each( function() {
                    $(this).removeClass('open');
                });
                $(this).removeClass('open');
                $(this).val('View Entire Table of Contents below');
            }
            else {
                $('table.chapter-content').each( function() {
                    $(this).slideDown();
                });
                $('.chapter-name a').each( function() {
                    $(this).addClass('open');
                });
                $(this).addClass('open');
                $(this).val('Close Table of Contents below');
            }
        });
        
        // Determine height of pdf-display iframe
        if ($('div.pdf-display').length) {
            $('div.pdf-display').height($(window).height()-$('#header-wrap').height()-$('#footer-wrap').height()); // 235
        }
        
        if ($('#account-management, #corporate-management').length) {
            $('.account_tab').click( function(e) {
                e.preventDefault();
                window.location = $(this).attr('url');
            })
        }
        
		$('.link_button').click(function(e){
			e.preventDefault();
            window.location = $(this).attr('url');
		});
    });
    
    var attach_prior_activity_event = function() {
        $('.activity_overlay').each( function() {
            $(this).hover( function(e) {
                var location = $(this).offset();
                $('#main').append('<div id="activity_info">'+$(this).attr('overlay_text')+'</div>');
                if(is_old_ie()) {
                    $('#activity_info').css({'left':location.left-$('#left-menu-wrap').width()+'px','top':location.top+25-$('#header-wrap').height()+'px'}).show();
                }
                else {
                    $('#activity_info').css({'left':location.left+'px','top':location.top+$(this).height()+'px'}).show();
                }
                alignOverlay($('#main'),$('#activity_info'),e.pageY,0,location);
            },
            function() {
                $('#activity_info').remove();
            });
        });
    }
 
	return this;   
};

function update_links() {

    $("a[href='#']").click( function(event){
        event.preventDefault();
    });

    $("a[name]").each(function() {
        $(this).attr('id',$(this).attr('name'));
        $(this).removeAttr('name');
    });
    
    $("a[href^='#'][href!='#']").each( function() {
        $(this).click( function(event) {
            event.preventDefault();
			window.location.hash = $(this).attr('href').replace(/ /g,'-');
            //scroll_to($(this).attr('href').replace(/ /g,'-'));
        });
    });

    $('a[href^="/document"]').each( function() {
        var link = $(this);
        link.attr('target','_blank');
        var document_regex = /\?filename=([^\.]+).pdf/;
        var document_name = link.attr('href').match(document_regex);
        if (typeof(document_name) != "undefined" && document_name !== null) {
            link.mouseover( function() {
                $('select[name="subject_id"]').hide();
				if(!link.attr('disable_popups')){
					var image = new Image();
	                image.onerror = function() {
	                    link.attr('img_url','/images/placeholder_400.jpg');
	                    show_document_overlay(link);
	                };
	                image.onload = function() {
	                    link.attr('img_url','/files/'+document_name[1]+'.jpeg');
	                    show_document_overlay(link);
	                };
	                image.src = '/files/'+document_name[1]+'.jpeg';
				}
            });
            link.mouseout(function(e) {
                mouse_coords = {'x':e.pageX, 'y':e.pageY};
                var overlay = $('#document_overlay');
                var overlay_offset = overlay.offset();
                var overlay_dimensions = {'width':overlay.width(),'height':overlay.height()};
                if (!(mouse_coords.x > overlay_offset.left 
                    && mouse_coords.x < (overlay_offset.left+overlay_dimensions.width)
                    && mouse_coords.y > overlay_offset.top
                    && mouse_coords.y < (overlay_offset.top+overlay_dimensions.height))) {
                    $('#document_overlay').empty().hide();
					$('#overlay_x').empty().hide();
	                $('select[name="subject_id"]').show();
                }
            });
        }
    });
    
	//SUBJECT HOME PAGES overlay
    $(".subject-highlight").hover( function() {
		var sub = $(this);
    	var highlight = sub.children('.subtopic-overlay');
		var highlight_link = highlight.prev('a');
		
		if(!is_old_ie()) highlight.css({'position': 'absolute','left': sub.offset().left+'px','top': sub.offset().top+sub.height()+'px'});	
		
		var doc_width = sub.parents("#all-subjects").width();
		var doc_left = sub.parents("#all-subjects").offset().left;
		var highlight_width = highlight.width();
		var padding = 5;
					
    	highlight.show();
		
		var ie_fix = 0;
		//adjust position to keep overlay within the fcc-document div on left and right
		if(is_old_ie()){
			var main = $('div#all-subjects').width();
			if(highlight.offset().left+highlight_width > main){
				highlight.css('left',main-highlight_width-padding+'px');
			}
			
			highlight.css('top', highlight_link.offset().top-$('#header-wrap').height()+highlight_link.height()-5+$('div#main').scrollTop()+'px');
			ie_fix = $('div#main').scrollTop()-$('#header-wrap').height();
		}
		else{
			if(parseInt(highlight.css('left'))+highlight_width > doc_left+doc_width){
				highlight.css('left',doc_left+doc_width-highlight_width-padding+'px');
			}
		}
		
		// If the overlay is too big, set it to height = 100 and autoscroll
		if(highlight.height() > 100) highlight.css({'overflow': 'auto','height':'100px'});
		if(highlight.offset().top+highlight.height() > $('#footer-wrap').offset().top) highlight.css('top',$('#footer-wrap').offset().top-highlight.height()+ie_fix-15+'px');
	
    	},function() {
        $(this).children('.subtopic-overlay').hide();
    });
    
    $(".brief-comments-link").mouseover( function() {
        $(this).next('.brief-comments').show();
    }).mouseout( function() {
        $(this).next('.brief-comments').hide();
    });
    
    // FCC Document hovers
    $(".assignment-link").hover( function(e) {
        var docket_info = $(this).next('.assignment-overlay');
        var position = $(this).offset();
        if (is_old_ie()) {
            docket_info.css('left',position.left - docket_info.width() +'px');
            docket_info.css('top',position.top-110+'px');
        }
        else {
            docket_info.css('left',position.left - (docket_info.width() / 2)+'px');
            docket_info.css('top',position.top+15+'px');
        }
		
        docket_info.show();
	alignOverlay($(this).parents("#main"),docket_info,e.pageY,0);
    }, function() {
        $(this).next('.assignment-overlay').hide();
    });
    
    //View prior activity links
    $(".activity-link").hover( function() {
        var docket_info = $(this).next('.assignment-overlay');
        var position = $(this).offset();
        if (is_old_ie()) {
            docket_info.css('left',(position.left - (docket_info.width() / 2)) - $('#left-menu-wrap').width() +'px');
            docket_info.css('top',(position.top+15) - $('#header-wrap').height() +'px');
        }
        else {
            docket_info.css('left',position.left - (docket_info.width() / 2)+'px');
            docket_info.css('top',position.top+15+'px');
        }

        docket_info.show();
	alignOverlay($(this).parents("#headline"),docket_info,e.pageY,0);
    }, function() {
        $(this).next('.activity-overlay').hide();
    });
    
    
    $("#fcc-record-title").mouseover( function() {
        $("#fcc-document .overlay").show();
    }).mouseout( function() {
        $("#fcc-document .overlay").hide();
    });
    
    //hide the comments section on subject page
  	$("#due-date").hide().attr('state','closed');
  	//toggle the componenet with class msg_body
  	$("#due-dates-toggle").click(function() {
    	$(this).next("#due-date").slideToggle(600);
    	if($(this).next("#due-date").attr("state") == "closed") {
    		$(this).next("#due-date").attr( "state","" );
    	} else {
    		$(this).next("#due-date").attr( "state","closed" );
    	}
  	});
  	
  	$('.top-nav-link,.left-nav-link').hover(
        function() {
            if (!$(this).attr('class').match('active')) {
                $(this).children().attr('src', $(this).children().attr('src').replace("_off","_active"));
            }
        },
        function() {
            if (!$(this).attr('class').match('active')) {
                $(this).children().attr('src', $(this).children().attr('src').replace("_active","_off"));
            }
    });

}

function show_document_overlay(link) {
    var main = $('#main');
    var link_offset = link.offset();
    var overlay = $('#document_overlay');
	var x_button = $('#overlay_x');
    overlay.empty().show();
	x_button.empty().show();
    overlay.append('<a href="'+link.attr('href')+'" target="_blank"><img src="'+link.attr('img_url')+'" alt="" /></a>');
	x_button.append('<a id="overlay_x"><img src="/images/closebutton.gif" /></a>');
	x_button.click(function(){
		overlay.empty().hide();
		x_button.empty().hide();
	});
    var link_dimensions = {'width':link.width(),'height':link.height()};
    var overlay_dimensions = {'width':overlay.width(),'height':overlay.height()};
    var window_dimensions = {'width':$(window).width(),'height':$(window).height()};
    overlay.css({'left':(window_dimensions.width/2)-(overlay_dimensions.width/2)+'px', 'top':(window_dimensions.height/2)-(overlay_dimensions.height/2)+'px'});
	x_button.css({'left':(window_dimensions.width/2)+(overlay_dimensions.width/2)-(16)+'px', 'top':(window_dimensions.height/2)-(x_button.height()/2)+'px'});
    if (!is_old_ie()) {
        overlay.css('top',parseInt(overlay.css('top'))+$(window).scrollTop()+'px');
		x_button.css('top',parseInt(x_button.css('top'))+$(window).scrollTop()+'px');
    }
	$('#document_overlay').mouseout( function() {
        $(this).empty().hide();
		$('#overlay_x').empty().hide();
        $('select[name="subject_id"]').show();
    });
}

function alignOverlay(fcc_doc,docket_info,mouseY,padding,object){
	var doc_pos = fcc_doc.offset();
	var footer_top = $("#footer-wrap").offset().top;
	var info_left = docket_info.offset().left;
	var info_top = docket_info.offset().top;
	var main = $('div#main');
	
	//adjust position to keep overlay within the fcc-document div
	if(is_old_ie()){
		docket_info.css('top',parseInt(docket_info.css('top'))+main.scrollTop()+'px');
		
		if(info_left+docket_info.width() > main.offset().left+main.width()){
			docket_info.css('left',main.offset().left+main.width()-docket_info.width()*2-padding +'px');
		}
		if(info_left < main.offset().left){
			docket_info.css('left',main.offset().left-docket_info.width()/2+'px');
		}
		if(docket_info.offset().top+docket_info.height() > footer_top+15){
			
			if(object){
				docket_info.css('top',object.top-docket_info.height()+main.scrollTop()-30-$('#header-wrap').height()+'px')
			}
			else{
				docket_info.css('top',mouseY-docket_info.height()+main.scrollTop()-30-$('#header-wrap').height()+'px')
			}
		}
	}
	else{
		if(info_left+docket_info.width() > doc_pos.left+fcc_doc.width()){			
			docket_info.css('left',doc_pos.left+fcc_doc.width()-docket_info.width()-padding+'px');
		}
		if(info_left < doc_pos.left){						
			docket_info.css('left',doc_pos.left+padding+'px');
		}
		if(info_top < doc_pos.top){			
			docket_info.css('top',mouseY+padding+'px');
		}
		if(info_top+docket_info.height() > footer_top){			
			docket_info.css('top',mouseY-docket_info.height()-30-padding+'px');
		}
	}
	
}

function setup_ticker() {

    $('ul#ticker01').css({'display': 'block','visibility':'visible'});
   // $('ul#ticker01').css('visibility', 'visible');
    
    if ($.cookie('scroll-position')) {
        $('ul#ticker01').liScroll({travelocity: 0.1, startleft: $.cookie('scroll-position')});
        $('.tickercontainer').css('width', '44%');
    }
    else {
        $('ul#ticker01').liScroll({travelocity: 0.1, startleft: 0});
        $('.tickercontainer').css('width', '44%');
    }

    var date = new Date();
    date.setTime(date.getTime() + (.5 * 60 * 1000));
    $(window).unload(function() {
        $.cookie("scroll-position",$('ul#ticker01').css('left').replace(" px", ""), {expires: date});
    });
}

/*function historyChange(newLocation, historyData)
{
    alert(newLocation);
    request_new_page(newLocation);
}*/

function setVisibility(objId, sVisibility) {
	var obj = document.getElementById(objId);
	obj.style.visibility = sVisibility;
	
	if (sVisibility == 'visible') {
		obj.style.display = 'block';
	} else {
		obj.style.display = 'none';
	}
}

function saveDisableScroll(value) {
    $.post('/account-management/save-preferences', {'disable_scroll': value}, function(response) {
        if ($.trim(response) != "") {
            window.alert(response);
        }
    }, 'text');
}


// Open glossary page
function glossary_word(word)
{
    window.open("/glossary?gloss_id=" + word, +word, "height=200,width=400,scrollbars=yes,resizable=yes,toolbar=no");
    if (is_old_ie()) {
        $('div#main').scrollTo({top:'0px',left:'0px'});
    }
    else {
        $.scrollTo({top:'0px',left:'0px'}, 0);
    }
}

// Just for old version of IE
function set_main_width() {
    $('div#main').width($(window).width()-$('#left-menu-wrap').width()-44);   //44 206
    $('div#main').height($(window).height()-$('#header-wrap').height()-$('#footer-wrap').height()+21); // 235
    $('div#left-menu-wrap').height($(window).height()-$('#header-wrap').height()-$('#footer-wrap').height()+15);
}

function is_old_ie() {
    if ($.browser.msie && (parseInt($.browser.version) == 6 || parseInt($.browser.version) == 7)) {
        return true;
    }
}

function scroll_to(location) {
    window.location.hash = location;
}

function clearCalendarCookies() {
    document.cookie = "calendar_date=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function attachReferenceLinkEvents() {
	$('.reference_link').hover(function() {
		var me = $(this);
		var view = $('#your_reference_view');
		view.html(me.attr('ref_text'));
		view.show();
		center_overlay(view);
	}, function(e) {
		var me = $(this);
		var view = $('#your_reference_view');
		var mouse_coords = {'x':e.pageX, 'y':e.pageY};
		var ref_offset = view.offset();
		var ref_dimensions = center_overlay(view);
	
		if (!(mouse_coords.x > ref_offset.left 
	        && mouse_coords.x < (ref_offset.left+ref_dimensions.width)
	        && mouse_coords.y > ref_offset.top
	        && mouse_coords.y < (ref_offset.top+ref_dimensions.height))) {
	        view.empty().hide();
	    }
		else {
			view.mouseout(function() {
				view.empty().hide();
			});
		}
	});
}

function center_overlay(overlay){
	var window_dimensions = {'width':$(window).width(),'height':$(window).height()};
	var overlay_dimensions = {'width':overlay.width(),'height':overlay.height()};
	overlay.css({'left':(window_dimensions.width/2)-(overlay_dimensions.width/2)+'px', 'top':(window_dimensions.height/2)-(overlay_dimensions.height/2)+'px'});
	return overlay_dimensions;
}

