//openWindow script from the previous site
function openWindow(url,x,y,toolbar,scrollbars,resizable)
{
	new_x=x+20;
	new_y=y+20;
	var options = "toolbar=" + toolbar + ",scrollbars=" + scrollbars + ",resizable=" + resizable + ",width=" + new_x + ",height=" + new_y;
	newWindow=window.open(url,"WinOpen",options);
}

// For clearing the comment form
var blanked = new Array();
function blank(textfield) {
  if (blanked[textfield.name] != true)
  {
    blanked[textfield.name] = true;
    textfield.value = "";
  }
}


//Cufon.replace('.page-name p', { fontFamily : 'Myriad Pro', fontSize: '17px' });
//
//Cufon.replace('.slogan p', { fontFamily : 'Myriad Pro', fontSize: '13px' });
//
//Cufon.replace('.psalm', { fontFamily : 'Myriad Pro', fontSize: '10px' });
//
//Cufon.replace('#navigation > ul > li > a', { fontFamily : 'Myriad Pro', fontSize: '12px' });
//
// this needs to also be in place below, in a slider callback, where it gets redrawn
//Cufon.replace('.slider .text a', { fontFamily : 'Myriad Pro', fontSize: '46px' });
//
//Cufon.replace('.buttons .title h3', { fontFamily : 'Myriad Pro', fontSize: '21px' });
//
//Cufon.replace('.socials h3', { fontFamily : 'Myriad Pro', fontSize: '15px' });
//
//Cufon.replace('.sitemap h4', { fontFamily : 'Myriad Pro', fontSize: '16px' });
//
//Cufon.replace('.masthead h1', { fontFamily : 'Myriad Pro', fontSize: '27px' });
//
//Cufon.replace('.welcome .title p', { fontFamily : 'Myriad Pro', fontSize: '17px' });
//
//Cufon.replace('.schedule .tabs-holder .tab h2', { fontFamily : 'Myriad Pro' });
//
//Cufon.replace('.schedule .tabs-holder .tab p', { fontFamily : 'Myriad Pro' });
//
//Cufon.replace('.convention .text h1', { fontFamily : 'Myriad Pro' });

// preload
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}






