eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(3($){7 m=\'2.12\';7 n=$.2z.2p&&/3z 6.0/.31(2P.2G);3 1t(){4(26.20&&26.20.1t)26.20.1t(\'[y] \'+3v.3p.3j.3b(36,\'\'))};$.B.y=3(l){K 9.1c(3(){l=l||{};4(l.2c==2y){3F(l){28\'3E\':4(9.U)22(9.U);9.U=0;K;28\'29\':9.17=1;K;28\'3w\':9.17=0;K;3u:l={1e:l}}}7 c=$(9);7 d=l.1R?$(l.1R,9):c.3g();7 e=d.38();4(e.C<2){1t(\'33; 30 2X 2V: \'+e.C);K}7 f=$.2O({},$.B.y.2q,l||{},$.2d?c.2d():$.2H?c.2F():{});4(f.1P)f.1O=f.1N||e.C;f.G=f.G?[f.G]:[];f.14=f.14?[f.14]:[];f.14.2x(3(){f.2a=0});4(f.1k)f.14.H(3(){1d(e,f,0,!f.1b)});4(n&&f.1I&&!f.2t)27(d);7 g=9.3D;f.r=1p((g.1G(/w:(\\d+)/)||[])[1])||f.r;f.8=1p((g.1G(/h:(\\d+)/)||[])[1])||f.8;f.N=1p((g.1G(/t:(\\d+)/)||[])[1])||f.N;4(c.A(\'1A\')==\'3s\')c.A(\'1A\',\'3o\');4(f.r)c.r(f.r);4(f.8&&f.8!=\'1D\')c.8(f.8);4(f.1a){f.1i=[];1n(7 i=0;i<e.C;i++)f.1i.H(i);f.1i.3f(3(a,b){K 39.1a()-0.5});f.18=0;f.W=f.1i[0]}13 4(f.W>=e.C)f.W=0;7 h=f.W||0;d.A(\'1A\',\'2f\').1y().1c(3(i){7 z=h?i>=h?e.C-(i-h):h-i:e.C-i;$(9).A(\'z-1B\',z)});$(e[h]).M();4(f.Z&&f.r)d.r(f.r);4(f.Z&&f.8&&f.8!=\'1D\')d.8(f.8);4(f.29)c.2U(3(){9.17=1},3(){9.17=0});7 j=$.B.y.L[f.1e];4($.2k(j))j(c,d,f);13 1t(\'2N 2L: \'+f.1e);d.1c(3(){7 a=$(9);9.V=(f.Z&&f.8)?f.8:a.8();9.S=(f.Z&&f.r)?f.r:a.r()});f.F=f.F||{};f.E=f.E||{};f.I=f.I||{};d.1w(\':1v(\'+h+\')\').A(f.F);4(f.T)$(d[h]).A(f.T);4(f.N){4(f.Q.2c==2y)f.Q={2E:2D,2C:2B}[f.Q]||2A;4(!f.1M)f.Q=f.Q/2;3I((f.N-f.Q)<3H)f.N+=f.Q}4(f.2b)f.1L=f.1K=f.2b;4(!f.1s)f.1s=f.Q;4(!f.1o)f.1o=f.Q;f.2v=e.C;f.11=h;4(f.1a){f.D=f.11;4(++f.18==e.C)f.18=0;f.D=f.1i[f.18]}13 f.D=f.W>=(e.C-1)?0:f.W+1;7 k=d[h];4(f.G.C)f.G[0].1J(k,[k,k,f,2u]);4(f.14.C>1)f.14[1].1J(k,[k,k,f,2u]);4(f.1r&&!f.P)f.P=f.1r;4(f.P)$(f.P).25(\'1r\',3(){K 21(e,f,f.1b?-1:1)});4(f.24)$(f.24).25(\'1r\',3(){K 21(e,f,f.1b?1:-1)});4(f.1q)2s(e,f);4(f.N||f.1k)9.U=23(3(){1d(e,f,0,!f.1b)},f.1k?10:f.N+(f.2r||0));f.3A=3(a){7 b=$(a),s=b[0];4(!f.1N)f.1O++;e.H(s);4(f.R)f.R.H(s);f.2v=e.C;b.A(\'1A\',\'2f\').A(f.F).2o(c);4(n&&f.1I&&!f.2t)27(b);4(f.Z&&f.r)b.r(f.r);4(f.Z&&f.8&&f.8!=\'1D\')d.8(f.8);s.V=(f.Z&&f.8)?f.8:b.8();s.S=(f.Z&&f.r)?f.r:b.r()}})};3 1d(a,b,c,d){4(b.2a)K;7 p=a[0].1H,1j=a[b.11],P=a[b.D];4(p.U===0&&!c)K;4(!c&&!p.17&&((b.1P&&(--b.1O<=0))||(b.1u&&!b.1a&&b.D<b.11))){4(b.1Z)b.1Z(b);K}4(c||!p.17){4(b.G.C)$.1c(b.G,3(i,o){o.1J(P,[1j,P,b,d])});7 e=3(){4($.2z.2p&&b.1I)9.3y.3x(\'1Y\');$.1c(b.14,3(i,o){o.1J(P,[1j,P,b,d])})};4(b.D!=b.11){b.2a=1;4(b.1F)b.1F(1j,P,b,e,d);13 4($.2k($.B.y[b.1e]))$.B.y[b.1e](1j,P,b,e);13 $.B.y.2m(1j,P,b,e)}4(b.1a){b.11=b.D;4(++b.18==a.C)b.18=0;b.D=b.1i[b.18]}13{7 f=(b.D+1)==a.C;b.D=f?0:b.D+1;b.11=f?a.C-1:b.D-1}4(b.1q)$(b.1q).2l(\'a\').3t(\'1W\').1Y(\'a:1v(\'+b.11+\')\').2j(\'1W\')}4(b.N&&!b.1k)p.U=23(3(){1d(a,b,0,!b.1b)},b.N);13 4(b.1k&&p.17)p.U=23(3(){1d(a,b,0,!b.1b)},10)};3 21(a,b,c){7 p=a[0].1H,N=p.U;4(N){22(N);p.U=0}b.D=b.11+c;4(b.D<0){4(b.1u)K 1E;b.D=a.C-1}13 4(b.D>=a.C){4(b.1u)K 1E;b.D=0}4(b.1x&&1U b.1x==\'3\')b.1x(c>0,b.D,a[b.D]);1d(a,b,1,c>=0);K 1E};3 2s(b,c){7 d=$(c.1q);$.1c(b,3(i,o){7 a=(1U c.1T==\'3\')?$(c.1T(i,o)):$(\'<a 3q="#">\'+(i+1)+\'</a>\');4(a.3n(\'3m\').C==0)a.2o(d);a.25(\'1r\',3(){c.D=i;7 p=b[0].1H,N=p.U;4(N){22(N);p.U=0}4(1U c.1S==\'3\')c.1S(c.D,b[c.D]);1d(b,c,1,!c.1b);K 1E})});d.2l(\'a\').1Y(\'a:1v(\'+c.W+\')\').2j(\'1W\')};3 27(b){3 1C(s){7 s=1p(s).3l(16);K s.C<2?\'0\'+s:s};3 2i(e){1n(;e&&e.3k.3i()!=\'3h\';e=e.1H){7 v=$.A(e,\'2h-2g\');4(v.3e(\'3d\')>=0){7 a=v.1G(/\\d+/g);K\'#\'+1C(a[0])+1C(a[1])+1C(a[2])}4(v&&v!=\'3c\')K v}K\'#3a\'};b.1c(3(){$(9).A(\'2h-2g\',2i(9))})};$.B.y.2m=3(a,b,c,d){7 e=$(a),$n=$(b);$n.A(c.F);7 f=3(){$n.1z(c.E,c.1s,c.1L,d)};e.1z(c.I,c.1o,c.1K,3(){4(c.O)e.A(c.O);4(!c.1M)f()});4(c.1M)f()};$.B.y.L={2e:3(a,b,c){b.1w(\':1v(\'+c.W+\')\').A(\'1m\',0);c.G.H(3(){$(9).M()});c.E={1m:1};c.I={1m:0};c.O={Y:\'X\'}}};$.B.y.37=3(){K m};$.B.y.2q={1e:\'2e\',N:35,1k:0,Q:34,1s:J,1o:J,P:J,24:J,1x:J,1q:J,1S:J,1T:J,G:J,14:J,1Z:J,2b:J,1L:J,1K:J,1l:J,E:J,I:J,F:J,O:J,1F:J,8:\'1D\',W:0,1M:1,1a:0,Z:0,29:0,1P:0,1N:0,2r:0,1R:J,1I:0,1u:0}})(q);q.B.y.L.32=3(d,e,f){d.A(\'19\',\'1h\');f.G.H(3(a,b,c){q(9).M();c.F.u=b.1g;c.I.u=0-a.1g});f.T={u:0};f.E={u:0};f.O={Y:\'X\'}};q.B.y.L.2Z=3(d,e,f){d.A(\'19\',\'1h\');f.G.H(3(a,b,c){q(9).M();c.F.u=0-b.1g;c.I.u=a.1g});f.T={u:0};f.E={u:0};f.O={Y:\'X\'}};q.B.y.L.2Y=3(d,e,f){d.A(\'19\',\'1h\');f.G.H(3(a,b,c){q(9).M();c.F.x=b.1f;c.I.x=0-a.1f});f.T={x:0};f.E={x:0}};q.B.y.L.2W=3(d,e,f){d.A(\'19\',\'1h\');f.G.H(3(a,b,c){q(9).M();c.F.x=0-b.1f;c.I.x=a.1f});f.T={x:0};f.E={x:0}};q.B.y.L.3r=3(f,g,h){f.A(\'19\',\'1h\').r();h.G.H(3(a,b,c,d){q(9).M();7 e=a.1f,1X=b.1f;c.F=d?{x:1X}:{x:-1X};c.E.x=0;c.I.x=d?-e:e;g.1w(a).A(c.F)});h.T={x:0};h.O={Y:\'X\'}};q.B.y.L.2T=3(f,g,h){f.A(\'19\',\'1h\');h.G.H(3(a,b,c,d){q(9).M();7 e=a.1g,1V=b.1g;c.F=d?{u:-1V}:{u:1V};c.E.u=0;c.I.u=d?e:-e;g.1w(a).A(c.F)});h.T={u:0};h.O={Y:\'X\'}};q.B.y.L.2S=3(a,b,c){c.E={r:\'M\'};c.I={r:\'1y\'}};q.B.y.L.2R=3(a,b,c){c.E={8:\'M\'};c.I={8:\'1y\'}};q.B.y.L.1l=3(g,h,j){7 w=g.A(\'19\',\'2Q\').r();h.A({x:0,u:0});j.G.H(3(){q(9).M()});j.Q=j.Q/2;j.1a=0;j.1l=j.1l||{x:-w,u:15};j.R=[];1n(7 i=0;i<h.C;i++)j.R.H(h[i]);1n(7 i=0;i<j.W;i++)j.R.H(j.R.2n());j.1F=3(a,b,c,d,e){7 f=e?q(a):q(b);f.1z(c.1l,c.1s,c.1L,3(){e?c.R.H(c.R.2n()):c.R.2x(c.R.2M());4(e)1n(7 i=0,1Q=c.R.C;i<1Q;i++)q(c.R[i]).A(\'z-1B\',1Q-i);13{7 z=q(a).A(\'z-1B\');f.A(\'z-1B\',1p(z)+1)}f.1z({x:0,u:0},c.1o,c.1K,3(){q(e?9:a).1y();4(d)d()})})}};q.B.y.L.3B=3(d,e,f){f.G.H(3(a,b,c){q(9).M();c.F.u=b.V;c.E.8=b.V});f.T={u:0};f.F={8:0};f.E={u:0};f.I={8:0};f.O={Y:\'X\'}};q.B.y.L.3C=3(d,e,f){f.G.H(3(a,b,c){q(9).M();c.E.8=b.V;c.I.u=a.V});f.T={u:0};f.F={u:0,8:0};f.I={8:0};f.O={Y:\'X\'}};q.B.y.L.2K=3(d,e,f){f.G.H(3(a,b,c){q(9).M();c.F.x=b.S;c.E.r=b.S});f.F={r:0};f.E={x:0};f.I={r:0};f.O={Y:\'X\'}};q.B.y.L.2J=3(d,e,f){f.G.H(3(a,b,c){q(9).M();c.E.r=b.S;c.I.x=a.S});f.F={x:0,r:0};f.E={x:0};f.I={r:0};f.O={Y:\'X\'}};q.B.y.L.2I=3(d,e,f){f.T={u:0,x:0};f.O={Y:\'X\'};f.G.H(3(a,b,c){q(9).M();c.F={r:0,8:0,u:b.V/2,x:b.S/2};c.E={u:0,x:0,r:b.S,8:b.V};c.I={r:0,8:0,u:a.V/2,x:a.S/2}})};q.B.y.L.3G=3(d,e,f){f.G.H(3(a,b,c){c.F={r:0,8:0,1m:1,x:b.S/2,u:b.V/2,2w:1};c.E={u:0,x:0,r:b.S,8:b.V}});f.I={1m:0};f.O={2w:0}};',62,231,'|||function|if|||var|height|this|||||||||||||||||jQuery|width|||top|||left|cycle||css|fn|length|nextSlide|animIn|cssBefore|before|push|animOut|null|return|transitions|show|timeout|cssAfter|next|speed|els|cycleW|cssFirst|cycleTimeout|cycleH|startingSlide|none|display|fit||currSlide||else|after|||cyclePause|randomIndex|overflow|random|rev|each|go|fx|offsetWidth|offsetHeight|hidden|randomMap|curr|continuous|shuffle|opacity|for|speedOut|parseInt|pager|click|speedIn|log|nowrap|eq|not|prevNextClick|hide|animate|position|index|hex|auto|false|fxFn|match|parentNode|cleartype|apply|easeOut|easeIn|sync|autostopCount|countdown|autostop|len|slideExpr|pagerClick|pagerAnchorBuilder|typeof|nextH|activeSlide|nextW|filter|end|console|advance|clearTimeout|setTimeout|prev|bind|window|clearTypeFix|case|pause|busy|easing|constructor|metadata|fade|absolute|color|background|getBg|addClass|isFunction|find|custom|shift|appendTo|msie|defaults|delay|buildPager|cleartypeNoBg|true|slideCount|zIndex|unshift|String|browser|400|200|fast|600|slow|data|userAgent|meta|zoom|turnRight|turnLeft|transition|pop|unknown|extend|navigator|visible|slideY|slideX|scrollVert|hover|slides|scrollRight|few|scrollLeft|scrollDown|too|test|scrollUp|terminating|1000|4000|arguments|ver|get|Math|ffffff|call|transparent|rgb|indexOf|sort|children|html|toLowerCase|join|nodeName|toString|body|parents|relative|prototype|href|scrollHorz|static|removeClass|default|Array|resume|removeAttribute|style|MSIE|addSlide|turnUp|turnDown|className|stop|switch|fadeZoom|250|while'.split('|'),0,{}));

/**
 * @author jcrane
 * @contact AIM: jcranefwst
 */

