function ieHover(){
	$('#menu li').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
}
if (window.attachEvent && !window.opera){
	window.attachEvent("onload", ieHover);
}
function hideCities(){
	$('.maps a').attr('class','');
}

var relurl = jQuery.url.attr('relative').toLowerCase();
var fullurl = jQuery.url.attr('source').toLowerCase();
var relurl = relurl.replace(/&page=\d{0,}/gi,'');
var fullurl = fullurl.replace(/&page=\d{0,}/gi,'');
var helpdeskpage = relurl.match(/helpdesk/gi);
var linkspage = relurl.match(/links/gi);
var photoToShow = 1;
var videoToShow = 1;
var numPhotos;
var numVideos;
$(document).ready(function(){
    // set up welcome vid (BETA)
    if($('#flashwelcome').length > 0)
    {
//	    var so = new SWFObject("/welcome/welcome.swf", "welcome", "410", "263", "8");
//        so.write("flashwelcome");
    }
    // set sidebar corners
    $('.section-links').corner('14px bottom');
    //$('#sidebar .section-links').corner('14px top');
    $('.doc-search').corner('14px');
    $('.issue-repeater').corner('14px');
    $('.rsl-border').corner();
    $('.rs-link').corner('8px');
    // Stripe dropdown menus
    $('.drop-down-top li:even a').addClass('color');
    // hack the news page
    HackNewsPage();
    // add issue button frames
    FrameIssues();
    // remove duplicate headlines on issue pages
    $('#ctl00_ctl06_IssueTitle ~ br').remove();
    $('#ctl00_ctl06_IssueTitle').remove();
    // highlight sidebar current url
    highlightUrl();
    // Remove dropdowns on pages with pdf iFrames
    PdfIframeHack();
    HackLinksWithFS21();
    //Set up Form Validation
    ValidateForms();
    // Set up TextOnly
    if(readCookie("textonly")=="true")
    {
        $('#Stylesheet1').attr('href','null');
        $('#TextOnly').attr('style','color:Red; font-weight:bold; font-size:1.6em;');
    }
    // Set up popup
    if(readCookie('popup')!='hide')
    {
        $('#modalPopup').click();
        createCookie('popup','hide',700);
    }
    // clear text boxes on click
    SetUpFieldHides();
    //Header clickable
    $('#header .header-box').click(function(){
        window.location = '/';
    });
    //Set up Datepicker
    $('.datepicker').datepicker();
    //Homepage Subtabs
    InitPhotoTab();
    //Set up Photo Album Anchor handlers
    SetUpAnchorHandlers();
    // Seed forms
    Seeding();
	// reset all tabs on start
	$('.tabset').find('a.tab').each(function(){
		if($(this).is('.active')){
			$($(this).attr('href')).show();
			hideCities();
			_rel = $(this).attr('rel');
			if (_rel) {
				$('#'+_rel).addClass(_rel);
			}
		} else {
			$($(this).attr('href')).hide();
		}
	});
	$('.tabset').find('a.tab').click(function(){
	    StopAllVideos();
		$(this).parent().parent().find('a.tab').each(function(){
			$(this).removeClass('active');
			$($(this).attr('href')).hide();
		});
		$(this).addClass('active');
		$($(this).attr('href')).show();
		if(!$(this).parent().parent().hasClass('tabs-top'))
		{
		    hideCities();
		}
		_rel = $(this).attr('rel');
		if (_rel) {
			$('#'+_rel).addClass(_rel);
		}
		return false;
	});
	$('.maps a').click(function(){
	    var Gpa = $(this).parent().parent();
	    var link = $(this).attr('href');
	    Gpa.find('.footer-box-bottom').children('.tab').hide();
	    Gpa.find('.tabset a.tab').removeClass('active');
	    Gpa.find('.tabset a.tab').each(function(){
	        if($(this).attr('href') == link)
	        {
	            $(this).addClass('active');
	        }
	    });
	    Gpa.find(link).show();
	    hideCities();
	    $(this).addClass($(this).attr('id'));
	});
});

function FrameIssues()
{
    $('.icons li').each(function(){
        var issueLink = $(this).children('a:first').attr('href');
        $(this).append('<a href="'+issueLink+'" class="icon-frame">&nbsp;</a>');
    });
    $('#issueslist td .isshold').each(function(){
        var issueLink = $(this).children('a:first').attr('href');
        $(this).append('<a href="'+issueLink+'" class="icon-frame-int">&nbsp;</a>');
    });
}

