HUDHRE.views = (function()
{
    var fix_ie6 = function(){
		$(document).ready(function(){
			if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
				if (!!document.getElementById('maincontentwrapper') && !!document.getElementById('siteInfo')) {
					var position = $('#maincontentwrapper').offset();
					var divHeight = $('#maincontentwrapper').height();
					$('#siteInfo').css({left: position.left,top:divHeight+position.top});
				}
				
				// Navbar li:hover fix
				$('.menu > ul > li').hover(function() {
					$(this).addClass('hover');
				}, function() {
					$(this).removeClass('hover');
				});
			}
		});
	};
	
	var setup_tabs = function(target_el)
    {   
        var index,previous_index;
        $("#"+target_el+" ul#head li").live('click',function()
        {
           index = $(this).index();
            if(previous_index != index)
            {
                $("#"+target_el+" ul#head li").removeClass("activetab");
				$("#"+target_el+" ul#head .arrow").hide();
                $(this).addClass("activetab");
                $("#"+target_el+" ul.tab").hide();
				$("#"+target_el+" ul#head li.activetab .arrow").show();
                $("#"+target_el+" ul.tab:eq(" + index + ")").fadeIn("slow");
                previous_index = index;
            }
        });
    };	

	var setup_datepicker = function(target_el)
	{
		$(document).ready(function() {			   
  			$(target_el).datepicker({
				onSelect: function(dateStr) {
					$('label.warning').remove();
			        $('form').validate().element(this);
    			},					
				showOn: "button",
				changeMonth: true,
				changeYear: true,
				buttonImage: "assets/images/miniCalendar/calendar.gif",
				buttonImageOnly: true
			});
		});
	};
	
	var setup_autocomplete = function(target_el,data){
		 $(document).ready(function(){
			//IE6 Autosuggest z-index fix
            $('.ac_results').bgiframe();    
			$(target_el).autocomplete(data, {
				multiple: true,
				matchContains: true,
				selectFirst: false
			});
		  });
	};
	var setup_autocomplete_search = function(target_el,data){
		 $(document).ready(function(){
			//IE6 Autosuggest z-index fix
            $('.ac_results').bgiframe();    
			$(target_el).autocomplete(data, {
				multiple: false,
				matchContains: true,
				selectFirst: false
			});
		  });
	};

	var hook_dropdown_faq_search = function(target_change_el){
		$(document).ready(function(){
				$(target_change_el).change(function(e) {
					e.preventDefault();
					var el = $(this);
					var name= el.attr("name");
					var url_param=el.attr("value");
					//var goto=el.parents('form:first').attr("action");
					window.location = '/index.cfm?do=search&'+
						name+'='+url_param+'&cv=t4&refererType=dropdownFaqSearch';
				});
		  });
	};
	
	var hook_dropdown_resource_search = function(target_change_el){
		$(document).ready(function(){
				$(target_change_el).change(function(e) {
					e.preventDefault();
					var el = $(this);
					var name= el.attr("name");
					var url_param=el.attr("value");
					//var goto=el.parents('form:first').attr("action");
					window.location = '/index.cfm?do=search&'+
						name+'='+url_param+'&cv=t2&refererType=dropdownResourceSearch';
				});
		  });
	};

	var hook_search_tabs = function(target_el){
		$(document).ready(function(){
			$(target_el).click(function(e){
				e.preventDefault();
				$('#resultviewscv').val(this.id);
				$('#resultviews').submit();
			});
		
		});
	};
	var view_more_resources_faqs = function(target_el){
		$(document).ready(function(){
			$(target_el).click(function(e){
				e.preventDefault();
				$('#resultviewscv').val(this.target);
				$('#resultviews').submit();
			});
		
		});
	};

	var external_link_disclaimer =function(target_el){
		/* Not used for now
		$(document).ready(function() {		
			$(target_el+' a').filter(function(){
				return this.hostname && this.hostname !== location.hostname;
			}).click(function (){
					var x=window.confirm('External link. Click OK to proceed.');
					var val = false;
					if (x){val=true;}else{val=false;}return val;
				});
		});
		*/	
	};
	
	var faq_topic_selection =function(target_el,populate_el,data){
		$(document).ready(function() {
			$(populate_el+'_row').hide();
			$(target_el).change(function (){
				var selected = $(this).val().split('^')[0];
				$(populate_el+" option[value!=0]").remove();
				//parent selected
				if(selected != 0 && selected != null){
					$(populate_el+'_row').show();
					$.each(data[selected], function(i, val) {
						if(val != null){
//							$(populate_el).append(new Option(val.split('^')[1], val));
							var optionText = val.split('^')[1];
							optionText = optionText.replace('&#44;',',');
							$("<option>").attr("value", val).text(optionText).appendTo(populate_el);
						}
					});
				}
				else{//no parent selected
					$(populate_el+" option:first").attr('selected','selected');
					$(populate_el+'_row').hide();
				}	
			});
		});
			
	};				   
	
	//<!--- khe for tasks - 664 --->
	//var modify_print_link =function(target_el,faqList){
	//	$(document).ready(function() {
			//mod the print link
	//		var printLink = $(target_el +' a');
	//		printLink.html("Print FAQs");
	//		printLink.unbind('click');
	//		printLink.removeAttr('onclick');
	//		printLink.removeAttr('href');
	//		printLink.onclick=null;
	//		$('#printemaillinks a').css({'font-weight': 'bold','font-size':'12px'});
	//		printLink.click(function(e) {
	//			e.preventDefault();
	//			var navTo = '/index.cfm?do=printAllFaqs&faqList=' + faqList;
	//			window.open(navTo, '_blank', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=800,height=500');
	//			return false;
	//		});
	//	});
	//};
	
	var setup_hopwa_spotlight = function() {
	    // Check if the hopwa_print class is applied to the hopwa_box element.
	    // If it is, this is in printfriendly mode, so don't do anything.
	    if ( $('.hopwa_box').hasClass('hopwa_print') ) {
	        return;
	    }
	    
	    var slides = [
		
            {
            title: "2011 HOPWA IHHP SPNS Grantees",
            body: 'In response to the National HIV/AIDS Strategy\'s call for greater access to care through collaborations between federal and community plans, the Office of HIV/AIDS Housing announced seven new competitive grants that will become models of integration. They will all create an Integrated HIV/AIDS Housing Plan (IHHP) at the end of their three years that will be made public and will hopefully be a tool for other communities. Read more about the <a href="/index.cfm?do=viewHopwaIHHP_SPNSPrgm" title="2011 IHHP SPNS Grantees">2011 IHHP SPNS Grantees</a>.'},	
		
		
            {
            title: "New Searchable Bibliography of Peer-Reviewed Journal Articles related to HIV/AIDS and Housing",
            body: 'This database of over 300 recent articles can be searched by key word and filtered by Topic, Population and/or Region. Search results can be ordered by title, first author and year of publication. Details for each article include: abstract, full citation and web links to the full text for articles available open source. <a target="_blank" title="Click here to access http://www.hivhousingsummit.org" href="http://www.hivhousingsummit.org/2011/frmSearchAbstracts.aspx">Click here</a> to access the database.'},

          //  {
          //  title: "HOPWA 2011 New Projects Competition",
          //  body: 'HUD has announced the availability of HOPWA funding under a 2011 new projects competition. For additional information, please refer to the following listserv message: <a target="_blank" title="HOPWA Notice for 2011 New Projects Competition" href="/documents/2011HOPWAFundingNotice.pdf">HOPWA Notice for 2011 New Projects Competition</a>.'},

        {
            title: "HOPWA Financial Management Online Training Now Available",
            body: 'The Office of HIV/AIDS Housing is pleased to announce the availability of a new online training course on Financial Management for HOPWA Grantees. To access this training, select this <a target="_blank" title="HOPWA Financial Management Online Training" href="/hopwa/index.cfm?do=viewHopwaFinancialTraining">HOPWA Financial Management Online Training</a> link.'},

       
 	{
            title: "Equal Access to Housing Final Rule Published",
            body: 'HUD published the <em>Equal Access to Housing Final Rule</em> in the Federal Registrar on February 3, 2012. The rule will go into effect on March 5, 2012, to ensure that core programs are open to all eligible individuals and families regardless of sexual orientation, gender identity, or marital status. To find out more about the rule, click <a title="Equal Access to Housing Final Rule" href="/index.cfm?do=viewResource&ResourceID=4599">here</a>.'}


 	//{
        //    title: "HOPWA Model Programs Showcase",
        //    body: 'HUD is pleased to be showcasing a number of community-operated HOPWA programs in honor of the 20th anniversary of the authorization of the Housing Opportunities for Persons with AIDS (HOPWA) program as part of the Cranston-Gonzalez Affordable Housing Act. Models can be found on the following page: <a target="_blank" title="HOPWA Model Programs Showcase" href="http://www.hud.gov/offices/cpd/aidshousing/showcase/model_programs.cfm">HOPWA Model Programs Showcase</a>.'}


        ],
            index = 1,
            iteration = 1,
            limit = 10,
            slideWidth = 200;

        function animateSlide() {
            var slide = slides[index];
            if (typeof slide !== "undefined") {
                $(".hopwa_box h4").animate({
                    "left": "-" + slideWidth + "px",
                    "opacity": 0
                }, "slow", function() {
                    $(".hopwa_box h4").remove();
                    $(".hopwa_box").append($('<h4>' + slide.title + '</h4>').css({
                        "left": slideWidth + "px",
                        "opacity": 0
                    }).animate({
                        "left": 0,
                        "opacity": 1
                    }, "slow"));
                });
                $(".hopwa_box p").animate({
                    "left": "-" + slideWidth + "px",
                    "opacity": 0
                }, "slow", function() {
                    $(".hopwa_box p").remove();
                    $(".hopwa_box").append($('<p>' + slide.body + '</p>').css({
                        "left": slideWidth + "px",
                        "opacity": 0
                    }).animate({
                        "left": 0,
                        "opacity": 1
                    }, "slow"));
                });
            }
        }

        function iterator() {
            if (index == slides.length) {
                index = 0;
            }
            animateSlide();
            index++;
            iteration++;
            if (iteration == limit) {
                clearInterval(int);
            }
        }

        $('.hopwa_box h3').append($('<span class="hopwa_next">Next &raquo;</span>').click(function() {
            if (index == slides.length) {
                index = 0;
            }
            animateSlide();
            index++;
            clearInterval(int);
            int = setInterval(iterator, 7000);
        }));

        var int = setInterval(iterator, 8000);
	};
	
    var setup_success_story_nav = function() {
        $('#success_topics li span').click(function(e) {
            var parental = $(this).parent();
            if (parental.hasClass('expanded')) {
                parental.removeClass('expanded').children('ul').slideUp(); 
            } else {
                parental.addClass('expanded').children('ul').slideDown();
            }
        });
    };

		var gaq_pdf = function(){
			$('a[href*=".pdf"]').click(function(e) {
					var _gaq = _gaq || [];
				 _gaq.push(['_trackPageview', 'Downloads', 'PDF', $(this).attr("href")]); 
			});
		};
	
    return{
        setup_tabs: function(target_el)
        {
            setup_tabs(target_el);
        },
		setup_datepicker: function(target_el)
        {
            setup_datepicker(target_el);
        },
		fix_ie6: function()
        {
            fix_ie6();
        },
		setup_autocomplete_search:function(target_el,data)
		{
			setup_autocomplete_search(target_el,data);
		},
		setup_autocomplete:function(target_el,data)
		{
			setup_autocomplete(target_el,data);
		},
		hook_dropdown_resource_search:function(target_change_el){
			hook_dropdown_resource_search(target_change_el);
		},
		hook_dropdown_faq_search:function(target_change_el){
			hook_dropdown_faq_search(target_change_el);
		},
		hook_search_tabs:function(target_el){
			hook_search_tabs(target_el);
		},
		view_more_resources_faqs:function(target_el){
			view_more_resources_faqs(target_el);
		},
		external_link_disclaimer:function(target_el){
			external_link_disclaimer(target_el);
		},
		faq_topic_selection:function(target_el,populate_el,data)
		{
			faq_topic_selection(target_el,populate_el,data);
		},
		setup_hopwa_spotlight:setup_hopwa_spotlight,
		setup_success_story_nav:setup_success_story_nav,
		gaq_pdf: function()
    {
    	gaq_pdf();
    }
		//modify_print_link:function(target_el,faqList)
		//{
		//	modify_print_link(target_el,faqList);
		//}
    }
})();

jQuery(function($) {
    if ( $(".hopwa_box").length > 0 ) {
        HUDHRE.views.setup_hopwa_spotlight();
    }
    
    if ( $("#success_topics").length > 0 ) {
        HUDHRE.views.setup_success_story_nav();
    }
});