var geoNews = {
	// add toggler for user to change area or ZIP code
	addChiclet: function() {
		optionsTarget = $('#geo_check').closest('div.grid_module');
		$('<div id="geo_options"/>').prependTo(optionsTarget).html('<span class="change_area">Change area</span><span class="ui-icon ui-icon-wrench">c</span>');
		// listen for click on the options toggler and hide or show the forms as required
		$('#geo_options').bind('click', function(event){
			// $('#option_toggle').text('Hide options' ? 'Show options' : 'Hide options');
			$('#geo_check').slideToggle();
		});	
	},
	
	isZipGood: function(areas, inputZip) {
		for (var area in areas) {
			if (areas.hasOwnProperty(area)) {
				for (var zip in areas[area].zips) { //['zips']
					isZip = areas[area]['zips'][zip];
					if (isZip == inputZip) {
						path = areas[area]['path'];
						name = areas[area]['name'];
						return [area, name, path];
					}
				}
			}
		}
	},
	
	// check cookied geo or zip code against arrays
	zipCookie: function(userArea){
		areaCookie = geoNews.areaCheck(userArea);
		if (areaCookie) {
			name = areaCookie[1];
			path = areaCookie[2];
			geoNews.addGeo(userArea, name, path);
		}
	},
	
	areaCheck: function(userArea) {
		var areas = geoNews.areas;
			for(var area in areas) {
				if (area == userArea) {
					path = areas[area]['path'];
					name = areas[area]['name'];
					return [area, name, path];
				}
			}
	},
	// function to control replacing headlines with a different set
	replaceGeo: function(){
		// when the select is changed
		$('#geo_select').change(function(){
			// grab the value to determine the geo
			var geo = $(this).val();
			// alert('replaceGeo geo is ' + geo);
			// loop through areas object to get the name
			var areas = geoNews.areas;
			for(var area in areas) {
				if (area == geo) {
					path = areas[area]['path'];
					name = areas[area]['name'];
					geoNews.addGeo(area, name, path);
				}
			} 
		});
	},
	cleanUp: function() {
		$('#geo_select option:first').attr('selected','selected');
	},
	// function to add geo headlines
	addGeo: function(area, name, path, zip){	
		$geoHeads = $('#geo-headlines');
		if ($geoHeads.hasClass(area)) {
			$geoHeads.effect('highlight');
			// geoNews.toggleOptions();
			geoNews.cleanUp();
		}
		else {
			height = $geoHeads.height();
			$geoHeads.height(height).text('Loading ...');
			// $geoHeads.fadeOut();
			loadPath = '/' + path + '/v-top_headlines/index.html';
			//console.log('loadPath is ' + loadPath);
			$geoHeads.load(loadPath, function(response, status, xhr){
				if (status == 'error') {
					var msg = 'Sorry, there was an error retrieving your headlines. Please try again momentarily.';
					$geoHeads.html(msg + xhr.status + " " + xhr.statusText);
				}
				else {
					$(this).effect('highlight').height('auto').attr('class','').addClass(area).closest('.grid_module_content').siblings('ul.tab_links').find('li:first span').html('<span class="hyper-label">My headlines</span> <span class="hyper-city">' + name + '</span>');
					$(this).find('.more_stories').children('a').text('More news from ' + name);
					geoNews.clickTrack(area);
					geoNews.toggleOptions();
					geoNews.geoCookie(area);
					geoNews.cleanUp();
				}
			});
		}
	},
	// grab each of the links in geo-headlines and add the #my-headlines query string after it, for tracking
	clickTrack : function(area) {
		$('#geo-headlines').find('a').map(function() {
			var my_link = $(this).attr('href');
			return $(this).attr('href',my_link + '#my-headlines-' + area);
		})
	},
	toggleOptions: function() {
		$('#geo_check').slideToggle();
	},
	
	// create cookie with the user's selected geo
	geoCookie: function(area){
		$.cookie('st_area_headlines', area, {
			expires: 365,
			path: '/'
		}); 
	},
	
	// initialize the geo functionality
	init: function(){
		// this is currently set up to run in an html module in site manager (or possibly a page element)
		// running it from html module makes it more difficult through the cms to call init from their
		// so it is being called from document ready
		// therefore, added this check for a length on #geo-check jQuery object, which is included in html module or pe
		// probably should check for it anyway
		$geoCheck = $('#geo_check');
		if ($geoCheck.length) {
			// nothing server side, this only works with javascript, therefore hiding the forms unless js is enabled
			$geoCheck.removeClass('ui-helper-hidden');
			// look for user_zip cookie
			var userArea = $.cookie('st_area_headlines');
			// initialize submit and change listeners on forms
			this.zipSubmit();
			this.replaceGeo();
			// add options div to toggle forms to change area
			this.addChiclet();
			// if cookie exists
			if (userArea) {
				geoNews.zipCookie(userArea);
			}
			else {
				// add my-headlines query string on initial load
				geoNews.clickTrack('default');
			}
		}
	},
	// listen for form's submit event
	zipSubmit : function() {
		// cache geo-zipper as variable
		var $geoZipper = $('#geo_zipper');
		$geoZipper.submit( function(event){
			// prevent browser form submit from firing
			event.preventDefault();
			// get the zip that was entered
			zip = $('#zip_text').val(); 
			// if the zip isn't numbers or isn't five digits, request a valid zip code
			// TODO => give immediate feedback for zips longer than five digits
			if (zip.match(/\D/g) || !zip.match(/^\d{5}$/)) {
				alert("Please enter a valid 5-digit ZIP code.");
				return false;
			}
			// if it's a good zip code, check if we have headlines for it
			else {
				//check for zip in areas object
				var isZipGood = geoNews.isZipGood(geoNews.areas, zip);
				if (isZipGood) {
					// grab the area, name and path returned by isZipGood()
					// and send to addGeo();
					var area = isZipGood[0];
					var name = isZipGood[1];
					var path = isZipGood[2];
					geoNews.addGeo(area, name, path, zip);
				}
				else {
					alert('Sorry, it doesn\'t appear that we have headlines for that ZIP code.');
				}	
			}
		});
		// TODO => might want to figure out something to do with invalid ZIP code before user submits form
		/* $geoZipper.change(function() {
			zip = $('#zip_text').val();
			if (zip.match(/\D/g) || !zip.match(/^\d{5}$/)) {
				$('#zip_text').css('background-color','red');
			}
		}); */
	}
};
// areas object defines an area, name, server path and the zip codes associated with that area
geoNews.areas = {
   'arlington': {
      'name': 'Arlington',
      'path': 'arlington',
      'zips': ['75050', 75051, 75052, 75053, 75054, 76010, 76011, 76012, 76013, 76014, 76015, 76016, 76017, 76018, 76006]
   },
   'northeast': {
      'name': 'Northeast',
      'path': 'northeast',
      'zips': [76117, 76111, 76053, 76022, 76021, 76039, 76040, 76054, 76180, 76118, 76182, 75022, 75077, 75057, 75028, 75067, 76262, 75062, 75038, 75061, 75014, 75015, 75016, 75017, 75037, 75039, 75060, 76201, 76205, 76209, 76208, 76071]
   },
   'mansfield': {
      'name': 'Mansfield',
	  'paper': 'Mansfield News Mirror',
      'path': 'mansfieldnewsmirror/news',
      'zips': [76063, 76060]
   },
   'weatherford': {
      'name': 'Weatherford',
      'path': 'weatherfordtelegram/news',
      'zips': [76086, 76087]
   },
   'southlake': {
      'name': 'Southlake',
      'path': 'southlakejournal/news',
      'zips': [76092]
   },
   'alliance': {
      'name': 'Alliance',
      'path': 'timesregister/news',
      'zips': [76247, 76226, 76177]
   },
   'colleyville': {
      'name': 'Colleyville',
      'path': 'colleyvillecourier/news',
      'zips': [76034]
   },
   'grapevine': {
      'name': 'Grapevine',
      'path': 'grapevinecourier/news',
      'zips': [76051]
   },
   'keller': {
      'name': 'Keller',
      'path': 'kellercitizen/news',
      'zips': [76148, 76248]
   },
   'fortworth': {
      'name': 'Fort Worth',
      'path': 'fortworth',
      'zips': [76101,76102,76103,76104,76105,76106,76107,76108,76109,76110,76111,76112,76113,76114,76115,76116,76118,76119,76120,76121,76122,76123,76124,76126,76129,76130,76131,76132,76133,76134,76135,76136,76137,76140,76147,76148,76150,76155,76161,76162,76163,76164,76177,76178,76179,76181,76185,76191,76192,76193,76195,76196,76197,76198,76199]
   },
   'dallas': {
      'name': 'Dallas',
      'path': 'dallas',
      'zips': [75201, 75202, 75205, 75218, 75214, 75206, 75225, 75230, 75207, 75001, 75231, 75243, 75254, 75240, 75248, 75252, 75080, 75081, 75082, 75083, 75085, 75034, 75035, 75023, 75024, 75025, 75026, 75074, 75075, 75086, 75093, 75094, 75069, 75070, 75071, 75002, 75013, 75203, 75208, 75216, 75232, 75040, 75041, 75042, 75043, 75044, 75045, 75047, 75048, 75049, 75046, 75149, 75150, 75180, 75181, 75182, 75185, 75187, 75030, 75088, 75089, 75032, 75087, 75159, 75134, 75146, 75116, 75137, 75138, 75115, 75123]
   },
   'other': {
      'name': 'Other areas',
      'path': 'fortworth',
      'zips': [76028, 76097, 76008, 76067, 76259, 76234, 76271, 76266, 76048, 76049, 76043, 76058, 76033, 76031, 76009, 76401, 76645, 75165, 75167, 76065, 75119, 76008, 76009, 76031, 76033, 76058, 76234, 76259, 76271, 75119, 76043, 76048, 76049, 76645, 76065, 76067, 76266, 76401, 75165, 75167, 76086, 76087]
   }
}; 

// would be better to call this from the page where this widget exists, but calling here
// since it's in an HTML module in SiteManager rather than a component in the templates
jQuery(document).ready(function() {
	geoNews.init(); 
});/* @minify true */
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);/**
 * Cookie plugin
 * @minify true
 * 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;
    }
};/* @minify true */
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);
/*
 * jQuery Galleriffic plugin
 * @minify true
 * Copyright (c) 2008 Trent Foley (http://trentacular.com)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Thanks to Taku Sano (Mikage Sawatari), whose history plugin I adapted to work with Galleriffic
 * Modified by Ghismo (ghismo.com) to disable the location rewrite 
 */