function SetUpFieldHides()
{
    $('input[type="text"]').addClass("idleField");
    $('.embed-txt').removeClass('idleField');
    $('.idleField').focus(function() {  
        $(this).removeClass("idleField").addClass("focusField");  
        if (this.value == this.defaultValue){  
            this.value = '';  
        }  
        if(this.value != this.defaultValue){  
            this.select();  
        }  
    });  
    $('input[type="text"]').blur(function() {  
        $(this).removeClass("focusField").addClass("idleField");  
        $('.embed-txt').removeClass('idleField');
        if ($.trim(this.value) == ''){  
            this.value = (this.defaultValue ? this.defaultValue : '');  
        }  
    });  
}

function highlightUrl()
{
    $('.RightSidebar li a').each(function(){
        var href = $(this).attr('href').toLowerCase();
        if((href == relurl) || (href == fullurl))
        {
            $(this).addClass('red');
        }
        if((href=='/helpdesk/') && (helpdeskpage != -1) && (helpdeskpage != null))
        {
            $(this).addClass('red');
        }
        if((href=='/links/state.htm') && (linkspage != -1) && (linkspage != null))
        {
            $(this).addClass('red');
        }
    });
}

function HackNewsPage()
{
//    if(relurl.match(/news/gi) != null)
//    {
//        $('#ctl00_ctl03_TopStories_ctl04_Table1 ~ p').remove();
//        $('#ctl00_ctl03_TopStories_ctl04_Table1 ~ ul').remove();
//        $('#aspnetForm > .pageTitle:gt(0)').remove();
//        $('#aspnetForm > .pageTitle:first ~ ul').remove();
//        $('#aspnetForm > .pageTitle').removeClass('pageTitle');
//        $('#PageContent .middleheadline > b').addClass('NewsHeadline');
//        $('b.NewsHeadline').click(function(){
//            var linkTo = $(this).parent().parent().children('a:first').attr('href');
//            window.location=linkTo;
//        });
//    }
    $('#PageContent a:not([href])').css('color','#000').css('text-decoration','none');
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function ToggleTextOnly()
{
    if(readCookie("textonly")==null||readCookie("textonly")=="false")
    {
        createCookie("textonly","true");
        $('#Stylesheet1').attr('href','null');
        $('#TextOnly').attr('style','color:Red; font-weight:bold; font-size:1.6em;');
    }
    else
    {
        createCookie("textonly","false");
        $('#Stylesheet1').attr('href','/css/all.css');
        $('#TextOnly').attr('style','');
    }
}

function InitPhotoTab()
{
    numPhotos = $('#homePhotos li').length;
    numVideos = $('#homeVideos li').length;
    $('#homePhotos li:gt(0)').hide();
    $('#homeVideos li:gt(0)').hide();
    $('#homePhotos a').click(function(event){        
        var slide = $(this).attr('rel');
        if(slide == "Prev")
        {
            event.preventDefault();
            if(photoToShow > 1)
            {
                photoToShow--;
            }
            else
            {
                photoToShow = numPhotos;
            }
            $(this).parent().find('.slides li').hide();
            $(this).parent().find('.slides li:eq('+(photoToShow-1)+')').show();
        }
        else if (slide == "Next")
        {
            event.preventDefault();
            if(photoToShow < numPhotos)
            {
                photoToShow++;
            }
            else
            {
                photoToShow = 1;
            }
            $(this).parent().find('.slides li').hide();
            $(this).parent().find('.slides li:eq('+(photoToShow-1)+')').show();
        }
    });
    $('#homeVideos a').click(function(event){
        StopAllVideos();
        var slide = $(this).attr('rel');
        if(slide == "Prev")
        {
            event.preventDefault();
            if(videoToShow > 1)
            {
                videoToShow--;
            }
            else
            {
                videoToShow = numVideos;
            }
            $(this).parent().find('.slides li').hide();
            $(this).parent().find('.slides li:eq('+(videoToShow-1)+')').show();
        }
        else if (slide == "Next")
        {
            event.preventDefault();
            if(videoToShow < numVideos)
            {
                videoToShow++;
            }
            else
            {
                videoToShow = 1;
            }
            $(this).parent().find('.slides li').hide();
            $(this).parent().find('.slides li:eq('+(videoToShow-1)+')').show();
        }
    });
}


// Handler for anchors
/*
  jQuery anchor handler - 0.5
  http://code.google.com/p/jquery-utils/

  (c) Maxime Haineault <haineault@gmail.com>
  http://haineault.com   

  MIT License (http://www.opensource.org/licenses/mit-license.php)

*/

(function($){
    var hash = window.location.hash;
    var handlers  = [];
    var opt = {};

        $.extend({
                anchorHandler: {
            apply: function() {
                $.map(handlers, function(handler){
                    var match = hash.match(handler.r) && hash.match(handler.r)[0] || false;
                    if (match)  { handler.cb.apply($('a[href*='+match+']').get(0), [handler.r, hash || '']); }
                });
                return $.anchorHandler;
            },
                        add: function(regexp, callback, options) {
                var opt  = $.extend({handleClick: true, preserveHash: true}, options);
                if (opt.handleClick) { 
                    $('a[href*=#]').each(function(i, a){
                        if (a.href.match(regexp)) {
                            $(a).bind('click.anchorHandler', function(){
                                if (opt.preserveHash) { window.location.hash = a.hash; }
                                return callback.apply(this, [regexp, a.href]);
                                });
                        }
                    }); 
                }
                                handlers.push({r: regexp, cb: callback});
                $($.anchorHandler.apply);
                                return $.anchorHandler;
                        }
                }
        });
})(jQuery);


function SetUpAnchorHandlers(){
    $('.PhotoAlbumTitle').each(function(){
        var albumAnchor = $(this).attr('id');
        var albumID = albumAnchor.match(/\d+/);
        $.anchorHandler.add('oto', function(){$(this).show();});
        var nothing = 5;
        //$(this).hide();
    });
    
}

function PdfIframeHack()
{
    $('iframe[src*=.pdf]').each(function(){
        $('#menu .drop-down-top').remove();
    });
    if(relurl.match(/multimedia/) != null)
    {
        $('#menu .drop-down-top').remove();
    }
}

function ValidateForms()
{
//    $('form.valForm input').validate({
//        rules:{
//            zip5:{required:true}
//        },
//        messages: {
//            required:'',
//            email:'<br/>Please enter a valid email address',
//            zip5:'arg!'
//        }
//    });
//    
    
    $('form.valForm').validate({
        //debug:true,
        errorContainer: "#ErrorHeader, #ErrorList",
        errorLabelContainer: "#ErrorList"
        //wrapper: "span"
        //messages:{zip5:'argle'}
    });
}

function StopAllVideos()
{
//    $('object').each(function(){
//        if($(this).children('param[value*=youtube]').length>0)
//        {
//            $(this).pauseVideo();
//        }
//    });
//    $('embed[src*=youtube]').each(function(){
//        $(this).pauseVideo();
//    });

    var video = $('object[id*=ytplay], embed[id*=ytplay]');
    video.each(function(){
        try{
            this.stopVideo();
        }
        catch(err)
        {
            //var vidError = err;
            //var nothing = 6;
        }
    });
}

function HackLinksWithFS21()
{
    //alert('hi');
    $('a[href*=fireside21]').each(function(){
        //alert('hi2');
        var templink = $(this).attr('href');
        templink = templink.replace(/davis\.fireside21\./gi,'geoffdavis.');
        $(this).attr('href',templink);
    });
    $('#PageContent [style*="ms sans serif"]').css('font-family','Helvetica, Verdana, Tahoma, Arial, Sans-Serif');
}

function Seeding()
{
    var formID = jQuery.url.param('ID');
    if(formID == '480')
    {
        $('input#ctl00_ctl06_ctl02_MyText').replaceWith('<select id="ctl00_ctl06_ctl02_MyText" name="ctl00$ctl06$ctl02$MyText"><option value=""></option><option value="Ms.">Ms.</option><option value="Mr.">Mr.</option><option value="Mrs.">Mrs.</option><option value="Dr.">Dr.</option></select>');
        $('select[id*=AddressState]').html('<option value="KY">Kentucky</option>');
        $('input[id*=AddressZip]').blur(function(){
            xajax_getTTHcode($('input#ctl00_ctl06_ctl05_AddressZip').val(),$('input#ctl00_ctl06_ctl05_AddressZipPlus4').val(),state,district);
        });
        $('input#ctl00_ctl06_ctl06_MyText').hide();
        $('.formAddress label:not(:eq(1))').append(' *');
    }
    else if (formID == '482')
    {
        $('.formAddress label:not(:eq(1))').append(' *');
    }
}