$(document).ready(function () {


//Global Slideout List////////////////////
$('#fs-global').hide();
$('a.global').click(function() {$('#fs-global').slideToggle(300);
return false;
});

$('a.global').click(function() {$('#quick-links').hide();
return false;
});

$('#quick-links').hide();
$('a.quicklinks').click(function() {$('#quick-links').slideToggle(300);
return false;
});

$('a.quicklinks').click(function() {$('#fs-global').hide();
return false;
});


// preloading graphics
$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// TODO: Load these only on the article page
$(['/images/dnews_innerbk.png','/images/dnews_innerbk290.png']).preload();

// TODO: Load these only on the home page
$(['/images/button1max.gif','/images/button2max.gif','/images/button3max.gif','/images/button4max.gif']).preload();

	
	// Share This functionality
	if(typeof(SHARETHIS) != "undefined"){
		var sharethisobject = SHARETHIS.addEntry({
		title:'share',
		summary: 'Sharing is good for the soul.'},
		{button:false});
	
		//Tie customized button to ShareThis button functionality.
		$('.sharethis').each(function(i){sharethisobject.attachButton(this);})

		$('.sharethis').click(function(i){
			return false;
		})
	}

	// text fields
	$('.blink')
		.focus(function(){
			if( $(this).val() == $(this).attr('title') ) {$(this).val('');}
		})
		.blur(function(){
			if( $(this).val() == '' ) {
				$(this).val( $(this).attr('title') );
			}
		});
		
	// navigation dropdown
	$("#navigation ul li").hover(function() {
		//$("#header").css({ 'z-index' : 100 });
		$(".head").css({ 'z-index' : 10 });
		$(this).css({ 'z-index' : 100 });
		$(this).find(".dd").show();
		$(this).find("a:eq(0)").addClass('hover');
	}, function() {
		//$("#header").css({ 'z-index' : 1 });
		$(".head").css({ 'z-index' : 1 });
		$(this).css({ 'z-index' : 1 });
		$(this).find(".dd").hide();
		$(this).find("a:eq(0)").removeClass('hover');
	});
	
	// choose language dropdown
	$(".lang").hover(function() {
		$(this).css({ 'z-index' : 200 });
		$(this).find(".dd-lang").show();
		//$(this).find("a:eq(0)").addClass('hover');
	}, function() {
		$(this).css({ 'z-index' : 1 });
		$(this).find(".dd-lang").hide();
		//$(this).find("a:eq(0)").removeClass('hover');
	});
	
	// horizontal carousel
	var lastButton = $("#active");
	var maxWidth = 458;
	var minWidth = 227;

    $(".buttons .btn").hover(function() {
    	
	// show this
	switch ($(".buttons .btn").index(this)) {
	    	case 0: $(this).addClass("button1max"); $(this).removeClass("button1min"); break;
    		case 1: $(this).addClass("button2max"); $(this).removeClass("button2min"); break;
    		case 2: $(this).addClass("button3max"); $(this).removeClass("button3min"); break;
    		case 3: $(this).addClass("button4max"); $(this).removeClass("button4min"); break;
    	}
	$(this).addClass("hover");
	$(this).animate({width: maxWidth+"px"}, { queue:false, duration:400 });
		
	lastButton = this;
    }, function() {
    	// hide previous
        $(lastButton).animate({width: minWidth+"px"}, { queue:false, duration:400 });

	switch ($(".buttons .btn").index(this)) {
	    	case 0: $(this).removeClass("button1max").addClass("button1min"); break;
	    	case 1: $(this).removeClass("button2max").addClass("button2min"); break;
	    	case 2: $(this).removeClass("button3max").addClass("button3min"); break;
	    	case 3: $(this).removeClass("button4max").addClass("button4min"); break;
    	}

    	$(".buttons .btn").removeClass("hover");

	
    });


	
	// smooth scrolling code
	
	$(function() {
	
		function filterPath(string) {
			return string
			.replace(/^\//,'')
			.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
			.replace(/\/$/,'');
		}
	
		var locationPath = filterPath(location.pathname);
		var scrollElem = scrollableElement('html', 'body');
	
		// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
		$('a[href*=#]').each(function() {

			// Ensure it's a same-page link
			var thisPath = filterPath(this.pathname) || locationPath;
			if (  locationPath == thisPath
			&& (location.hostname == this.hostname || !this.hostname)
			&& (!($(this).hasClass('noscroll')))
			&& this.hash.replace(/#/,'') ) {
	
				// Ensure target exists
				var $target = $(this.hash), target = this.hash;
				if ((target) && $target.offset()) { // offset() has to exist.
	
					// Find location of target
					var targetOffset = $target.offset().top;
					$(this).click(function(event) {
	
						// Prevent jump-down
						event.preventDefault();
	
						// Animate to target
						$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
	
							// Set hash in URL after animation successful
							location.hash = target;
	
						});
					});
				}
			}
	
		});
	
		// Use the first element that is "scrollable"  (cross-browser fix?)
		function scrollableElement(els) {
			for (var i = 0, argLength = arguments.length; i <argLength; i++) {
				var el = arguments[i],
				$scrollElement = $(el);
				if ($scrollElement.scrollTop()> 0) {
					return el;
				} else {
					$scrollElement.scrollTop(1);
					var isScrollable = $scrollElement.scrollTop()> 0;
					$scrollElement.scrollTop(0);
					if (isScrollable) {
						return el;
					}
				}
			}
			return [];
		}
	
	});
    
    // accordion
	$(".content-holder .tab-content").each(function () {$(this).removeClass("hide");});
	
	$(".tab-content").accordion({
		header : "a.header",
		change: function(event, ui) { 
			$(ui.newHeader).removeClass("border");
			
			if ($(".tab-content a.header").index(ui.oldHeader) != $(".tab-content a.header").length - 1) {$(ui.oldHeader).addClass("border");}
		 }
	});
	
	// this makes the header links clickable when expanded:
	// basically, you check for a click, then check to see if it's a click on a TALL li,
	// and if so, follow the link.
	// it's a hack because otherwise, ALL clicks on an active link will go to a new page
	$('a.ui-state-active').live('click', function() {
		if ($(this).parent().height() > 80 ) {
			$(".tab-content").accordion('disable');
			window.location = $(this).attr('href');
		
			setTimeout ( function() {$(".tab-content").accordion('enable');}, 250 );
		}
	});

	$(".content-holder .tab-content").each(function () {$(this).addClass("hide");});
	$(".content-holder .tab-content").eq(0).removeClass("hide");
	
	// tab
	$(".tab-holder a").click(function () {
		
		$(".tab-holder a").each(function () {$(this).removeClass("active");});
		$(this).addClass("active");
		
		$(".content-holder .tab-content").each(function () {$(this).addClass("hide");});
		
		$(".content-holder .tab-content").eq($(".tab-holder a").index(this)).removeClass("hide");
	});
	
	$(".go1").click(function () {
		
		$(".welcome-video").hide();
		$(".welcome-usmap").show();
		$(".welcome-global").hide();
		$('.go1').addClass("active");
		$('.go2').removeClass("active");
		return false;
		
	});
	
	$(".go2").click(function () {
		
		$(".welcome-video").hide();
		$(".welcome-usmap").hide();
		$(".welcome-global").show();
		$('.go1').removeClass("active");
		$('.go2').addClass("active");
		return false;
		
	});
	
	$("#welcome-link").fancybox({
			'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'overlayOpacity'	: .8,
			'overlayColor'		: '#000'
	});
	
	$("#founder, #comm-image, #article-image").fancybox({
			'titlePosition'		: 'inside',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'overlayOpacity'	: .8,
			'overlayColor'		: '#000'
	});
	
	$(document).bind("custom", function () {$("#welcome-link").click();});

	$(".closebox").click(function () {
		$.fancybox.close();
		return false;
	});	

	// the home page small map links weren't working...
	// this is a fix.
	$(".smallmap").click(function () {
		district = $(this).attr('district');
		$('#loc').val(district);
		$('#set_form').submit();
		return false;
		// This makes the small map link to a page.  
//		window.setTimeout(function() {
//			window.location = $(this).attr('href');
//		}, 900);
	});	

	//tooltip
	$('area').tooltip({ 
	    track: true, 
	    delay: 0, 
	    showURL: false, 
	    showBody: " - ", 
	    fade: 250 
	});
	
	var i = 0;
	$('.region').each(function(){
		$('.region').eq(i).attr('index', i);
		i++;
	});
	
	
	
	$(".districtmaplink").click(function () {
		var index = $(".districtmaplink").index(this);
		var removed = $(".region[index="+ index +"]").remove();
		
		$('.regions').prepend( removed );
		
		return false;
	});
	
	/******************************************************************/
	// slide box
	$('.box-slide').hover(function () {
		$(this).find('.shadow .content').slideDown();
	}, function () {
		$(this).find('.shadow .content').slideUp();
	});
	//sub nav dd
	$(".sub-nav ul li").hover(function() {
		$(this).css({ 'z-index' : 100 });
		$(this).find(".dd").show();
	}, function() {
		$(this).css({ 'z-index' : 1 });
		$(this).find(".dd").hide();
	});
	
	$('.article-incr').click(function () {
		var fontSize = $('.article-text p').css('font-size').replace('px','');
		fontSize++;
		$('.article-text p').css('font-size', fontSize)
		var fontSize2 = $('.article-text ul').css('font-size').replace('px','');
		fontSize2++;
		$('.article-text ul').css('font-size', fontSize2)
		return false;
	});
	$('.article-decr').click(function () {
		var fontSize = $('.article-text p').css('font-size').replace('px','');
		fontSize--;
		$('.article-text p').css('font-size', fontSize)
		var fontSize2 = $('.article-text ul').css('font-size').replace('px','');
		fontSize2--;
		$('.article-text ul').css('font-size', fontSize2)
		return false;
	});
	
	$('.close').click(function () {
		$('.headlines').slideUp();
		$.cookie('exp_seen_breaking', 1, { expires: 1, path: '/' }); // expires in a day
		return false;
	});
	$('.close2').click(function () {
		$('.headlines2').slideUp();
		$.cookie('exp_no_mobile', 1, { expires: 7, path: '/' }); // expires in a week
		return false;
	});
	
	// schedule tabs
	$('.tab-schedule').hide();
	$('.tab-schedule:eq(0)').show();
	
	$('.schedule .tabs-holder .tab').click(function () {
		$('.schedule .tabs-holder .tab h2').removeClass('tab-active');
		$(this).find('h2').addClass('tab-active');
		
		$('.tab-schedule').hide();
		var index = $('.schedule .tabs-holder .tab').index(this);
		$('.tab-schedule').eq(index).show();
		return false;
	});

	
	// masthead tabs
	// functionality disabled
	/*
	$('.masthead .tabs a:eq(0)').addClass('active');
	$('.tab-content-i:eq(0)').show();
	
	$('.masthead .tabs a').click(function () {
		$('.masthead .tabs a').removeClass('active');
		$(this).addClass('active');
		
		$('.tab-content-i').hide();
		$('.tab-content-i').eq($(this).index('.masthead .tabs a')).show();
		
		return false;
	});
	*/


	// Loading the single page

	// when you click on a single page link, fetch the whole body and insert it...
	$('.single-page').click(function(){
		// get current URL
		currentURL = document.URL;
		// replace one part of it
		newURL = currentURL.replace('article','article_single_page');
		$('#article-text-outer').load(newURL);
		$('.pager').hide(); // hide pagination when this loads
		$('.single-page-wrapper').hide(); // hide link, too, this loads
		$('.size-label').show(); // hide pagination when this loads
	});

	// this function controls the forms that lookup the district by zip code of district id
	// if the form is given the "news" class,  the form will go to the news  page on completion;
	// if the form is given the "about" class, the form will go to the about page on completion;
	// if the form is given the "mobile" class, the form will go to the mobile page on completion;
	// otherwise, it just reloads the existing page.
	$('.set_district').submit(function(){
		thisform = $(this);
		$.post('/site/set_district', $(this).serialize(), function(data){ // serialize takes the data in the form, and passes it to the POST function

			// data is returned in JSON format?
			cookie_value = data.district_name + ':' + data.district_url_title + ':' + data.district_id ;
			$.cookie('exp_district', cookie_value, { expires: 365, path: '/' });

			// data comes back in JSON format, ready to be parsed
			$('#district_location').html('<a href="/about/districts/' + data.district_url_title + '">' + data.district_name + ' District</a>');

			if (data.district_url_title == "") {
				alert ("Sorry, we can't find a district that matches that value.");
			}
			else
			{
				if (thisform.hasClass('news')) {
					window.setTimeout(function() {
						newspage = 	'/news/district/c/' + data.district_url_title;
						window.location = newspage;
					}, 700);
				}
				else if (thisform.hasClass('about')) {
					window.setTimeout(function() {
						newspage = 	'/about/district/' + data.district_url_title;
						window.location = newspage;
					}, 700);
				}
				else if (thisform.hasClass('mobile')) {
					window.setTimeout(function() {
						newspage = 	'/mobile/district/' + data.district_url_title;
						window.location = newspage;
					}, 700);
				}
				else
				{
					window.setTimeout(function() {location.reload();}, 700);
				}
			}

		}, "json");
		return false;
	});

	// this is for making links submit the district switching form
	$('.district_switch').click(function(){
		district = $(this).attr('district');
		$('#loc').val(district);
		$('#set_form').submit();
		return false;
	});

});


function cycle_before  (curr, next, opts) {
	// highlight the dot corresponding with this slide
	// do this by counting the number of items,
	dot_count = $(".nav .dot").length;
	// then adding 1 to the current slide and reset if greater than the number of items (modulo)
	$(".nav .dot").eq((opts.currSlide + 1) % dot_count).find("a").addClass("current");

	// 
//	Cufon.replace('.slider .text a', { fontFamily : 'Myriad Pro', fontSize: '46px' });
}

function cycle_after (curr, next, opts) {

	// unhighlight all dots
	$(".nav .dot").each(function () {$(this).find("a").removeClass("current");});

	// highlight the dot corresponding with this slide
	$(".nav .dot").eq(opts.currSlide).find("a").addClass("current");
	// console.log('count: ' + dot_count + ", " + (opts.currSlide + 1));
}

// trigger click





/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);