;(function($) {

	// Write noscript style
	document.write("<style type='text/css'>.noscript{display:none}</style>");

	var ver = 'galleriffic-1.0';
	var galleryOffset = 0;
	var galleries = [];
	var allImages = [];	
	var historyCurrentHash;
	var historyBackStack;
	var historyForwardStack;
	var isFirst = false;
	var dontCheck = false;
	var isInitialized = false;

	function getHashFromString(hash) {
		if (!hash) return -1;
		hash = hash.replace(/^.*#/, '');
		if (isNaN(hash)) return -1;
		return (+hash);
	}

	function getHash() {
		var hash = location.hash;
		return getHashFromString(hash);
	}

	function registerGallery(gallery) {
		galleries.push(gallery);

		// update the global offset value
		galleryOffset += gallery.data.length;
	}

	function getGallery(hash) {
		for (i = 0; i < galleries.length; i++) {
			var gallery = galleries[i];
			if (hash < (gallery.data.length+gallery.offset))
				return gallery;
		}
		return 0;
	}
	
	function getIndex(gallery, hash) {
		return hash-gallery.offset;
	}
	
	function clickHandler(e, gallery, link) {
		gallery.pause();

		if (!gallery.settings.enableHistory) {
			var hash = getHashFromString(link.href);
			if (hash >= 0) {
				var index = getIndex(gallery, hash);
				if (index >= 0)
					gallery.goto(index);
			}
			e.preventDefault();
		}
	}

	function historyCallback() {
		// Using present location.hash always (seems to work, unlike the hash argument passed to this callback)
		var hash = getHash();
		if (hash < 0) return;

		var gallery = getGallery(hash);
		if (!gallery) return;
		
		var index = hash-gallery.offset;
		gallery.goto(index);
	}
	
	function historyInit() {
		if (isInitialized) return;
		isInitialized = true; 

		var current_hash = location.hash; //(enableHistory) ? location.hash : currentIndexHash; // Ghismo

		historyCurrentHash = current_hash;
		if ($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (historyCurrentHash == '') {
				historyCurrentHash = '#';
			}
		} else if ($.browser.safari) {
			// etablish back/forward stacks
			historyBackStack = [];
			historyBackStack.length = history.length;
			historyForwardStack = [];
			isFirst = true;
		}

		setInterval(function() { historyCheck(); }, 100);
	}
	
	function historyAddHistory(hash) {
		// This makes the looping function do something
		historyBackStack.push(hash);
		historyForwardStack.length = 0; // clear forwardStack (true click occured)
		isFirst = true;
	}
	
	function historyCheck() {
		if ($.browser.safari) {
			if (!dontCheck) {
				var historyDelta = history.length - historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) historyForwardStack.unshift(historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) historyBackStack.push(historyForwardStack.shift());
					}
					var cachedHash = historyBackStack[historyBackStack.length - 1];
					if (cachedHash != undefined) {
						historyCurrentHash = location.hash; // (enableHistory) ? location.hash : currentIndexHash; // Ghismo
						historyCallback();
					}
				} else if (historyBackStack[historyBackStack.length - 1] == undefined && !isFirst) {
					historyCallback();
					isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash; // (enableHistory) ? location.hash : currentIndexHash; // Ghismo
			if(current_hash != historyCurrentHash) {
				historyCurrentHash = current_hash;
				historyCallback();
			}
		}
	}

	var defaults = {
		delay:                  3000,
		numThumbs:              20,
		preloadAhead:           40, // Set to -1 to preload all images
		enableTopPager:         false,
		enableBottomPager:      true,
		imageContainerSel:      '',
		captionContainerSel:    '',
		controlsContainerSel:   '',
		loadingContainerSel:    '',
		renderSSControls:       true,
		renderNavControls:      true,
		playLinkText:           'Play',
		pauseLinkText:          'Pause',
		prevLinkText:           'Previous',
		nextLinkText:           'Next',
		nextPageLinkText:       'Next &rsaquo;',
		prevPageLinkText:       '&lsaquo; Prev',
		enableHistory:          false,
		autoStart:              false,
		onChange:               undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
		onTransitionOut:        undefined, // accepts a delegate like such: function(callback) { ... }
		onTransitionIn:         undefined, // accepts a delegate like such: function() { ... }
		onPageTransitionOut:    undefined, // accepts a delegate like such: function(callback) { ... }
		onPageTransitionIn:     undefined  // accepts a delegate like such: function() { ... }
	};

	$.fn.galleriffic = function(thumbsContainerSel, settings) {
		//  Extend Gallery Object
		$.extend(this, {
			ver: function() {
				return ver;
			},

			initializeThumbs: function() {
				this.data = [];
				var gallery = this;
				
				this.$thumbsContainer.find('ul.thumbs > li').each(function(i) {
					var $li = $(this);
					var $aThumb = $li.find('a.thumb');
					var hash = gallery.offset+i;

					gallery.data.push({
						title:$aThumb.attr('title'),
						slideUrl:$aThumb.attr('href'),
						caption:$li.find('.caption').remove(),
						hash:hash
					});

					// Setup history
					$aThumb.attr('rel', 'history');
					$aThumb.attr('href', '#'+hash);
					$aThumb.click(function(e) {
						clickHandler(e, gallery, this);
					});
				});
				return this;
			},

			isPreloadComplete: false,

			preloadInit: function() {
				if (this.settings.preloadAhead == 0) return this;
				
				this.preloadStartIndex = this.currentIndex;
				var nextIndex = this.getNextIndex(this.preloadStartIndex);
				return this.preloadRecursive(this.preloadStartIndex, nextIndex);
			},
			
			preloadRelocate: function(index) {
				// By changing this startIndex, the current preload script will restart
				this.preloadStartIndex = index;
				return this;
			},

			preloadRecursive: function(startIndex, currentIndex) {
				// Check if startIndex has been relocated
				if (startIndex != this.preloadStartIndex) {
					var nextIndex = this.getNextIndex(this.preloadStartIndex);
					return this.preloadRecursive(this.preloadStartIndex, nextIndex);
				}

				var gallery = this;

				// Now check for preloadAhead count
				var preloadCount = currentIndex - startIndex;
				if (preloadCount < 0)
					preloadCount = this.data.length-1-startIndex+currentIndex;
				if (this.settings.preloadAhead >= 0 && preloadCount > this.settings.preloadAhead) {
					// Do this in order to keep checking for relocated start index
					setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
					return this;
				}

				var imageData = this.data[currentIndex];
				if (!imageData)
					return this;

				// If already loaded, continue
				if (imageData.image)
					return this.preloadNext(startIndex, currentIndex); 
				
				// Preload the image
				var image = new Image();
				
				image.onload = function() {
					imageData.image = this;
					gallery.preloadNext(startIndex, currentIndex);
				};

				image.alt = imageData.title;
				image.src = imageData.slideUrl;

				return this;
			},
			
			preloadNext: function(startIndex, currentIndex) {
				var nextIndex = this.getNextIndex(currentIndex);
				if (nextIndex == startIndex) {
					this.isPreloadComplete = true;
				} else {
					// Use set timeout to free up thread
					var gallery = this;
					setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
				}
				return this;
			},

			getNextIndex: function(index) {
				var nextIndex = index+1;
				if (nextIndex >= this.data.length)
					nextIndex = 0;
				return nextIndex;
			},
			
			getPrevIndex: function(index) {
				var prevIndex = index-1;
				if (prevIndex < 0)
					prevIndex = this.data.length-1;
				return prevIndex;
			},

			pause: function() {
				if (this.interval)
					this.toggleSlideshow();
				
				return this;
			},

			play: function() {
				if (!this.interval)
					this.toggleSlideshow();
				
				return this;
			},

			toggleSlideshow: function() {
				if (this.interval) {
					clearInterval(this.interval);
					this.interval = 0;
					
					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls a').removeClass().addClass('play')
							.attr('title', this.settings.playLinkText)
							.attr('href', '#play')
							.html(this.settings.playLinkText);
					}
				} else {
					this.ssAdvance();

					var gallery = this;
					this.interval = setInterval(function() {
						gallery.ssAdvance();
					}, this.settings.delay);
					
					if (this.$controlsContainer) {
						this.$controlsContainer
							.find('div.ss-controls a').removeClass().addClass('pause')
							.attr('title', this.settings.pauseLinkText)
							.attr('href', '#pause')
							.html(this.settings.pauseLinkText);
					}
				}

				return this;
			},

			ssAdvance: function() {
				var nextIndex = this.getNextIndex(this.currentIndex);
				var nextHash = this.data[nextIndex].hash;

				// Seems to be working on both FF and Safari
				if (this.settings.enableHistory)
					location.href = '#'+nextHash;
				else
					this.goto(nextIndex);

				// IE we need to explicity call goto
				//if ($.browser.msie) {
				//	this.goto(nextIndex);
				//}

				return this;
			},

			goto: function(index) {
				if (index < 0) index = 0;
				else if (index >= this.data.length) index = this.data.length-1;
				
				if (this.settings.onChange)
					this.settings.onChange(this.currentIndex, index);
				
				this.currentIndex = index;
				this.preloadRelocate(index);
				return this.refresh();
			},
			
			refresh: function() {
				var imageData = this.data[this.currentIndex];
				if (!imageData)
					return this;
				
				// Flag we are transitioning
				var isTransitioning = true;

				var gallery = this;

				var transitionOutCallback = function() {
					// Flag that the transition has completed
					isTransitioning = false;

					// Update Controls
					if (gallery.$controlsContainer) {
						gallery.$controlsContainer
							.find('div.nav-controls a.prev').attr('href', '#'+gallery.data[gallery.getPrevIndex(gallery.currentIndex)].hash).end()
							.find('div.nav-controls a.next').attr('href', '#'+gallery.data[gallery.getNextIndex(gallery.currentIndex)].hash);
					}

					var imageData = gallery.data[gallery.currentIndex];

					// Replace Caption
					if (gallery.$captionContainer) {
						gallery.$captionContainer.empty().append(imageData.caption);
					}

					if (imageData.image) {
						gallery.buildImage(imageData.image);
					} else {
						// Show loading container
						if (gallery.$loadingContainer) {
							gallery.$loadingContainer.show();
						}
					}
				}

				if (this.settings.onTransitionOut) {
					this.settings.onTransitionOut(transitionOutCallback);
				} else {
					this.$transitionContainers.hide();
					transitionOutCallback();
				}

				if (!imageData.image) {
					var image = new Image();
					
					// Wire up mainImage onload event
					image.onload = function() {
						imageData.image = this;

						if (!isTransitioning) {
							gallery.buildImage(imageData.image);
						}
					};

					// set alt and src
					image.alt = imageData.title;
					image.src = imageData.slideUrl;
				}

				// This causes the preloader (if still running) to relocate out from the currentIndex
				this.relocatePreload = true;

				return this.syncThumbs();
			},
			
			buildImage: function(image) {
				if (this.$imageContainer) {
					this.$imageContainer.empty();

					var gallery = this;
					var nextIndex = this.getNextIndex(this.currentIndex);

					// Hide the loading conatiner
					if (this.$loadingContainer) {
						this.$loadingContainer.hide();
					}

					// Setup image
					this.$imageContainer
						.append('<span class="image-wrapper"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+image.alt+'"></a></span>')
						.find('a')
						.append(image)
						.click(function(e) {
							clickHandler(e, gallery, this);
						});
				}

				if (this.settings.onTransitionIn)
					this.settings.onTransitionIn();
				else
					this.$transitionContainers.show();

				return this;
			},

			syncThumbs: function() {
				if (this.$thumbsContainer) {
					var page = Math.floor(this.currentIndex / this.settings.numThumbs);
					if (page != this.currentPage) {
						this.currentPage = page;
						this.updateThumbs();
					}

					// Remove existing selected class and add selected class to new thumb
					var $thumbs = this.$thumbsContainer.find('ul.thumbs').children();
					$thumbs.filter('.selected').removeClass('selected');
					$thumbs.eq(this.currentIndex).addClass('selected');
				}

				return this;
			},

			updateThumbs: function() {
				var gallery = this;
				var transitionOutCallback = function() {
					gallery.rebuildThumbs();

					// Transition In the thumbsContainer
					if (gallery.settings.onPageTransitionIn)
						gallery.settings.onPageTransitionIn();
					else
						gallery.$thumbsContainer.show();
				};

				// Transition Out the thumbsContainer
				if (this.settings.onPageTransitionOut) {
					this.settings.onPageTransitionOut(transitionOutCallback);
				} else {
					this.$thumbsContainer.hide();
					transitionOutCallback();
				}

				return this;
			},

			rebuildThumbs: function() {
				// Initialize currentPage to first page
				if (this.currentPage < 0)
					this.currentPage = 0;
				
				var needsPagination = this.data.length > this.settings.numThumbs;

				// Rebuild top pager
				var $topPager = this.$thumbsContainer.find('div.top');
				if ($topPager.length == 0)
					$topPager = this.$thumbsContainer.prepend('<div class="top pagination"></div>').find('div.top');

				if (needsPagination && this.settings.enableTopPager) {
					$topPager.empty();
					this.buildPager($topPager);
				}

				// Rebuild bottom pager
				if (needsPagination && this.settings.enableBottomPager) {
					var $bottomPager = this.$thumbsContainer.find('div.bottom');
					if ($bottomPager.length == 0)
						$bottomPager = this.$thumbsContainer.append('<div class="bottom pagination"></div>').find('div.bottom');
					else
						$bottomPager.empty();

					this.buildPager($bottomPager);
				}

				var startIndex = this.currentPage*this.settings.numThumbs;
				var stopIndex = startIndex+this.settings.numThumbs-1;
				if (stopIndex >= this.data.length)
					stopIndex = this.data.length-1;

				// Show/Hide thumbs
				var $thumbsUl = this.$thumbsContainer.find('ul.thumbs');
				$thumbsUl.find('li').each(function(i) {
					var $li = $(this);
					if (i >= startIndex && i <= stopIndex) {
						$li.show();
					} else {
						$li.hide();
					}
				});

				// Remove the noscript class from the thumbs container ul
				$thumbsUl.removeClass('noscript');
				
				return this;
			},

			buildPager: function(pager) {
				var gallery = this;
				var startIndex = this.currentPage*this.settings.numThumbs;
				
				// Prev Page Link
				if (this.currentPage > 0) {
					var prevPage = startIndex - this.settings.numThumbs;
					pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.settings.prevPageLinkText+'">'+this.settings.prevPageLinkText+'</a>');
				}

				// Page Index Links
				for (i=this.currentPage-3; i<=this.currentPage+3; i++) {
					var pageNum = i+1;
					
					if (i == this.currentPage)
						pager.append('<span class="current">'+pageNum+'</span>');
					else if (i>=0 && i<this.numPages) {
						var imageIndex = i*this.settings.numThumbs;
						pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageNum+'">'+pageNum+'</a>');
					}
				}

				// Next Page Link
				var nextPage = startIndex+this.settings.numThumbs;
				if (nextPage < this.data.length) {
					pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.settings.nextPageLinkText+'">'+this.settings.nextPageLinkText+'</a>');
				}

				pager.find('a').click(function(e) {
					clickHandler(e, gallery, this);
				});

				return this;
			}
		});

		// Now initialize the gallery
		this.settings = $.extend({}, defaults, settings);
		//enableHistory = this.settings.enableHistory; // Ghismo

		if (this.interval)
			clearInterval(this.interval);

		this.interval = 0;
		
		if (this.settings.imageContainerSel) this.$imageContainer = $(this.settings.imageContainerSel);
		if (this.settings.captionContainerSel) this.$captionContainer = $(this.settings.captionContainerSel);
		if (this.settings.loadingContainerSel) this.$loadingContainer = $(this.settings.loadingContainerSel);

		// Setup the jQuery object holding each container that will be transitioned
		this.$transitionContainers = $([]);
		if (this.$imageContainer)
			this.$transitionContainers = this.$transitionContainers.add(this.$imageContainer);
		if (this.$captionContainer)
			this.$transitionContainers = this.$transitionContainers.add(this.$captionContainer);
		
		// Set the hash index offset for this gallery
		this.offset = galleryOffset;

		this.$thumbsContainer = $(thumbsContainerSel);
		this.initializeThumbs();

		// Add this gallery to the global galleries array
		registerGallery(this);

		this.numPages = Math.ceil(this.data.length/this.settings.numThumbs);
		this.currentPage = -1;
		this.currentIndex = 0;
		var gallery = this;

		// Hide the loadingContainer
		if (this.$loadingContainer)
			this.$loadingContainer.hide();

		// Setup controls
		if (this.settings.controlsContainerSel) {
			this.$controlsContainer = $(this.settings.controlsContainerSel).empty();
			
			if (this.settings.renderSSControls) {
				if (this.settings.autoStart) {
					this.$controlsContainer
						.append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.settings.pauseLinkText+'">'+this.settings.pauseLinkText+'</a></div>');
				} else {
					this.$controlsContainer
						.append('<div class="ss-controls"><a href="#play" class="play" title="'+this.settings.playLinkText+'">'+this.settings.playLinkText+'</a></div>');
				}

				this.$controlsContainer.find('div.ss-controls a')
					.click(function(e) {
						gallery.toggleSlideshow();
						e.preventDefault();
						return false;
					});
			}
		
			if (this.settings.renderNavControls) {
				var $navControls = this.$controlsContainer
					.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.settings.prevLinkText+'">'+this.settings.prevLinkText+'</a><a class="next" rel="history" title="'+this.settings.nextLinkText+'">'+this.settings.nextLinkText+'</a></div>')
					.find('div.nav-controls a')
					.click(function(e) {
						clickHandler(e, gallery, this);
					});
			}
		}

		// Initialize history only once when the first gallery on the page is initialized
		historyInit();
		
		// Build image
		var hash = getHash();
		var hashGallery = (hash >= 0) ? getGallery(hash) : 0;
		var gotoIndex = (hashGallery && this == hashGallery) ? (hash-this.offset) : 0;
		this.goto(gotoIndex);

		if (this.settings.autoStart) {
			
			setTimeout(function() { gallery.play(); }, this.settings.delay);
		}

		// Kickoff Image Preloader after 1 second
		setTimeout(function() { gallery.preloadInit(); }, 1000);

		return this;
	};
})(jQuery);/*
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}var validator=$.data(this[0],'validator');if(validator){return validator;}validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}return false;}return true;}if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}return handle();}else{validator.focusInvalid();return false;}});}return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=true;var validator=$(this[0].form).validate();this.each(function(){valid&=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(a.value);},filled:function(a){return!!$.trim(a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}if(params.constructor!=Array){params=[params];}$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);this.errorsFor(element).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)this.element(element);},highlight:function(element,errorClass,validClass){$(element).addClass(errorClass).removeClass(validClass);},unhighlight:function(element,errorClass,validClass){$(element).removeClass(errorClass).addClass(validClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",dateDE:"Bitte geben Sie ein gültiges Datum ein.",number:"Please enter a valid number.",numberDE:"Bitte geben Sie eine Nummer ein.",digits:"Please enter only digits",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator");validator.settings["on"+event.type]&&validator.settings["on"+event.type].call(validator,this[0]);}$(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",delegate).delegate("click",":radio, :checkbox",delegate);if(this.settings.invalidHandler)$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus();}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.formSubmitted=false;this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name)[0];}var rules=$(element).rules();var dependencyMismatch=false;for(method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method");throw e;}}if(dependencyMismatch)return;if(this.objectLength(rules))this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)return arguments[i];}return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method);if(typeof message=="function")message=message.call(this,rule.parameters,element);this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}if(!this.labelContainer.append(label).length)this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}this.toShow=this.toShow.add(label);},errorsFor:function(element){return this.errors().filter("[for='"+this.idOrName(element)+"']");},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))return this.findByName(element.name).filter(':checked').length;}return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",previous={old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}if(rules.messages){delete rules.messages}return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message||$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var options=$("option:selected",element);return options.length>0&&(element.type=="select-multiple"||($.browser.msie&&!(options[0].attributes['value'].specified)?options[0].text:options[0].value).length>0);case'input':if(this.checkable(element))return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])this.settings.messages[element.name]={};this.settings.messages[element.name].remote=typeof previous.message=="function"?previous.message(value):previous.message;param=typeof param=="string"&&{url:param}||param;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};errors[element.name]=previous.message=response||validator.defaultMessage(element,"remote");validator.showErrors(errors);}previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},dateDE:function(value,element){return this.optional(element)||/^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},numberDE:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))return"dependency-mismatch";if(/[^0-9-]+/.test(value))return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)nDigit-=9;}nCheck+=nDigit;bEven=!bEven;}return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){return value==$(param).val();}}});$.format=$.validator.format;})(jQuery);;(function($){var ajax=$.ajax;var pendingRequests={};$.ajax=function(settings){settings=$.extend(settings,$.extend({},$.ajaxSettings,settings));var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}return(pendingRequests[port]=ajax.apply(this,arguments));}return ajax.apply(this,arguments);};})(jQuery);;(function($){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){if($.browser.msie)return false;this.addEventListener(original,$.event.special[fix].handler,true);},teardown:function(){if($.browser.msie)return false;this.removeEventListener(original,$.event.special[fix].handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};});$.extend($.fn,{delegate:function(type,delegate,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});},triggerEvent:function(type,target){return this.triggerHandler(type,[$.event.fix({type:type,target:target})]);}})})(jQuery);/* declare global variables for jslint */
/*global $ */
/* menu.js
 * @author Jason Crane, jcranefwst
 * @minify true
 */
// handles adding/removing of classes that make menu work, uses hoverIntent plugin to delay mouseover/out events 
jQuery(document).ready(function() { 
	var hoverIntentConfig = {    
	     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
	     interval: 10, // number = milliseconds for onMouseOver polling interval    
	     over: isHover, // function = onMouseOver callback (REQUIRED)    
	     timeout: 350, // number = milliseconds delay before onMouseOut    
	     out: outHover // function = onMouseOut callback (REQUIRED)    
	};
	var _default = $('#nav ul li.default').attr('id'), is_default = '#' + _default;
	function isHover() {
		$('#nav').toggleClass('z99');
		 $(this).addClass('active').removeClass('inactive');	
		 $(this).siblings().removeClass('active').addClass('inactive');
		 $(this).children('.sub_nav').addClass('subnav_active');
	}
	function outHover(){
		var subnav_active = $('li.active').children('sub_nav').hasClass('subnav_active');
		if (subnav_active) {
			// do nothing
		}
		else {	
			$('#nav').toggleClass('z99');
			$(this).removeClass('active').addClass('inactive');
			$(this).children('.sub_nav').removeClass('subnav_active');
			if ($(this).siblings().hasClass('active'))
			{
				// do nothing
			}
			else {
				$(is_default).removeClass('inactive');
				$(is_default).addClass('active');
				// this is a last failsafe if none of the top menu items are active, the home page menu will be made active
				// create array 
				any_active = [];
				// check if any of the top menu items have the class 'active'
				$('#nav li.top').each(function() {
					// get true or false 
					yes_active = $(this).hasClass('active');
					// push the result each time into an array
					any_active.push(yes_active);
				})
				// sort the array alphabetically, thereby putting all of the false items first; any true items in array would go to the end
				any_active.sort();
				// pop out the last item of the array. if any of them were true, true would be last and would get popped out.
				active_check = any_active.pop().toString();
				// if nothing came back true (as in, none of the top menu items had a class of active
				if (active_check != 'true') {
					// just double check and remove the active class from any of the top menu items
					$('li#home_page').siblings('.top').removeClass('active').addClass('inactive');
					// and add the class to the home page menu item to make it active
					$('li#home_page').removeClass('inactive').addClass('active');
				}
			}
		}
	}
	jQuery('#nav ul li.top').each(function() {
		jQuery(this).hoverIntent(hoverIntentConfig);
	});
});/** MI_Cookie.js ****************************************************************
 * @fileoverview Class for managing cookies. This class allows you to interact with cookies
 * as an object with each named value represented as a property of the object.
 * This class will store multiple name/value pairs in a single cookie, reducing 
 * the number of cookies needed. Browsers may enforce limits to the number of 
 * individual cookies stored, so bundling values up in a single cookie is a good
 * idea. New cookies should be used if there's a difference in access rights, or
 * a cookie is getting too big, 4k of data is generally the limit.
 * @minify true
 * @author Joe Whetzel
 * @aggpath js/MI_Cookie.js
 *************************************************************************** */
 var mi = (!mi) ? {'media_domain':''} : mi;
 
/** Cookie object constructor. This constructor creates the javascript object, it
 * does not create the browser cookie, use {@link #store} to store the cookie in 
 * the browser.
 * @param document the Document object for which the cookie is stored
 * @param {String} name string that specifies a name for the cookie, defaults to "cookie"
 * @param {Integer} minutes how long until the cookie expires, defaults to current session
 * @param {String} path the path with which the cookie is associated, defaults to current page
 * @param {String} domain domain the cookie is associated to
 * @param {Boolean} secure whether or not the cookie is secure, only if the connection is secure
 * @constructor
 */
mi.Cookie = function (document, name, minutes, path, domain, secure) {
	/** Document object for which the cookie is stored. Default is to use the current document. */
	this.$document = (document) ? document : window.document;
	/** Name of the cookie. Defaults to "cookie".
	 * @type Document
	 */
	this.$name = (name) ? name : 'cookie';
	/** Minutes until the cookie expires. Default is at the end of the current session.
	 * @type Integer
	 */
	this.$expiration = (minutes) ? new Date((new Date()).getTime() + minutes * 60000) : null;
	/** Path associated with the cookie.
	 * @type String
	 */
	this.$path = (path) ? path : null;
	/** Domain associated with the cookie.
	 * @type String
	 */
	this.$domain = (domain) ? domain : null;
	/** Whether or not the cookie is secure.
	 * @type Boolean
	 */
	this.$secure = (secure) ? true : false;
};

/** Stores the cookie in the browser. Defining or changing values in the cookie
 * object alone does not save the values to the browser. After working with the
 * cookie object it must be stored in the browser.
 */
mi.Cookie.prototype.store = function() {
	var cookieVal = "";
	for(var prop in this) {
		if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) {
			continue;
		}
		if (cookieVal !== "") {
			cookieVal += '&';
		}
		cookieVal += prop + ':' + escape(this[prop]);
	}
	var cookie = this.$name + '=' + cookieVal;
	cookie += (this.$expiration) ? '; expires=' + this.$expiration.toGMTString() : '';
	cookie += (this.$path) ? '; path=' + this.$path : '';
	cookie += (this.$domain) ? '; domain=' + this.$domain : '';
	cookie += (this.$secure) ? '; secure' : '';
	this.$document.cookie = cookie;
};

/** Loads a single cookie from the browser into the cookie object, making each 
 * name/value pair properties of the object.
 * @type Boolean
 */
mi.Cookie.prototype.load = function() {
	var allCookies = this.$document.cookie;
	if (allCookies === "") {
		return false;
	}
	var start = allCookies.indexOf(this.$name + '=');
	if (start == -1) {
		return false;
	}
	start += this.$name.length + 1;
	var end = allCookies.indexOf(';', start);
	if (end == -1) {
		end = allCookies.length;
	}
	var cookieVal = allCookies.substring(start, end);
	var a = cookieVal.split('&');
	if ((a.length == 1) && (a[0].indexOf(':') == -1)) {
		var prop = this.$name;
		this[prop] = unescape(cookieVal.replace(/\+/g, '%20')); // PHP encodes spaces with a '+'
		return true;
	}
	for(var i=0; i < a.length; i++) {
		a[i] = a[i].split(':');
	}
	for(i=0; i < a.length; i++) {
		this[a[i][0]] = unescape(a[i][1]);
	}
	return true;
};

/** Method for removing the entire cookie from the browser.
 */
mi.Cookie.prototype.remove = function() {
	var cookie = this.$name + '=';
	cookie += (this.$path) ? '; path=' + this.$path : '';
	cookie += (this.$domain) ? '; domain=' + this.$domain : '';
	cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
	this.$document.cookie = cookie;
};



/* MI_Cookie.js ^ *********************************************************** */
/* 
 @minify true
 taken for minification from http://star-telegram.com/static/scripts/mi/polls/polls-20071128-AAY.js
This is an object oriented version of the poll javascript
This script does everything our ajax polls implementation needs, including:

1. showing appropriate html depending on if the person has voted or not
2. handle submission of the form
3. get results
etc
*/

/* object constructor */
function miPollAjax() {
    this.poll_id;
    this.story_id;
    this.section_id;
    this.stretched = false;
    this.vote_casted = false;

    // When you click to cast your vote this get's called
    this.submitPoll = function()
    {
        var poll_value = this.getPollValue();

        // Test if they chose a radio button to vote on
        if (poll_value != -1)
        {
            // vote_casted gets set in the beginning if they have already voted and set to true after voting.
            // That allows us to pop up an alert if they've already voted. 
            if ( this.vote_casted == true )
            {
                alert( "Limit 1 vote per user, you have already voted." );
            }
            else
            {
                // Build a url with the form data to send the iframe to to exec the perl script
                url = "/survey-bin/tabulate_poll.cgi?mi_pb_cache=1&expire_days=5&path=/&already_voted_error=You%20have%20already%20voted.%20Limit%201%20vote%20per%20user.&save=Cast%20Vote&value=Cast%20Vote";
                url = url + "&poll_id=" + this.poll_id;
                url = url + "&section_id=" + this.section_id;
                url = url + "&story_id=" + this.story_id;
                url = url + "&poll_response=" + poll_value;

		$("#poll_result").load(url); 
		this.hidePollForm();
            	this.fetchPollResults();
            	this.showPollResults();
                this.vote_casted = true;
            }
        }
        else
        {
            alert( "Please choose an option to vote for" )
        }
    }

    // This will retrieve poll results without casting a vote, by calling in the cgi results via jquery's 
    // AJAX support
    // Note: not passing "save" or "value" like the submitPoll function does prevents this call
    // from casing a vote. 
    this.fetchPollResults = function()
    {
        // Build a url with the form data to send the iframe to to exec the perl script
        url="/survey-bin/tabulate_poll.cgi?mi_pb_cache=1&expire_days=5&path=/&already_voted_error=You%20have%20already%20voted.%20Limit%201%20vote%20per%20user.";
        url = url + "&poll_id=" + this.poll_id;
        url = url + "&section_id=" + this.section_id;
        url = url + "&story_id=" + this.story_id;
	
	$("#poll_result").load(url); 
    }

    this.register_response = function( element )
    {
        this.tempElement = element;
        //this.handleResponse( 1, this.tempElement );
        this.stretch_graphs();
    }


    // This helper function looks at the list of poll responses and returns the index of the one selected
    this.getPollValue = function()
    {
        var radios = document.forms.poll_responses.poll_response;
        for ( var i=0; i < radios.length; i++ )
        {
            if ( radios[i].checked ) return ( radios[i].value );
        }
        return -1;
    }

    // Onload, hide either the poll form or the poll results based on the cookie
    this.visibilityCheck = function()
    {
        if ( this.alreadyVoted() )
        {
            //alert( "You have already voted." );
            this.hidePollForm();
            this.fetchPollResults();
            this.showPollResults();
            //this.showAlreadyVotedMessage();
            this.vote_casted = true;
        }
        else  // Otherwise show the form so they can vote
        {
            this.showPollForm();
        }
    }

    //checks to see if the user has voted already
    this.alreadyVoted = function()
    {
        // Get the cookie and parse it to see if this poll ID has been submitted before
        content = this.getPollCookie('mi_polls');
        //alert( "poll cookie => '" + this.getPollCookie('mi_polls') + "'" );
    
        // No cookie, do nothing
        if ( content == null )
        {
            return;
        }
    
        // Parse the cookie so we can see if they voted on this particular poll id
        sval = content.split ( ";" );
        num_cookies = sval.length;
        key = new Array();
        for ( x = 0; x < num_cookies / 2 + 1; x++ )
        {
            qval = sval[x].split("=");
            id = qval[0];
            poll_submitted = qval[1];
            key[id] = poll_submitted;
            //alert( "id => '" + id + "', value => '" + poll_submitted + "'" );
        }

        // If they already voted, hide the form, and show a message saying they already voted
        if ( key[this.poll_id] == 1 )
        {
            //alert( "You have already voted" );
            return true;
        }
        else
        {
            return false;
        }
    }

    // Grab the cookie so we can check if they've already submitted or not
    this.getPollCookie = function(cookie_name)
    {
        dc = document.cookie;
        cname = cookie_name + "=";
        clen = dc.length;
        cbegin = 0;
    
        while ( cbegin < clen )
        {
            vbegin = cbegin + cname.length;
    
            if ( dc.substring ( cbegin, vbegin ) == cname )
            {
                vend = dc.indexOf ( ";", vbegin );
                if ( vend == -1 ) vend = clen;
    
                return unescape ( dc.substring ( vbegin, vend ) );
            }
    
            cbegin = dc.indexOf ( " ", cbegin ) + 1;
    
            if ( cbegin == 0 ) break;
        }
        
        return null;
    }

    // The size of the box this stuff is going into can vary quite a bit so
    // This will scale up the size of those bars on the bar graph so they take up
    // More of the box.. If your graphs are running off the edge, bring .9 down to .8
    this.stretch_graphs = function()
    {
        this.stretched = true;
        var element_poll_result = document.getElementById("poll_result");
        var element_poll_form = document.getElementById("poll_form");
   
        // Detect how much room the box has that the results are going into 
        if ( element_poll_result.offsetWidth > 0 )
            div_width = element_poll_result.offsetWidth;
        else
            div_width = element_poll_form.offsetWidth;

        // Magical formula or deciding how much to increase the bar width    
        multiplier = (div_width * .9 - 20)/100;

        // Get each of those bars, and expand or shrink each one of them       
        var element_bar_result = document.getElementsByName("bar_result");

        for ( count = 0; count < element_bar_result.length; count++ )
        {
            pixels = element_bar_result[count].width;
            if ( pixels > 0 )
                element_bar_result[count].width = pixels * multiplier;
        }
    
    }

    // Hide/Show the poll form and poll results  
    this.hidePollForm = function()
    {
        //alert( "hide poll form" );
        var element = document.getElementById("poll_form");
        if (element) element.style.display= "none";
    }

    this.showPollForm = function()
    {
        var element = document.getElementById("poll_form");
        if (element) element.style.display= "block";
    }

    this.hidePollResult = function()
    {
        var element = document.getElementById("poll_result");
        if (element) element.style.display= "none";
    }

    this.hideAlreadyVotedMessage = function()
    {
        var element = document.getElementById("poll_already_voted");
        if (element) element.style.display="none";
    }

    this.showPollResults = function()
    {
        this.fetchPollResults();
        var element = document.getElementById("poll_result");
        if (element) element.style.display = "block";

        if (this.stretched == false)
        {
            this.stretch_graphs();
        }
    }

    this.showAlreadyVotedMessage = function()
    {
        element = document.getElementById("poll_already_voted");
        if (element) element.style.display = "block";
    }

} /* end object *//* @minify true */
/*
this script provides a way to test to see if a script has been loaded previously, and if so, does not load it again.
it checks for the object that will be created by a script, if the object exists, the script has been loaded.
*/

function miScriptScheduler() {

    this.scriptCheck = ""; /* value of function check (eg. window.jQuery)*/
    this.scriptPath = ""; /* file path to required script */
    //var cc = this; /*cache a copy of the object for use inside jquery methods*/

    /*
    method checks value of scriptCheck, if undefined a script node is created
    with the src attribute set to scriptPath. This node is then injected into the   DOM
    */
    
    this.scheduleScript = function ()
    {
        if(!this.scriptCheck)
        {
            /* script test function not found, load script with no waiting*/
                var tempElement = document.createElement("script");
                tempElement.src = this.scriptPath;
                var bases = document.getElementsByTagName('base');
                if(bases.length && bases[0].childNodes.length) {
                   bases[0].appendChild(tempElement);
                }
                else {
                  document.getElementsByTagName('head')[0].appendChild(tempElement);
                }
            
        }
        else {
            return(0);
        }
    } /*end scheduleScript method*/
} /* end constructor*/

/* photo_gallery.js
 * @author jcrane
 * @minify true
 */
function photoGallery(){
	var newHeight, slideHeight;
	var slideHeights = [];
	// determine tallest slide by looping through them and getting their height
	// also determine if photo is vertical (taller than it is wide) and if it is, add width: 400px to image style
	// have no idea why we were adding a 400 width to these photos, was causing issues. removed Fri Mar 19 2010 16:41:02 GMT-0500 (CDT)
	$('.gallery_slide').each(function(){
		slideHeight = $(this).height();
		slideHeights.push(slideHeight);
		slideWidth = $(this).width();
		// if (slideHeight > slideWidth) {
			// $(this).children('img').css('width','400px');
		// }
	});
	// sort the heights in the array
	slideHeights = slideHeights.sort(sortNumber);
	// pop out the last (largest) height, and then give it to cycle below
	newHeight = slideHeights.pop();
	newHeight = newHeight + 20;
	$('#photo_gallery').cycle({
		fx: 'fade',
		speed: 'fast',
		timeout: 5000,
		pager: '#gallery_pager',
		next: '#gallery_next',
		prev: '#gallery_prev',
		height: newHeight
	});
	$('#photo_gallery').cycle('pause');
	$('#gallery_play').toggle(function(){
		$('#photo_gallery').cycle('resume', true);
		$(this).toggleClass('ui-icon-pause');
	}, function(){
		$('#photo_gallery').cycle('pause');
		$(this).toggleClass('ui-icon-pause');
	});
	$('#gallery_nav a, #gallery_nav .ui-icon').click(function(){
		injectAd();
	});
	// allow user to scroll through photos using left and right arrow keys
	function checkKey(e){
     switch (e.keyCode) {
        case 37:
          $('#gallery_prev').trigger('click');
            break;
        case 39:
           $('#gallery_next').trigger('click');
            break;
      }      
	}
	if ($.browser.mozilla) {
	    $(document).keypress (checkKey);
	} else {
	    $(document).keydown (checkKey);
	}
}/* @minify true */

// search **********************************************************************
//function searchFormSubmit(form) {
//      if (form.aff.value == 'archives' || form.aff[1].checked == true) {
//            window.location = "http://www.newslibrary.com/nlsearch.asp?search_mode=all&action=search&date_mode=year&year=last+180+days&sort=d%3Ah&nitems=10&region=st&dbquery=" + form.keywords.value;
//                return false;
//        } 
//	 else if (form.aff[2].checked == true || form.aff.value == 'web') {
//		window.location = "http://www.star-telegram.com/cgi-bin/mi/overture/overture.pl?Keywords=" + form.keywords.value;
//                return false;
//	}

//        return true;
//}
// end search ******************************************************************


// search **********************************************************************
function searchFormSubmit(form) {
        if (form.aff.value == 'archives' || form.aff[1].checked == true) {
                window.location = "http://www.newslibrary.com/nlsearch.asp?search_mode=all&action=search&date_mode=year&year=last+180+days&sort=d%3Ah&nitems=10&region=st&dbquery=" + form.keywords.value;
                return false;
        } 
	 else if (form.aff[2].checked == true || form.aff.value == 'web') {
		 var encoded_keywords = encodeURIComponent(form.keywords.value);
		 var section_num = '547';
		 var url_version = 'ysr';
		 var params = 'product=Yahoo%2COverture&' +
			      'collection=WEB&' +
			      'live_template=http%3A%2F%2Fwww.star-telegram.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' + 
			      'preview_template=http%3A%2F%2Fpreview.star-telegram.com%2F' + section_num + '%2Fv-' + url_version + '%2Findex.html&' + 
			      'error_template=http%3A%2F%2Fwww.star-telegram.com%2F' + section_num + '%2Fv-err%2Findex.html&' +
			      'results_per_page=10&' +
			      'prop_related=1&prop_dym=1';
		 window.location = "http://search.star-telegram.com/search-bin/search.pl.cgi?sf_Keywords=" + encoded_keywords + '&' + params;

		 return false;
	}
        return true;
}
// end search ******************************************************************

// getParams *******************************************************************
function getParams(params) {
   var Params = new Object ();
   if ( ! params ) return Params; // return empty object
   var Pairs = params.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;

}
// end getParams *****************************************************************


function today_string() {
	// dependant on date functions defined in mi-utilities.js
	var today = new Date();
	return today.getDayString()+', '+today.getMonthString()+' '+today.getDate()+', '+today.getFullYear();
}

// text_digge_ variable configuration - set digger_is_off variable to 1 to turn off ***********

var digger_is_off = 1;

// text_digger


/* global $ */
/* startelegram.functions_09.js
 * @minify true
 * @author jcranefwst
 */
// jQuery.noConflict();
// eventually want to make this object oriented, so...
var st = {};
var tabConfig;
// controls display of hidden headlines in grids of headlines as on weeklies
var smg = {
	showMore: function(){
		// when clicking on show_more link
		$('.show_more').bind('click', function(){
			// if there is actually content in the tabbed_more div
			if ($(this).next('.tabbed_more').children().length > 0) {
				// show the content of the tabbed_more div
				$(this).next('.tabbed_more').slideDown('fast');
				// hide the show more link
				$(this).hide();
				// don't open the link itself
				return false;
			}
			else {
				// or if there isn't anything in the tabbed more link, open the link (to that section front 
				return true;
			}
		});
	}
}; 
// control opening, closing and which icons show when using service links at top of page
function removeCloseIcon() {
	$('.sub_service li').each(function() {
		$(this).click(function() {
			$(this).closest('.sub_service').slideUp('fast');
			$(this).siblings('.sub_service').slideToggle('fast');
			$(this).closest('.sub_service').siblings('.ui-icon').toggleClass('ui-icon-close');
			// return false;
		});
	});
}
function serviceLinks(){
	var isOpen;
	$('.service_link').each(function() {
			$(this).click(function(){
				var isOpen = $(this).parents('#service_links > ul > li').siblings().children('.sub_service');
				if (isOpen.is(':visible')) {
					$(this).parents('#service_links > ul > li').siblings().children('.sub_service').hide();
					$(this).siblings('.sub_service').slideToggle('fast').addClass('active');
					$(this).parents('#service_links > ul > li').siblings().children().siblings('.ui-icon').toggleClass('ui-icon-close');
					// testing icon behavior with/without next line
					$(this).siblings('.ui-icon').toggleClass('ui-icon-close');
					$('#header_wrap').addClass('z99');
				}
				else {
					$('#header_wrap').toggleClass('z99');
					$(this).siblings('.ui-icon').toggleClass('ui-icon-close');
					$(this).siblings('.sub_service').slideToggle('fast');
				}
			if ($(this).hasClass('single_link')) {
				// do nothing
				}	
			else { 
				return false;
			}
		});
	});
	
	$('#service_links .ui-icon').each(function() {
		hasCloseIcon = $(this).hasClass('ui-icon-close');
		$(this).click(function() {
			if ($(this).hasClass('ui-icon-close')) {
				$(this).toggleClass('ui-icon-close');
				$('#header_wrap').toggleClass('z99');
			}
		});
	});
	
	$('.sub_service li').each(function() {
		$(this).click(function() {
			$(this).closest('.sub_service').slideUp('fast');
			$(this).siblings('.sub_service').slideToggle('fast');
			$(this).closest('.sub_service').siblings('.ui-icon').toggleClass('ui-icon-close');
			$('#header_wrap').toggleClass('z99');
			// return false;
		});
	});
	
	// if one of the submenus is open and user clicks elswhere in document, close the submenu  
	
		// $('#header_wrap').click(function(){
			$('#pagebody').bind('click', function(){
				$('#service_links .sub_service:visible').hide();
				$('#service_links .sub_service').siblings('.ui-icon').removeClass('ui-icon-close');
				$('#header_wrap').removeClass('z99');
			});
		// click binding is causing cursor flicker issues in ie7, so this prevents 	
		/* $('#wrapper').click(function(e) {
  			e.stopPropagation();
		}); */
		// trying to add this functionality elswhere in this function so it works whenever dropdown is open
		/* $('#service_links').hover(function() {
			$('#header_wrap').addClass('z99');
			},
			function() {
				$('#header_wrap').removeClass('z99');
			}
		);	 */
		/* cornerPeel = $('#yahoo_1x1_ipatf, #yahoo_1x1_ipatf_1').find('script:eq(1)');
		text = cornerPeel.text();
		if (text) {
			if (text.indexOf('// no ads') == -1) {
				$('#service_links').css('padding-left', '120px');
			}
		} */	
} // end function serviceLinks

// control font sizes of articles on story detail page
defaultFontSize = 12;
function fontSizeMultiplier(changeThis) {
	var fontSize = $(changeThis).css('font-size');
	fontSize = fontSize.replace('px','');
	fontSize = parseFloat(fontSize) * 1.2;
	fontSize += 'px';
	$(changeThis).css('font-size',fontSize);
}
function bigText(){
	$('.bigger_text').click(function(){
		fontSizeMultiplier('#story_body');
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
	});	
}
function fontSizeSmaller(changeThis) {
	var fontSize = $(changeThis).css('font-size');
	fontSize = fontSize.replace('px','');
	fontSize = parseFloat(fontSize);
	if (fontSize >= defaultFontSize) {
		fontSize = fontSize / 1.2;
		fontSize += 'px';
		$(changeThis).css('font-size',fontSize);
	}
}
function smallText(){
	$('.smaller_text').click(function(){
		fontSizeSmaller('#story_body');
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
	});
}
function defaultText() {
	$('.default_text').click(function(){
		$('#story_body').css('font-size','1.1em');
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
	});
}
// scroll to specific location for links within same page
// via http://www.vagrantradio.com/2009/12/stupid-jquery-tricks.html
function smoothScroll() {
	$('a.scroll[href*=#]').click(function() {  
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')  
		&& location.hostname == this.hostname) {  
		  var $target = $(this.hash);  
		  $target = $target.length && $target  
		  || $('[name=' + this.hash.slice(1) +']');  
		  if ($target.length) {  
		 var targetOffset = $target.offset().top;  
		 $('html,body')  
		 .animate({scrollTop: targetOffset}, 900);  
		   return false;  
		  }  
		}  
	});  
}

// return default text back in an input text field if it is focused and then blurred
function inputFocusBlur() {	
	$('input.text').each(function() {
		var defaultValue = $(this).val();
		$(this).blur(function() {
			if (this.value === '') {
				this.value = defaultValue;
			}
		});
		$(this).focus(function() {
			// $(this).select();
			if (this.value == defaultValue) {
				this.value = '';
			}
		});
	});
}

// selects default text in a text field when it is clicked
function formTextSelect() {
	$('form .text').each(function() {
		$(this).focus(function() {
   			$(this).select();
		});
	});
}

// closes news alert when close icon is clicked
function closeBulletin() {
	$('#bulletin .ui-icon').click(function() {
		$('#bulletin').slideUp('fast');
		// $('#skyline').show();
	});
}

// creates tabs for article, photos and videos on story detail pages
function articleTabs() {
	var hasVideo, hasMap, hasComments, media_id, href, commentsPaging, aec;
	var $story_content_tabs = $('#story_content_container').tabs();
	// toggles font size controls, so they're only shown when article tab is active
	var selected = $story_content_tabs.tabs('option', 'selected');
	$story_content_tabs.bind('tabsselect', function(event, ui) {
 		// if we're not selecting the first tab, which is the article tab, hide the text resize options
		if (ui.index !== 0) {
				$('.bigger_text, .smaller_text, .default_text').hide();
			}
		// or show them if we are selecting the article tab	
		else {
				$('.bigger_text, .smaller_text, .default_text').show();
			}	
	});
	// opens appropriate tab when photo or video link is clicked from story assets links
	$('#story_assets .photo_link, #photo_asset_thumb img').click(function() {
		$story_content_tabs.tabs('select','#article_photos');
		return false;
	});
	$('#story_assets .video_link, #story_assets #main_thumbnail').click(function() {
		$story_content_tabs.tabs('select','#article_videos');
		return false;
	});
	$('#story_assets .map_link, #map_asset_thumb img').click(function() {
		$story_content_tabs.tabs('select','#article_map');
		return false;
	});
	var video_url = document.location;
	video_url = video_url.toString();
	if (video_url.match('video=')) {
	    $story_content_tabs.tabs('select','#article_videos');
		if (hasVideo == 'true') {
		// don't do anything b/c we already have our videoStack
		}
		else {
			media_id = $('#embedded_video').attr('name');
			getVmixVideoDetail(media_id);
			getVmixVideoDetailStack();
			hasVideo = 'true';
		}
	}
	// adds a button so users can get embed code of our videos
	
	
	$('.link_to_video').click(function() {
		$('#story_content_container').tabs('select','#article_videos'); 
		window.scrollTo(0,300); 
		return false;
	})
	// this handles the events that happen when certain tabs are selected
	$story_content_tabs.bind('tabsselect', function(event, ui){
		href = new String(ui.tab.href);
		// if video tab selected
		if (href.match('article_videos')) {
			if (hasVideo == 'true') { 
				// don't do anything b/c we already have our videoStack
			}
			else {		
			// get the media id from the name attribute of the embedded_video div, which is set in the template
			media_id = $('#embedded_video').attr('name');
			// get the main video and the latest videos stack
			getVmixVideoDetail(media_id);
			getVmixVideoDetailStack();
			// variable to see if video already loaded, so we don't load each time the tab is selected
			hasVideo = 'true';
			}	
		}
		// if map tab is selected
		else if (href.match('article_map')) {
			if (hasMap == 'true') {
			// don't do anything b/c we already have our map
			}
			else {
				// get the api key from the name attribute of the map, which is set in the template
				api_key = $('#article_map .map').attr('name');
				// load the maps api, which will callback to the function to the load the maps
				initMapLoader(api_key);
				// variable to see if map is already loaded, so we don't load it each time the tab is selected
				hasMap = 'true';
			}
		}
		// NONE OF THIS NECESSARY WITH DISQUS
		// change the comment pagination URLs to not take users to #Comments_Container div, which is added to URL through pluck javascript
		/* else if (href.match('article_comments')) {
			if (hasComments == 'true') {
			// don't do anything b/c we have already done this
			}
			else {
				// this variable is declared in MI_SiteLife.js, overriding to remove '#Comments_Container identifier from returned URL
				gSiteLife.mi.commenting = {
					submitReturnAddress: 'http://' + location.host + location.pathname + "?mi_pluck_action=comment_submitted&qwxq="+Math.floor(Math.random()*10000)+urlTS.getMilliseconds()
				};
				// need to do the same thing for the pagination links, but the #Comments_Container is inserted in a different way
				// that's a little tougher to get to, so we go about it this way
				// loop through the links inside the comment pagination div
				
				st.commentsPaging = function(){
					$('#nyxComments_pager span a').each(function(){
						// grab the href attribute
						paginationLink = $(this).attr('href');
						// cut it off at the hash
						paginationLink = paginationLink.substring(0, paginationLink.indexOf("#"));
						// give the new href back to the link
						$(this).attr('href', paginationLink);
					});
					hasComments == 'true';
				};
				st.commentsPaging();
			}
		} */
	}); 
	$('#article_videos .cycle').cycle({
		speed: 'fast',
		timeout: 5000,
		pager: '#video_pager',
		next: '#video_next',
		prev: '#video_prev'
	});
	$('#article_videos .cycle').cycle('pause');
	$('#story_assets .map_link, #map_asset_thumb img').click(function() {
		$story_content_tabs.tabs('select','#article_map');
		return false;
	});	
	$('#story_assets .graphics_link, #graphic_asset_thumb img').click(function() {
		$story_content_tabs.tabs('select','#article_graphics');
		return false;
	});	
	$('#story_assets .chart_link').click(function() {
		$story_content_tabs.tabs('select','#article_chart');
		return false;
	});	
	// add class of last to remove bottom padding on last in list of links in story assets box
	$('#links_asset_thumb p:last').addClass('last');
	
	
	// TODO - fix in IE, this does not yet work in IE; problem is with commentsCount = $('#commentsCount').text(), line 311
	// grab the number of comments, and if there are comments, add number to comments tab
	// this needs to happen after thhe number is loaded in the 1st place by Pluck
	// this is not the best way to do this, keep working on figuring out how to grab that variable instead.
	/*
	// fisrt, set the interval of checking for the comments total to once a second
	commentCountInterval = setInterval('st.commentsCount()',1000);
	// only going to check ten times, once a second, so start at 1
	commentCountLimit = 1;
	st.commentsCount = function(){
		// grab the comments number from pluck comment count in story tools
		commentsCount = $('#commentsCount').text();		
		// if it's 0, it may not have been populated yet, so keep checking
		if (commentsCount == 0) {
			// make sure it hasn't been 10 times
			while (commentCountLimit < 10) {
				// run the interval timer
				commentCountInterval;
				// add this check to the count limit total
				commentCountLimit = commentCountLimit + 1;
			}
		}
		// or if the comment count is more than 0
		else {
			// wrap it in parentheses
			commentsTab = 'Comments (' + commentsCount + ')';
			// and add that number to the comments tab
			$('#comments_tab_test').children('a').text(commentsTab);
			// and clear the interval timer
			clearInterval(commentCountInterval);
		}
	}
	st.commentsCount(); */
	
	
	// check to see if a comment has just been submitted, and if it has, go the comments tab so the user can see their comment
	var comment_submitted, url, openCommentTab;
	url = document.location;
	url = url.toString();
	if(url.match(/comment_submitted/)) {
		openCommentTab = 'true';
		// st.commentsCount();
	}
	else if (url.match(/page_nav/)) {
		openCommentTab = 'true';
		// st.commentsCount();
	}
	else {
		comment_submitted = '';
	}
	if (openCommentTab) {
		$story_content_tabs.tabs('select', '#article_comments');
		// TODO: this is an attempt to run the commentsPaging function after a comment is submitted, so that those links are corrected.
		// this doesn't work, really i think it needs to run on document ready, or with a setTimeout maybe
		/* $story_content_tabs.tabs({ 
        	select: function(event, ui) { 
            	if($(ui.href) == "article_comments") { 
					st.commentsPaging();
				}
			}
		}); */
	}
	// opens the comment tba when the commentCount in story tools is clicked
	$('#commentCount').bind('click',function() {
		$story_content_tabs.tabs('select','#article_comments');
		return false;
	});
	
	// get the comment count from first place it's displayed on page
	
	// commenting out injectAd function during troubleshooting of why tabs won't load
	// injectAd();
} // end articleTabs function

/* function addEmbedCode() {
	var ec = $('#embedded_video').clone();
	var ecv = ec.children('embed');
	if (ecv.length) {
		// change the width and height for something a little more accomodating
		ec.children('embed').attr({width:'450',height:'277'});
		ech_f = ec.html();
		// console.log('not the ajax-loader');
		$('#article_videos .video_wrapper').append('<button id="get_embed_code">Get embed code</button>');
		$('#article_videos .video_wrapper').append('<textarea id="show_embed_code" style="display:none; width: 600px; height: 150px;">' + ech_f + '</textarea>');
		$('#get_embed_code').live('click',function() {
			$(this).text($(this).text() == 'Get embed code' ? 'Hide embed code' : 'Get embed code');
			$('#show_embed_code').slideToggle().select();
		});
		// console.log('about to clear interval');
		clearInterval(aec);
	}
	else {
		console.log('looking');
		aec = setInterval(aecInt,2000);
	};
};
var aecInt = function() {
	addEmbedCode();
} */
	
	
// sort numbers in an array
function sortNumber(a,b) {
	return a - b;
}
 function mycarousel_initCallback(carousel){
	jQuery('.jcarousel-control a').bind('click', function(){
		carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('id')));
		return false;
	});
	/* $('#skyline_options').hover( function() {
		$(this).toggleClass('ui-state-hover');
	},
	function() {
		$(this).toggleClass('ui-state-hover');
	}
	);
	$('#skyline_options').bind('click', function() {
		$('.jcarousel-control').slideToggle('fast');
		$(this).toggleClass('ui-icon-close');
	}); */
}
/*
* This is the callback function which receives notification
* when an item becomes the first one in the visible range.
*/
/* function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
	if (idx == 1) {
		$('.jcarousel-control a#1').children('span').addClass('ui-icon-bullet');
		$('.jcarousel-control a#1').siblings().children('span').removeClass('ui-icon-bullet');
	}
	if (idx == 3) {
		$('.jcarousel-control a#3').children('span').toggleClass('ui-icon-bullet');
		$('.jcarousel-control a#3').siblings().children('span').removeClass('ui-icon-bullet');
	}
	if (idx == 5) {
		$('.jcarousel-control a#5').children('span').toggleClass('ui-icon-bullet');
		$('.jcarousel-control a#5').siblings().children('span').removeClass('ui-icon-bullet');
	}
	if (idx == 7) {
		$('.jcarousel-control a#7').children('span').toggleClass('ui-icon-bullet');
		$('.jcarousel-control a#7').siblings().children('span').removeClass('ui-icon-bullet');
	}
} */		
// runs functions when the DOM is ready
jQuery(document).ready(function() {
	// creates carousel for skyline
	jQuery('#skyline_items').jcarousel({
		scroll: 1,
		initCallback: mycarousel_initCallback
		// itemFirstInCallback: mycarousel_itemFirstInCallback
	});	
	// creates cycle for special features promos
	jQuery('#special_features_promos').cycle({
		fx: 'fade',
		timeout: 7000,
		speed: 300,
		pause: 1
	});
	
	// creates tabs on any div with class of tabs
	jQuery('.tabs').each(function() {
		$(this).tabs({ 
		    // collapsible:true,
			// removed mouseover event, handling with hoverIntent plugin
			// event: 'mouseover',
			// creates accordion when applicable inside of those tabs 
			show: function(ui) { 
		        $('.accordion').accordion({ 
					icons: {
						'header': 'ui-icon-triangle-1-w',
						'headerSelected' : 'ui-icon-triangle-1-s'
						},
					// event: 'mouseover',
					// fillSpace: true
					autoHeight: false, 				
					change: function(event, ui) {
						// remove title of exposed accordions (open accordions)
						ui.newHeader.attr('title','');
						// change title of exposed accordions siblings (closed accordions)
						ui.newHeader.siblings('.header').attr('title','Click to show content');
					} 
				});
				// added for mi analytics testing of page height / scrolling / 4-29-2010
				if ( typeof( mistats.pageHeight ) !== 'undefined' ) {
					mistats.pageHeight = mistats.pageInfo.documentHeight();
					mistats.roundHeights();
				}	
		    },
			spinner: '', 
			cache: true 
		}).children('.tab_links').removeClass('ui-corner-all');
	}); 
	
	// give tab links mouseover functionality with a slight delay using hoverIntent plugin
	function tabHover() {
		$(this).trigger('click');
	}
	function tabOut(){ 
		// do nothing 
	}
	var tabConfig = {    
    	sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
    	interval: 40, // number = milliseconds for onMouseOver polling interval    
    	over: tabHover, // function = onMouseOver callback (REQUIRED)    
    	timeout: 300, // number = milliseconds delay before onMouseOut    
    	out: tabOut // function = onMouseOut callback (REQUIRED)    
	};
	// hoverIntent for tabs
	$('.tabs').each(function() {
		$(this).find('ul.tab_links li a').hoverIntent(tabConfig);
	});
	$('#story_content_container').find('ul.tab_links li a').hoverIntent(tabConfig);
	
	$('ul.tab_links').each(function() {
		$(this).children('li:first').addClass('first');
	});
	
	// function to pull in ATOM feed of party pics galleries and display then in a tab on the media belt
	// not currently in use Tue Jan 12 2010 14:43:40 GMT-0600 (CST)
	/* var partyPicked;
	function getPartyPics() {
		var ln, newClass, last, title, image, link, gallery;
		// get the atom feed, convert to JSON
		$.jGFeed('http://www.dfw.com/204/index.atom',
			function(feeds){	
			  // Check for errors
			  if(!feeds){
			  	// alert('no feed found');
			    // there was an error
			    return false;
			  }
			 // remove the loading indicator 
			$('#pics .loading').remove();
			ln = feeds.entries.length;
			// loop through the feeds
			  for(var i=0; i<ln; i++){
			  	// if it's the last one, add a class of last
				if (i == 4) {newClass = ' last'}
                else {newClass = ' '};
			    var entry = feeds.entries[i];
			    // get the title, image src and gallery link
			    title = entry.title;
				image = entry.content;
				link = entry.link;
				// put them all together
				gallery = '<div id="pics_' + i + '" class="pics_stack media_stack' + newClass + '"><h4><a href="' + link + '">'+ title + '</a></h4><a href="' + link + '"><img src="' + image + '" /></a></div>';
				// append to the pics div
				$('#pics').append(gallery);
			  }
			}, 5);
	partyPicked = 1; 
	}
	
	// grab party pics feed from dfw.com and load pics into tab
	$('#st_bottom_full').tabs().bind('tabsselect', function(event, ui){
		if(ui.index == 3 && partyPicked != 1) {
			getPartyPics();
		}
	}); 
	*/
	
	$('#share li a, .story_tool_option').each(function() {
		$(this).hover(
			function() {
				$(this).find('.ui-icon').addClass('ui-state-hover');
			},
			function() {
				$(this).find('.ui-icon').removeClass('ui-state-hover');
			}
		);
	});
		
	$('#story_tools #recommendation').click(function() {
		$(this).siblings('#recommendation_icon').addClass('ui-state-highlight');
	});
	
	$('.story.summary:last').addClass('last');
	
	// show and hide search bar options when clicking Show options text above search bar
	$('#search .search_options_toggle').click(function() {
		optionText = $(this).children('a').children('span');
		$(this).siblings('.search_options').slideToggle('fast');
		if (optionText.text().match('Show options')) {
			optionText.text('Hide options');
		}
		else if (optionText.text().match('Hide options')) {
			optionText.text('Show options');
		}
		return false;
	});
	$('#search_1100_label').click(function() {
		$('input#search_1100').attr('checked', 'checked');
		$(this).addClass('active_search');
		$(this).siblings('.radio_label').removeClass('active_search');
		return false;
	
	});
	$('#search_archives_label').click(function() {
		$('input#search_archives').attr('checked', 'checked');
		$(this).addClass('active_search');
		$(this).siblings('.radio_label').removeClass('active_search');
		return false;
		
	});
	$('#search_web_label').click(function() {
		$('input#search_web').attr('checked', 'checked');
		$(this).addClass('active_search');
		$(this).siblings('.radio_label').removeClass('active_search');
		return false;
	});
	
	
	// use hoverIntent on more menu option if it exists in main menu
	// moved config options below function definitions so they will be defined before referenced, 9-1-09
	
	function moreHover(){
		$(this).parents('li.more_nav_link').addClass('more_nav_link_active');
		$(this).siblings('.more_nav').addClass('more_nav_active').removeClass('more_nav_inactive');
	}
	function moreOutHover(){
		$(this).siblings('.more_nav').addClass('more_nav_inactive').removeClass('more_nav_active');
		$(this).parents('.more_nav_link').removeClass('more_nav_link_active');
	}
	var hoverIntentMoreConfig = {    
	     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
	     interval: 10, // number = milliseconds for onMouseOver polling interval    
	     over: moreHover, // function = onMouseOver callback (REQUIRED)    
	     timeout: 350, // number = milliseconds delay before onMouseOut    
	     out: moreOutHover // function = onMouseOut callback (REQUIRED)    
	};
	$('#nav a.more_link').hoverIntent(hoverIntentMoreConfig);
	$('#nav a.more_link').click(function() { return false; });
	serviceLinks();
	closeBulletin();
	bigText();
	smallText();
	defaultText();
	formTextSelect();
	inputFocusBlur();
	smoothScroll();
	smg.showMore();
	// this is causing problems on super bowl template, not vital at this point anyway
	// 1-4-10, jcranefwst
	// st.modalPDF();
	st.toggleBatChart();
	$('#scores td.TSN5').closest('tr').addClass('odd');
	$('#scores td.TSN1').closest('tr').addClass('even');
	$('#scores tr.even + tr.odd, #scores tr.odd + tr.even').addClass('top_rule');
	$('#schedule tr:odd, #standings tr:odd, #leaders tr:odd').closest('tr').addClass('odd');
	
	// this is for the sports network widgets, to lazy load those javascript files	
	// LazyLoadTsnSchedule();	

	// this is to hide text digger tags. temporarily only displaying topics links until tags pages are generated
	// turning this off because tags pages are live and we are now displaying links
	// $('#digger_topics p:eq(1)').hide();
	
	// this is to only display topics or tags if there are actually links, otherwise, hide the topics/tags label(s)
	// loop through each paragraph (topics are in one and tags in the other
	$('#digger_topics p').each(function() {
		// find the links if they exist
		hasLinks = $(this).find('a');
		// get number of links
		hasLinks = hasLinks.length;
		// if there aren't any links
		if (hasLinks < 1) {
			// hide the paragraph
   			$(this).addClass('hide');
		}
	});
	
}); // end main document ready function



function initMapLoader(apiKey) {
  var script = document.createElement("script");
  script.src = "http://www.google.com/jsapi?key=" + apiKey + "&callback=loadMaps";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}

// this is taken from current preredesign site, still will be used for templates using legacy highlights method	
function setLeftRightWidth() {
	if(window.leftRightWidth) {
		$("div.left_half").each(function(i){
			if(i < leftRightWidth.length){ // Check to see if a custom width has been defined for this DIV
				if(leftRightWidth[i][0]<=100) { // Only apply left width if it is less than or equal to 100
					$(this).width(leftRightWidth[i][0]+"%");
				}
			 }
		 }); 	
		$("div.right_half").each(function(i){
	 		if(i < leftRightWidth.length){ // Check to see if a custom width has been defined for this DIV
	 			if(leftRightWidth[i][0]<=100) { // Only apply right width if the left width is less than or equal to 100
	 				if(leftRightWidth[i][0]+leftRightWidth[i][1]>=100) { // If sum of the left and right widths is greater than 100 adjust right width
	 					leftRightWidth[i][1]=99-leftRightWidth[i][0]; //using 99 here to avoid problems with border widths
	 				}
	 				$(this).width(leftRightWidth[i][1]+"%");
	 			}
	 		}
	 	});
	 	// equalHeightLR();
	}
} 

/*
 * VALIDATION / OPINIONS MAILER FORM
 */

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

var $submission_type, $submission_email, submitOK;
// $submission_type = document.feedback.email_option.value;
/* function checkOptionValue() {

    if (document.feedback.email_option.value == "letter"){
          $submission_type="Letter to the Editor";
		  $submission_email="letters@star-telegram.com";
       }
	else if (document.feedback.email_option.value == "cheer"){
          $submission_type="Cheers and Jeers"; 
		  $submission_email="letters@star-telegram.com";
       } 
   else if (document.feedback.email_option.value == "test"){
          $submission_type="Test submission"; 
		  $submission_email="jasonljunk@star-telegram.com";
       }
   
} */

var http_request = false;
function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
                // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }

      http_request.onreadystatechange = alertContents; 
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
}

function alertContents() {
    if (http_request.readyState == 4) {
       if (http_request.status == 200) {
          // alert(http_request.responseText);
          result = http_request.responseText;
          $('#contentarea').html(result);  
document.getElementById('contentarea').innerHTML = result;
      } else {
          alert('Request status: ' + http_request.status + '. There was a problem with the request.');
      }
   }
}

function submitForm(){
	var $submission_type, $submission_email;
	$email_option = document.getElementById("email_option").value;
	$sender_name = document.getElementById("sender_name").value;
	$email_address = document.getElementById("email_address").value;
	$postal_address = document.getElementById("postal_address").value;
	$phone_number = document.getElementById("phone_number").value;
	$body_content = document.getElementById("body_content").value;
$submission_type = document.feedback.email_option.value;
	var poststr = 'submission_type=' + $submission_type + '&sender_name=' + $sender_name + '&phone_number=' + $phone_number + '&email_address=' + $email_address + '&postal_address=' + $postal_address + '&body_content=' + $body_content;
	makePOSTRequest('/cgi-bin/opinions_mailer.pl', poststr);
}
 
$(document).ready(function() {
	$("#opinions_mailer").validate({
		rules: {
			 sender_name: "required",
			 email_address: "required",
			 postal_address: "required",
 			 phone_number: {
				required: true,
				phoneUS: true
			}
		},
		messages: {
			 sender_name: "Enter your name",
			 email_address: "Please enter a valid email address",
			 postal_address: "Please enter your mailing address",
 			 phone_number: "Please enter your phone number"
		}, 
		submitHandler: function() {  
			submitForm();
			// form.submit();
		}
	});
});

function radarLoop(){
	url = '/static/accuweather/locradar_sixty_minute_loop.html';
	$('#weather_loop').load('/static/accuweather/locradar_sixty_minute_loop.html #pics', function(){
		$('#pics').cycle({
			fx: 'fade',
			speed: 10,
			timeout: 700
		});
	});
	$('#weather_loop').click(function(){
		window.open(url);
	});
};

		
// function to create Century in the making widget based on google spreadsheet data
function cm_w(json) {
	var cm_w, the_widget;
  	now = new Date();
	month = now.getMonth() + 1;
	date = now.getDate(); 
  	year = now.getFullYear();
	today = month + '/' + date + '/' + year;
	ln = json.feed.entry.length;
	for (var i = 0; i < ln; i++) {
	    var entry = json.feed.entry[i];
	    rundate = entry.gsx$rundate.$t;
		if (today === rundate) {
			var head = document.createElement('h4');
			var leadin = document.createTextNode(entry.gsx$leadin.$t);
			var headline = document.createTextNode(entry.gsx$headline.$t);
			var br = document.createElement('br');
			var leadin_wrap = document.createElement('span');
			leadin_wrap.setAttribute('id','leadin');
			var head_link = document.createElement('a');
			var linkURL = entry.gsx$url.$t;
			// var linkURL = 'http://www.star-telegram.com/2010/04/14/2114825/the-top-college-moments-in-north.html';
			head_link.setAttribute('href', linkURL);
			leadin_wrap.appendChild(leadin);
			head_link.appendChild(leadin_wrap);
			head_link.appendChild(br);
			head_link.appendChild(headline);
			head.appendChild(head_link);
			cm_w = document.getElementById('cm_widget');
			cm_w.appendChild(head);
		}
	}
};

function inlineTopics() {
	try {
		td_TopicLinker.InlineContentName = "story_body";
		td_TopicLinker.InlineLinkClass = 'td_link';
		td_TopicLinker.InlineLinkCount = '10';
		td_TopicLinker.InlineLinkTracker = '#navlink=inline_to_topics';
	}
	catch(err) {
		console.log('no topics') // no topics
	}
};


	/*
 * jQuery :nth-last-child - v0.2 - 2/13/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var c=/:(nth)-last-child(?:\((even|odd|[\dn+-]*)\))?/,a=$.expr,b=a.filter.CHILD;a[":"]["nth-last-child"]=function(h,g,e,k){var j=e[0].match(c),f=$(h.parentNode).children(),d;j=a.preFilter.CHILD(j);b(h,j);d=f.eq(f.length-h.nodeIndex)[0];return b(d,j)}})(jQuery);
st.mlbScoreline = function() {
	$('.mlb_scoreline').find('tr:first').addClass('scoreline_header');
	$('.mlb_scoreline').find('tr:first').children('th:nth-last-child(3)').addClass('runs');
	$('.mlb_scoreline').find('tr:first').nextAll('tr:lt(2)').children('td:nth-last-child(3)').addClass('runs');
	$('.mlb_scoreline').find('table').attr('cellspacing','0');
	var $secondToLastRow = $('.mlb_scoreline').find('tr:nth-last-child(2)');
	var $lastRow = $('.mlb_scoreline').find('tr:last-child');
	var text = $lastRow.html();
	var splitText = text.split('<br>');
	$secondToLastRow.append(splitText[0] + '</td>').children('td:first').attr('colspan','');
	$lastRow.remove();
	// $lastRow.html(splitText[0] + '</td>').css('height','25px');
};
st.filterFeaturedStory = function() {
	var sID = $('.st_featured').add('.st_major').find('h1 a').attr('storyid');
	$('#st_main_content .story').find('a[name="story"]').each(function() {
		new_sID = $(this).attr('storyid');
		if (new_sID == sID) {
			$(this).parents('.story').hide();
		}
	});
};
// opens a link to a PDF in a modal window using Google's PDF viewer;
st.modalPDF = function() {
	var $dialog = $('<iframe />').attr('width', '600').attr('height', '780');
	$dialog.dialog({
		autoOpen: false,
		width: 630,
		height: 780
	});
	$("a[href$='.pdf']").bind('click', function(e){
		e.preventDefault();
		var $link = $(this);
		var href = $link.attr('href');
		var linkToLoad = 'http://docs.google.com/viewer?url=' + href + '&embedded=true';
		$dialog.attr('src', linkToLoad).dialog('open');
	});
};
st.toggleBatChart = function() {
	$('.bats-toggle').click(function() {
	    if ($(this).parents('.hit-chart').hasClass('bats-right')) {
	        $(this).parents('.hit-chart').hide();
			$(this).parents('.player').children('.bats-left').show();
	    }
	    else if 
			($(this).parents('.hit-chart').hasClass('bats-left'))
			{
		        $(this).parents('.hit-chart').hide();
				$(this).parents('.player').children('.bats-right').show();
	    	}
	});
};
// creates jquery ui tabs
// expects <div><ul><li><a/></li></ul><div/></div> template
st.utils = {};
st.utils.tabify = function() {
	$('#' + id).tabs(); 
};
st.utils.showOnHover = function(container, elemToShow) {
	$('.' + container).hover(
		function() {
			$(this).find(elemToShow).show();
		},
		function() {
			$(this).find(elemToShow).hide();
		}
	)
};
st.utils.atify = function() {
	var re = /(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g,
		$tag = $(".tagline").add('.shirttail').filter( function() {
			var text = $(this).text();
				if (text.match(re)) {
					return $(this);
				}
			}),
		tagText = $tag.text(),
		at = function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g, function(m, m1, m2) {
				return m1 + '<a href="http://twitter.com/' + m2 + '">@' + m2 + '</a>';
			});
		},
		username = at(tagText);
	$tag.html(username);
};
st.utils.removeEmptyAssets = function() {
	$('.related_content').find('li').filter(function() {
		var text = $(this).text();
		if(text.replace(/\s/g,"") == "") {
			return $(this).remove();
		}
	});
};
// accepts ids of containing elements (divs?) and will show one of them randomly
// arguments are passed in in a listm as in: st.showRandom("id1","id2","id3"); 
st.showRandom = function() {
	var l = arguments.length;
    var rnd_no = Math.floor(l*Math.random());
    for (var i=0; i<l; i++){
        if (i !== rnd_no) {
            document.getElementById(arguments[i]).style.display = 'none';
        }
    }
};// **********************
// Name: st_google_map.js
// Function: This JavaScript file will render a Google Map on a Pubsys Story
// Author: Ara Yapejian
// Date: 1/29/08
// Modified by Jason Crane, 6-22-09, see note on mapInfoWindow, googlebar
/* @minify true */

// **********************

function miGoogleMap( myMapType, myMapControls, myMapZoom, mySetMarkerCenter, myMouseDrag) {
	// ***********
	// Here we are setting the default value for all passable arguments, these
	//   defaults will be used if no ( by 'no' we mean an empty string is passed)
	//   argument is passed during instantiation.
	// Arguments:
	//   mapType:           Should we show 'map', 'satellite', 'hybrid'
	//   mapControls:       Should we display 'zoom', 'type', 'none' or 'both'
	//   mapZoom:           What is the starting zoom level on map creation
	//   setMarkerCenter:   Should we place a Google Marker in the center of the map
	//   mapMouseDraggable: Enable or Disable mouse dragging 'true' or 'false'
		var mapType = 'map';
		var mapControls = 'both';	
		var mapZoom = 14;
		var setMarkerCenter = true;
		var mapMouseDraggable = true;
		if ( myMapType != 'null' ) 
			var mapType = myMapType;
		if ( myMapControls != 'null' )
			var mapControls = myMapControls;
		if ( myMapZoom != null )
			var mapZoom = myMapZoom;
		if ( (mySetMarkerCenter == true) || (mySetMarkerCenter == false)  )
			setMarkerCenter = mySetMarkerCenter;
		if ( (myMouseDrag == true) || (myMouseDrag == false) )
			mapMouseDraggable = myMouseDrag;
	// ***********

	// ***********
	// This is the function that actually does the displaying of the map
	// ***********
	this.initializeGoogleMap = function( location, divID ) {
		if ( GBrowserIsCompatible() ) {
			var geocoder = new GClientGeocoder();
			// added googleBar so users can search map now that it's much larger than before
			var opts = { resultList : G_GOOGLEBAR_RESULT_LIST_SUPPRESS, suppressInitialResultSelection : true, showOnLoad: true};
			var map = new GMap2(document.getElementById( divID ),{googleBarOptions: opts});
			map.enableGoogleBar();
			geocoder.getLatLng( location, function( point ) {
				if (!point) {
					// console.log("Address not Found!");
				} else {
					map.setCenter(point, mapZoom);
					// *******
					// Detect the map type user requested and set,
					//   default is G_NORMAL_MAP, so no need to detect.
					if ( mapType == 'satellite')
						map.setMapType(G_SATELLITE_MAP);
					if ( mapType == 'hybrid')
						map.setMapType(G_HYBRID_MAP);
					if ( mapType == 'map' )
						map.setMapType(G_NORMAL_MAP);
					// *******

					// *******
					// Detect what the user specified for map controls and set
					if ( mapControls != 'none') {
						if ( mapControls == 'zoom')
							map.addControl(new GSmallMapControl());
						if ( mapControls == 'type' )
			        			map.addControl(new GMapTypeControl());
						if ( mapControls == 'both' ) {
							map.addControl(new GSmallMapControl());
						        map.addControl(new GMapTypeControl()); }
					}
					// *******

					// *******
					// Enable / Disable mouse dragability of map
					if( mapMouseDraggable == true )
						map.enableDragging();
					if( mapMouseDraggable == false )
						map.disableDragging();
					// *******

					// *******
					// Detect if the user wants a marker on map center and display
					if ( setMarkerCenter == true )
						// original -- map.addOverlay( new GMarker(point) );
						var myHtml;
						function createMarker(point) {
						      var marker = new GMarker(point);
							   var myHtml = '<p><span class="bold">' + location + '</span><br /><a href="http://maps.google.com/maps?f=q&hl=en&geocode=&q=' + location + '&sspn=0.003603,0.006738&ie=UTF8&t=k&z=17&iwloc=addr&om=0&t=m">Get directions, search nearby, more</a></p>';
							 map.openInfoWindowHtml(point, myHtml);
							  GEvent.addListener(marker,"click", function() {						       
						        map.openInfoWindowHtml(point, myHtml);
						      });
						      return marker;
						  }
						map.addOverlay(createMarker(point));
				}
			});	
		}	
	}
};/*global $ */
/* vmix_stack.js
 * @author jcrane
 * @minify true
 */
var vmix_media_id, proxy, limit, token, title, video_icon, video_link, link_close, last_modified, video_open, description, main_thumbnail, video, len, thumbnail, last_modified, video_link, video_link_close, thumbnail_open, each_open, title_open, title_close, description_open, description_close, close_div, video_content; 
function getVmixStack(tab_id, genre_ids, limit) {
	limit = limit ? limit : 3;
	proxy = "/cgi-bin/ajax/apiproxy_vmix.php?miaction=list&vmix=media.php?action=getMediaList&limit=" + limit + "&author=Star-Telegram&genre_ids=" + genre_ids;
	$.getJSON(proxy, function(data){
		// TODO -->
		// started experimenting with doing this as a loop rather than each to improve performance
		// var l = data.media.length;
		// for (var i=0;i<l; i++) {
		$.each(data.media, function(i,video){
			token = video.token;
			title = video.title;
			description = video.description;
			len = 150;
			if (description.length > len) {
				/* Truncate the content of the description, then go back to the end of the previous word to ensure that we don't truncate in the middle of a word */
				description = description.substring(0, len);
				description = description.replace(/\w+$/, '');
				description += ' ...';
			}
			thumbnail = video.thumbnail[0].url;
			// console.log('thumbnail url is ' + thumbnail);
			last_modified = video.last_modified;
			vmix_media_id = video.id;
			link_close = '</a>';
			thumbnail_open = '<div class="thumbnail">';
			each_open = '<div class="media_stack">';	
			title_open = '<h4>';
			title_close = '</h4>';				
			video_open = '<div class="video" style="display:none">';
			description_open = '<p class="story_body">';
			description_close = '</p>';
			video_icon = '<span class="video_play_overlay hide ui-icon ui-icon-play ui-corner-all"></span>';
			close_div = "</div>";
			// http://video.star-telegram.videos.vmixcore.com/vmix_hosted_apps/p/media?id=
			video_link = '<a href="http://www.star-telegram.com/videos/#vmix_media_id=' + vmix_media_id + '">';
			thumbnail = '<img src="' + thumbnail + '" width="130"/>';
			// join an array rather than concatenate all those variables for faster performance
			video_content = each_open + video_icon + video_link + thumbnail + link_close + video_link + title_open + title + link_close + title_close + description_open + description + description_close + close_div;
			$(tab_id).append(video_content);
			$('.video_play_overlay').removeClass('hide');
		});
	});
}/*global $ */
/* vmix_stack2.js
 * @author jcrane
 * @minify true
 */
var vmix_media_id, proxy, token, title, video_icon, video_link, link_close, last_modified, 
	video_open, description, main_thumbnail, video, len, thumbnail, last_modified, video_link, video_link_close, 
	thumbnail_open, each_open, title_open, title_close, description_open, description_close, close_div, video_content;
	
// create object if it doesn't exist	
var st = st || {};	

st.getVmixStack = {
	running : false,
	options: {
		container: '#video-stack',
		genre: 4437,
		img_width: 130,
		limit: 3,
		truncate: 150,
		start: 0
	},
	init: function (config) {
		var context = this, prop;
		if (st.getVmixStack.running === true) {
			// console.log('breaking; ' + this.running);
			context.init();
		}
		// console.log('before true decl ' + st.getVmixStack.running);
		if ( config ) {
			for ( prop in config ) {
				st.getVmixStack.options[prop] = config[prop];
				// console.log(config[prop]);
			}
		}
		var options = st.getVmixStack.options, video_url;
		var limit = options.limit, container = options.container;
		var genre = options.genre;
		var img_width = options.img_width;
		var truncate = options.truncate;
		var start = options.start;
		proxy = "/cgi-bin/ajax/apiproxy_vmix.php?miaction=list&vmix=media.php?action=getMediaList&limit=" + limit + "&start=" + start + "&author=Star-Telegram&genre_ids=" + genre;
		// replaced getJSON with ajax so this can run synchronously
		// $.getJSON(proxy, function(data){
		$.ajax({  
			url: proxy,  
			dataType: 'json',  
			// data: data,  
			async: false,  
			success: function( data ) {  
				// TODO -->
				// started experimenting with doing this as a loop rather than each to improve performance
				// var l = data.media.length;
				// for (var i=0;i<l; i++) {
				$.each(data.media, function(i,video){
					token = video.token;
					title = video.title;
					description = video.description;
					if (description.length > truncate) {
						/* Truncate the content of the description, then go back to the end of the previous word to ensure that we don't truncate in the middle of a word */
						description = description.substring(0, truncate);
						description = description.replace(/\w+$/, '');
						description += ' ...';
					}
					thumbnail = video.thumbnail[0].url;
					vmix_media_id = video.id;
					video_url = 'http://www.star-telegram.com/videos/#vmix_media_id=' + vmix_media_id;
					// join an array rather than concatenate all those variables for faster performance
					//video_content = each_open + video_icon + video_link + thumbnail + link_close + video_link + title_open + title + link_close + title_close + description_open + description + description_close + close_div;
					$('.video_play_overlay').removeClass('hide');
					// console.log('container at end of each is ' + container);
				});
				// console.log('title: ' + title);
				// console.log('container after each is ' + container);
				$(container).find('a').attr('href',video_url);
				$(container).find('h6 > a').text(title);
				$(container).find('img').attr('src',thumbnail);
				this.running = false;
			}
		});
	}
};/*global $ */
/* vmix_video_detail.js
 * @author jcrane
* @minify true
*/
var vmix_media_id, error_message, detail_proxy, stack_proxy, token, title, description, main_thumbnail, video, len, thumbnail, last_modified, video_link, video_link_close, thumbnail_open, each_open, title_open, title_close, description_open, description_close, close_div, video_content;
function getVmixVideoThumb(vmix_media_id){
	detail_proxy = "/cgi-bin/ajax/apiproxy_vmix.php?miaction=single&vmix=media.php?action=getMedia&media_id=" + vmix_media_id;
	$.getJSON(detail_proxy, function(data){
		main_thumbnail = data.thumbnail[0].url;
		main_thumbnail = '<img src="' + main_thumbnail + '" width="148" />';
		$('#main_thumbnail').html(main_thumbnail);	
		$('#video_asset_thumb .video_play_overlay').removeClass('hide');
	});
}
function getVmixVideoDetail(vmix_media_id){
	error_message = "We\'re having some trouble finding that video at the moment. Sorry for the inconvenience";
	detail_proxy = "/cgi-bin/ajax/apiproxy_vmix.php?miaction=single&vmix=media.php?action=getMedia&media_id=" + vmix_media_id;
	$.getJSON(detail_proxy, function(data){
		// $.each(data.media, function(i,video){
		token = data.token;
		if (token == undefined) {
			$('#embedded_video').text(error_message);
		}
		else {
			// debug('token is ' + token);
			title = data.title;
			$('#video_title').append(title);
			description = data.description;
			$('#video_description').append(description);
			$('#video_asset_link').append(' | ' + title);
			video = '<embed id="player_swf" src="http:\/\/media.vmixcore.com\/core-flash\/UnifiedVideoPlayer\/UnifiedVideoPlayer.swf" quality="high" width="610" height="375" name="UnifiedVideoPlayer" align="middle" play="false" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=543fec5828893ebb9077596915defac8&auto_play=0&token=' + token + '" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed>';
			$('#embedded_video').html(video);
			// add button to grab embed code for embedding on other sites
			embed_code = '<embed src="http:\/\/media.vmixcore.com\/core-flash\/UnifiedVideoPlayer\/UnifiedVideoPlayer.swf" quality="high" width="450" height="277" name="UnifiedVideoPlayer" align="middle" play="false" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=543fec5828893ebb9077596915defac8&auto_play=0&token=' + token + '" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed>';
			$('#article_videos .video_wrapper').append('<button id="get_embed_code">Get embed code</button>');
			$('#article_videos .video_wrapper').append('<textarea id="show_embed_code" style="display:none; width: 600px; height: 150px;">' + embed_code + '</textarea>');
			$('#get_embed_code').live('click',function() {
				$(this).text($(this).text() == 'Get embed code' ? 'Hide embed code' : 'Get embed code');
				$('#show_embed_code').toggle().select();
			});
		} 
	});
}
function getVmixVideoDetailStack(){
	stack_proxy = "/cgi-bin/ajax/apiproxy_vmix.php?miaction=list&vmix=media.php?action=getMediaList&limit=4&author=Star-Telegram";
	$.getJSON(stack_proxy, function(data){
		$.each(data.media, function(i, video){
			token = video.token;
			title = video.title;
			description = video.description;
			len = 100;
			if (description.length > len) {
				/* Truncate the content of the description, then go back to the end of the previous word to ensure that we don't truncate in the middle of a word */
				description = description.substring(0, len);
				description = description.replace(/\w+$/, '');
				description += ' ...';
			}
			thumbnail = video.thumbnail[0].url;
			last_modified = video.last_modified;
			vmix_media_id = video.id;
			video_link = '<a href="http://www.star-telegram.com/videos/#vmix_media_id=' + vmix_media_id + '">';
			video_link_close = '</a>';
			thumbnail_open = '<div class="thumbnail">';
			thumbnail = '<img src="' + thumbnail + '" width="130"/>';
			each_open = '<div class="media_stack">';
			title_open = '<h4>';
			title_close = '</h4>';
			description_open = '<p class="story_body">';
			description_close = '</p>';
			close_div = "</div>";
			video_content = each_open + thumbnail + video_link + title_open + title + video_link_close + title_close + description_open + description + description_close + close_div;
			$('#video_stacks').append(video_content);
			
		});
		$('#more_videos .media_stack:first').addClass('first');
			$('#more_videos .media_stack:last').addClass('last');
	});
}var zvents = {
	options: {
		limit: 1,
		when: '',
		cat: 0,
		images: true,
		tag: '',
		kids: false //,
	},
	eventsFinder : function(Z, config) {
		if(config) {
			for(prop in config){
				zvents.options[prop] = config[prop];
			}
		}
		limit = zvents.options.limit;
		when = zvents.options.when;
		cat = zvents.options.cat;
		kids = zvents.options.kids;
		images = zvents.options.images;
		tag = zvents.options.tag;
		if (zvents.options.kids == true) {
			kids = 1;
		}
		else {
			kids = 0;
		}
		var offset = Math.ceil(limit*Math.random()) -1;
		// var srss = limit + 1;
		Z.site = 'http://listings.dfw.com';
		Z.partner = 1065;
		Z.widget.eventList({
			load: {
			  p: Z.partner,
			  search: true,
			  sort: '',
			  when: when,
			  cat: cat,
			  offset: offset,
			  st: 'event',
			  has_kids: kids,
			  limit: limit,
			  // overrides default thumb image size, none == full size image
			  image_size: 'none',
			  has_editors_pick: 1065,
			  tag: tag,
			  srss: limit // ,
			  // fields: 'id,name,zurl,starttime, venue.name, venue.city, venue.state, site, images'                            
			},
			images: images,
			// Example custom render function for event list
			events: function( events ) {
				return [
					'<div class="ZventsEventList"><ul>',
						events.map(this.event,this).join(''),
					'</ul></div>'
				].join('');
			},
			image: function( event ) {
				var image = event.images[0];
				return ! image ? '' : [
					'<div class="zvents-image">',
					'<a class="ZventsImageLink" href="', event.zurl, '">',
						'<img class="ZventsImage" alt="Image" border="0" ',
							'src="', image.url, '" ',   //note that I changed out Z.imgThumb(image.url) and it still has the same URL
							'width="130"', // image.width, '" height="', image.height, '" ',
						'/>',
					'</a>',
					'</div>'
				].join('');
			},
			
			/* event: function( event ) {
				var date = this.date( event );
				var time = this.time( event );
				// isoDate = dfw.utils.getISODate(date + time);
				// console.log(isoDate);
				if( date ) {
				  date = [
					'<span class="ZventsEventDate"><abbr class="dtstart">',
					  this.date( event ),
					'</abbr></span>',
					' '
				  ].join('');
				}
				return [
					'<li class="ZventsEvent">',
					  this.images ? this.image( event ) : '',
					  '<span class="ZventsEventTime">',
						this.time( event ),
					  '</span>',
					  ' ',
					  date,
					  '<a class="ZventsEventName" href="',  event.zurl, '">',
						Z.String.truncate( event.name, this.maxTitle || 40 ),
					  '</a>',
					'</li>'
				].join('');
			}  */
			
			event: function( event ) {
				var date = this.date( event );
				var time = this.time( event );
				// isoDate = dfw.utils.getISODate(date + time);
				// console.log(isoDate);
				if( date ) {
				  date = [
					'<span class="ZventsEventDate"><abbr class="dtstart">',
					  this.date( event ),
					'</abbr></span>',
					' '
				  ].join('');
				}
				return [
					'<div class="zvents-listing">',
					this.images ? this.image( event ) : '',
					'<h2><a class="ZventsEventName" href="',  event.zurl, '">',
						Z.String.truncate( event.name, this.maxTitle || 40 ),
					'</a></h2>',	
					'<span class="ZventsEventTime">',
					  time,
					'</span>',
					' ',
					date,
				   '<p><a class="ZventsEventName" href="',  Z.site, event.venue.zurl, '">',
					event.venue.name,
					'</a></p><p>',
					event.venue.address,
					'</p><p>',
					event.venue.city,
				  '</p></div>'
				].join('');
			}
			
		});			
	},
	calendar : function(nDays) {
		// EDIT HERE: partner calendar base URL, search URL template,
		// number of days to display
		var partner = 'http://listings.dfw.com/';
		var searchUrl = partner + 'search?swhat=&amp;swhen={day}&amp;st=event';
		var nDays = nDays ? nDays : '7';
		
		var dayNames = [
			'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
		];
		var monthNames = [
			'January', 'February', 'March', 'April', 'May', 'June',
			'July', 'August', 'September', 'October', 'November', 'December'
		];
		
		var todayClass = ' ZventsDayButtonToday';
		var today = new Date( (new Date).setHours( 0, 0, 0, 0 ) );
		for( var i = 1;  i <= nDays;  ++i ) {
			var year = today.getFullYear();
			var month = monthNames[ today.getMonth() ];
			var date = today.getDate();
			var day = today.getDay();
			var weekend = ( day == 0  ||  day == 6 );
			var weekendClass = weekend ? ' ZventsDayButtonWeekend' : '';
			var dayName = dayNames[ today.getDay() ];
			var search = searchUrl.replace( /{day}/, i == 1 ? 'Today' : i == 2 ? 'Tomorrow' : dayName );
			
			button( date, dayName.slice(0,3), search,
				dayName + ', ' + month + ' ' + date + ', ' + year );
			
			todayClass = '';
			today.setDate( date + 1 );
		}
		
		// these add the All events link, which we don't want to do write here
		// weekendClass = ' ZventsDayButtonAll';
		// button( 'All', 'Events', partner, 'any day' );
		
		function button( date, day, url, title, clas ) {
			document.write( [
				
				/* '<li class="z_primary"><a href="', url, '" ',
					'class="ZventsDayButton', todayClass, weekendClass, '" ',
					'title="View events for ', title, '" ',
				'>', day,'</a></li>' */
				
				'<span class="ZventsDay">',
					'<a href="', url, '" ',
						'class="ZventsDayButton', todayClass, weekendClass, '" ',
						'title="View events for ', title, '" ',
					'>',
					// '<span class="ZventsDayButtonDate">',
					// 	'&nbsp;', date, '&nbsp;',
					// '</span>',
					'<span class="ZventsDayButtonDay">',
						day,
					'</span>',
					'</a>',
				'</span>'
			].join('') );
		}		
	},
	restaurantFinder : function( Z ) {
		Z.site = 'http://listings.dfw.com';
		Z.partner = 1065;
		var limit = 2;
		var offset = Math.ceil(limit*Math.random()) -1;
		Z.widget.venueList({
			load: {
				p: Z.partner,
				st: 'restaurant',
				search: true,
				limit: 1,
				srss: 2,
				tag: 'bestofdfw',
				image_size: 'none',
				offset: offset,
				//choose cuisines.  See the Cuisine ID in the URL on your co-brand site
				// cuisine: '133', 
				//Options include: ['id', 'name', 'address', 'parent_id', 'phone', 'city', 'country', 'zip', 'latitude', 'longitude', 'state', 'timezone', 'url', 'zurl', 'private', 'description', 'images', 'types', 'showtimes', 'movies', 'cuisines']
				fields: 'id,address,name,zurl,phone,city,state,images'
			},
			// images: true,
			// Example custom render function for venue list
			venues: function( venues ) {
				return [
					'<div class="ZventsEventList">',
						venues.map(this.venue,this).join(''),
					'</div>'
				].join('');
			},
			// Render the image(s) for an event
			image: function( venue ) {
				var image = venue.images[0];
				return ! image ? '' : [
					'<div class="zvents-image">',
					'<a class="ZventsImageLink" href="', Z.site, venue.zurl, '">',
						'<img class="ZventsImage" alt="Image" border="0" ',
						'src="', image.url, '" ',
						'width="66"', // image.width, '" height="', image.height, '" ',
						'/>',
					'</a>',
					'</div>'
				].join('');
			},
			//Override Date Rendering
			//    Changed the date order and style           
			venue: function( venue ) {
				//Best Place to set the output order.  Rearrange these as needed
				//'date' is the Date
				//this.time(event) is the time
				//venue.zurl is the venue URL
				//venue.name is the name of the event            
				//  Other options include event.phone, event.description, etc. 
				//  ***Remember to set the "fields:" parameter if you add sources  
				return [
				  '<div class="zvents-listing">',
					this.image ? this.image( venue ) : '',
					'<h2><a class="ZventsEventName" href="',  Z.site, venue.zurl, '">',
					  Z.String.truncate( venue.name, this.maxTitle || 40 ),
					'</a></h2>',
					'<p>',
					venue.address,
					'</p><p> ',
					venue.city,
					'</p><p>',
					venue.phone,    
					'</p>',
				  '</div>'
				].join('');
			  }
		});
	}
};/* get-latest-tweet.js
 * @minify true
 * @author jcranefwst
 */

st.getLatestTweet = {
	init: function(user, container) {
		var context = this;
		if (!context.cachedData) {
			$.ajax({  
				url: '/static/includes/s-t-tweets.json',  // '/static/includes/startelegram-tweets.json',  
				dataType: 'json',  
				async: false,  
				success: function(data){
					// console.log('ajax request');
					// console.log(data);
					context.cachedData = data;
					context.compileTweet(data, user, container);
				}
			});
		}
		else {
			context.compileTweet(context.cachedData, user, container);
			// console.log('using cachedData');
		}
	},
	compileTweet : function(data, user, container) {
		var start = new Date().getTime();
		context = this;
		// console.log('compiling tweet');
		
		for (var key in data) {
			for (var i in data[key]) {
				var tweeter = data[key][i];
				// console.log(tweeter);
				var description = tweeter.description;
				var screen_name = tweeter['screen_name'];
				// console.log('name is ' + screen_name);
				if (screen_name === user) {
					// console.log('found ' + user);
					screen_name = context.Linkify('@' + screen_name);
					var tweet = tweeter['status'];
					var id = tweet.id_str;
					var text = context.Linkify(tweet['text']);
					// console.log('text is ' + text);
					var created = context.Timify(tweet['created_at']);
					// console.log('created at ' + created);
					var html = '<div data-tweetid="' + id + '" class="tweet"><span class="tweet-user">' + screen_name + ' on Twitter: </span><span class="tweet-text">' + text + '</span> <span class="tweet-created">' + created + '</span></div>';
					$(html).appendTo(container);
				}
			}
		}
		var end  = new Date().getTime();
		var time = end - start;
		// console.log('compiling tweets took ' + time);
		
		/* for (var key in data) {
			for (var i in data[key]) {
				var tweeter = data[key][i];
				console.log(tweeter);
				var description = tweeter.description;
				var screen_name = tweeter['screen_name'];
				console.log('name is ' + screen_name);
				if (screen_name === user) {
					console.log('found ' + user);
					screen_name = context.Linkify('@' + screen_name);
					var tweet = tweeter['status'];
					var id = tweet.id_str;
					var text = context.Linkify(tweet['text']);
					console.log('text is ' + text);
					var created = context.Timify(tweet['created_at']);
					console.log('created at ' + created);
					var html = '<div data-tweetid="' + id + '" class="tweet"><span class="tweet-user">' + screen_name + '</span><span class="tweet-text">' + text + '</span> <span class="tweet-created">' + created + '</span></div>';
					$(html).appendTo(container);
				}
			}
		} */
		/* for (var key in data) {
			tweet = data[key];
			var name = tweet.user.screen_name;
			if (name === user) {
				name = context.Linkify('@' + name);
				var id = tweet.id_str;
				var text = context.Linkify(tweet.text);
				var created = context.Timify(tweet.created_at);
				var html = '<div data-tweetid="' + id + '" class="tweet"><span class="tweet-user">' + name + '</span><span class="tweet-text">' + text + '</span> <span class="tweet-created">' + created + '</span></div>';
				$(html).appendTo(container);
			}
		} */
	},
	Linkify : function(text) {
		text = text.replace(/(https?:\/\/\S+)/gi, function (s) {
			return '<a href="' + s + '">' + s + '</a>';
		});
		text = text.replace(/(^|)@(\w+)/gi, function (s) {
			return '<a href="http://twitter.com/' + s + '">' + s + '</a>';
		});

		text = text.replace(/(^|)#(\w+)/gi, function (s) {
			return '<a href="http://search.twitter.com/search?q=' + s.replace(/#/,'%23') + '">' + s + '</a>';
		 });
		return text;
	},
	Timify : function(a) {
		var b = new Date();
		var c = new Date(a);
		var d = b - c;
		var e = 1000,
			minute = e * 60,
			hour = minute * 60,
			day = hour * 24,
			week = day * 7;
		if (isNaN(d) || d < 0) {
			return ""
		}
		if (d < e * 7) {
			return "right now"
		}
		if (d < minute) {
			return Math.floor(d / e) + " seconds ago"
		}
		if (d < minute * 2) {
			return "about 1 minute ago"
		}
		if (d < hour) {
			return Math.floor(d / minute) + " minutes ago"
		}
		if (d < hour * 2) {
			return "about 1 hour ago"
		}
		if (d < day) {
			return Math.floor(d / hour) + " hours ago"
		}
		if (d > day && d < day * 2) {
			return "yesterday"
		}
		if (d < day * 365) {
			return Math.floor(d / day) + " days ago"
		} else {
			return "over a year ago"
		}
	}
};
			
			
			
			
			

