/* 
	Lee Common JS
	Last Update: 4/7/2009
	Author: Ryan Davis <rdavis@qctimes.com>
*/

// cookie plugin
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}('r.5=w(k,d,a){4(m d!=\'H\'){a=a||{};4(d===p){d=\'\';a.3=-1}2 g=\'\';4(a.3&&(m a.3==\'n\'||a.3.u)){2 f;4(m a.3==\'n\'){f=G E();f.C(f.B()+(a.3*z*s*s*v))}o{f=a.3}g=\'; 3=\'+f.u()}2 b=a.7?\'; 7=\'+(a.7):\'\';2 e=a.9?\'; 9=\'+(a.9):\'\';2 l=a.t?\'; t\':\'\';6.5=[k,\'=\',K(d),g,b,e,l].I(\'\')}o{2 h=p;4(6.5&&6.5!=\'\'){2 c=6.5.F(\';\');D(2 i=0;i<c.8;i++){2 j=r.A(c[i]);4(j.q(0,k.8+1)==(k+\'=\')){h=y(j.q(k.8+1));x}}}J h}};',47,47,'||var|expires|if|cookie|document|path|length|domain|||||||||||||typeof|number|else|null|substring|jQuery|60|secure|toUTCString|1000|function|break|decodeURIComponent|24|trim|getTime|setTime|for|Date|split|new|undefined|join|return|encodeURIComponent'.split('|'),0,{}))

var j = jQuery.noConflict();
	
j(document).ready(function(){
	// globals
	var leeUser = j.cookie('SSID');
	
	// header definitions
	var leeMenu = '#blox-main-nav li';
	var leeMenuSelected = 'selected-nav';
	var leeSearchMenu = '#blox-search-nav';
	var searchTextEl = '#blox-search-form .search-bar';
	
	// loggedin box
	if(leeUser){
		j('#blox-user-nav').html('<span>Welcome:</span> <a href="#" class="logoutPort">Logout</a> | <a href="http://my.billingsgazette.com/editor/app/admin/tprofile.aspx?p=1" rel="external">Edit your account</a>');
	}
	// show user controls when loaded
	j('#blox-user-nav').show();
	j('.loading-block').hide();
	j('.loading').show();
	
	// externals
	j('a[rel="external"]').click(function(){
        window.open(j(this).attr('href'));
        return false;
    });
	
	// attach facebox events
	j('a[rel*=facebox]').facebox();
	
	// open login modal
	j('.openLoginBox').click(function(){
		j.facebox(function(){
  			j.get('/app/port/loginForm.php?',function(loginForm){
    			j.facebox(loginForm);
  			});
		});
		return false;
	});
	
	// logout
	j('.logoutPort').click(function(){
		j.cookie('SID', null, { path:'/' }); 
		j.cookie('SSID',null, { path:'/' }); 
		j.cookie('isAdminUser',null, { path:'/' }); 
		top.location.reload(true);
		return false;
	});
	
	// set homepage
	j('#makeHomePage').click(function(){
		if(window.showModalDialog){
			setHomePage(j(this).attr('href'));
			window.open(j(this).attr('href'));
		} else {
			alert('Please drag this link onto home icon!');
		}
		return false;
	});
	
	// lets look for toggle elements within the menu
	var isToggleMenu = j(leeMenu + ' .nav-toggle').length > 0 ? true : false;
	
	// global nav toggle
	function toggleMainNav(lObj){
		var nSelected = j(lObj).attr('class');
		j(leeMenu + '.' + leeMenuSelected).removeClass(leeMenuSelected);
		if(nSelected!=leeMenuSelected){
			j(lObj).addClass(leeMenuSelected);
		} else if(!isToggleMenu){
			j(lObj).addClass(leeMenuSelected);
		}
	}
	
	// add hover event
	if(!isToggleMenu){
		j(leeMenu + ' ,' + leeMenu+ 'span').mouseover(function(){
			toggleMainNav(this);
    	});
	}

	// add click event
	j(leeMenu + ' em.nav-toggle a, '+ leeMenu + ' em.nav-toggle-over a').click(function(){
		toggleMainNav(j(this).parent().parent());
		return false;
    });
	
	// search submit
	function bloxSearchSubmit(){ j('#blox-search-form').submit(); }
	j('#submit-search a').click(function(){ bloxSearchSubmit(); return false; });
	
	// search menu hover state
	j(leeSearchMenu + ' a').hover(function(){
		j(leeSearchMenu + ' a').removeClass('selected');
		j(this).addClass('selected');
	});
	
	// change search type
	j(leeSearchMenu + ' a').click(function(){
		var sType = j(this).attr('title');
		
		if(sType){
			switch(sType){
				case 'stories':
					j('#blox-search-form').attr('action','/search/');
				break;
				case 'web':
					j('#blox-search-form').attr('action','/app/yahoo/search/');
				break;
				case 'classifieds':
					j('#blox-search-form').attr('action','http://www2.billingsgazette.com/admarket/');
				break;
			}
			j(leeSearchMenu + ' #type').attr('value',sType);
			
			bloxSearchSubmit();
			return false;
		}
	});
	
	// remove yahoo search logo when value is present
	if(j(searchTextEl).val()){ j(searchTextEl).removeClass('yahoo'); }
	// remove logo on focus and add search menu
	j(searchTextEl).focus(function(){ 
		j(this).removeClass('yahoo'); 
		j(leeSearchMenu).show(); 
	});

	// add on blur when no value attr
	j(searchTextEl).blur(function(){ 
		if(!j(searchTextEl).val()){
			j(this).addClass('yahoo');
		}
	});
	
	// close search nav
	j(document).bind('click',function(cEvent){
		var documentID = j(cEvent.target);
		if(documentID.parent().parent().attr('id') != 'blox-search-form'){
			j(leeSearchMenu).hide();
		}
	});
	
	// screen tabs
	j('.init-blox-tabs > ul').tabs();
	j('#blox-calendar-widget > ul').tabs();
	
	// center piece widget
	function centerPieceDisplay(carousel)
	{
		// Pause autoscrolling if the user moves with the cursor over the clip.
		carousel.clip.hover(function() {
			carousel.stopAuto();
		}, function() {
			carousel.startAuto();
		});
		
		// add center piece navigation
		if(carousel.size() > 1){
			var nStr = '';
			for(i=1; i<=carousel.size(); i++){
				nStr += '<a id="center-piece-page_'+i+'" href="#'+i+'">'+i+'</a>';
			}
			j('#blox-center-piece ol').before('<div id="center-piece-nav"></div><div class="clear"></div>');
			j('#center-piece-nav').html(nStr);
		}
		
		// add paging event
		j('#center-piece-nav a').bind('click', function() {
			carousel.scroll(j.jcarousel.intval(j(this).text()));
			carousel.startAuto(0);
			return false;
		});
	};
	
	// init callback for centerpiece paging
	function cpPaging(carousel, state)
	{
		j('#center-piece-nav a').removeClass('selected');
		cpSelected = '#center-piece-page_'+carousel.first;
		j(cpSelected).addClass('selected');
	};
	
	// carousels
	j('#blox-slideshow-widget li,#blox-slider-featured li,#blox-center-piece li,.blox-ticker li').show();
	j('#blox-slideshow-widget').jcarousel();
	// story photo gal
	j('#blox-story-photos-page').jcarousel({
		scroll: 6,
		animation: 'slow'
	});
	// story photo click event
	j('#blox-story-photos-page a,#blox-story-photos a').click(function(){
		// img params
		var pictopiaURL = j('#pictopiaURL').attr('title');
		var thisImgHost = j('#siteHost').attr('title');
		var galTitle = j(this).attr('title');
		var galCutline = j(this).attr('name');
		var galByline = j(this).attr('rev');
		var galPhoto = j(this).attr('rel');
		var galPhotoHires = galPhoto.replace('.image.','.hires.');
		// add pictopia links
		if(j(this).children('img').attr('rel')=='buy_photo'){
			var pictopiaLink = pictopiaURL + '?photo_name='+galPhoto+'&title='+galTitle+'&t_url='+galPhoto+'&fs_url='+galPhotoHires+'&pps=buynow';
			j('#gallery-buy').attr('href',pictopiaLink).show();
		} else {
			j('#gallery-buy').hide();
		}
		// chang photo attributes
		j('h2#gallery-title').html(galTitle);
		j('#blox-large-photo-page #img-holder').attr('src',galPhoto);
		j('#gallery-cutline').html(galCutline);
		j('#gallery-byline').html(galByline);
		j('#blox-large-photo-page #img-holder').parent().attr('href',galPhoto);
		j('.blox-thumb-container a').removeClass('selected');
		// add selected class
		j(this).addClass('selected');
		return false;
	});
	
	j('#blox-slider-featured').jcarousel({scroll: 2,animation: 'slow' });
	j('#blox-center-piece ol').jcarousel({
        auto: 10,
		scroll: 1,
		animation: 'slow',
		buttonNextHTML: null,
		buttonPrevHTML: null,
        wrap: 'last',
		itemLoadCallback: cpPaging,
        initCallback: centerPieceDisplay
    });
	j('.blox-ticker').jcarousel({
        auto: 6,
		scroll: 1,
		animation: false,
		buttonNextHTML: null,
		buttonPrevHTML: null,
        wrap: 'last'
    });
	
	// load weather header
	if(j('#blox-weather').length > 0){
		j.ajax({
			type: "GET",
			url: "/app/weather/qwikcast_feed0.xml",
			dataType: "xml",
			success: function(xml)
			{
				var wData = j('data', xml);
				var wTemp =  j(wData).find('obs').attr('temp');
				var wTempUnit =  j(wData).find('obs').attr('tempUnit');
				var wCode =  j(wData).find('obs').attr('code');

				var icoPath ='global/resources/images/weather_icons/';
				// change to night icons
				icoTime = new Date();
				currIco = icoTime.getHours();
				if(currIco >= 19 || currIco < 6){
					icoPath = icoPath+'night/';
				}
				j('#blox-weather').css('background-image','url('+icoPath+wCode+'.gif)');
				j('#blox-weather #wTemp').html(wTemp+'&deg;');
				j('#blox-weather #wTempUnit').html(wTempUnit);

			}  
		}); 
	}

	// load yahoo content match
	if(j('#yahoo-contentmatch').length > 0){
		j.ajax({
			type: "GET",
			url: "/app/yahoo/contentmatch/index.php",
			data: "cat=" + j('#ycm_url_path').html() + '&ctxtUrl=' + location.href.escape,
			dataType: "html",
			success: function(result){ j('#yahoo-contentmatch').html(result); }
		});
	}
	
	// load topad rss feeds
	j('.get-feed').each(function(){ 
		eval(j(this).attr('title'));
		if(!feedLimit){ var feedLimit=''; }
		var rId = j(this).attr('id');
		if(rId && feedUrl){
			j.get("/app/scripts/rss/get.php", { type:feedType,limit:feedLimit,feed:feedUrl }, 
				function(result){ 
					j('#'+rId).html(result); 
				}
			);
		}
	});
	
	// get ajax objects
	j('.ajax-request').each(function(){ 
		var ajaxRequest = j(this).attr('title');
		var ajaxObj = j(this).attr('id');
		
		j.ajax({
			type: "GET",
			url: ajaxRequest,
			dataType: "html",
			success: function(result){ j('#'+ajaxObj).html(result); }
		});
	});
	
	// story font size div
	var currentFontSize = 13;
	var storyFontSizeDiv = '#blox-story-text';
	// cookie for story fontsize
	var storyFontSize = j.cookie('story-font-size');
	// if cookie was set load pref
	if(storyFontSize){
		currentFontSize = parseInt(storyFontSize);
		j(storyFontSizeDiv).css('font-size',storyFontSize+'px');
	}
	// lower font size up to 11px
	j('#story-font-size #default').click(function(){
		var cFont = currentFontSize;
		var fSize = parseInt(cFont-1);
	
		if(cFont >= 11){
			currentFontSize = fSize;
			j(storyFontSizeDiv).css('font-size',fSize+'px');
			j.cookie('story-font-size',fSize);
		}
		return false;
	});
	// enlarge font size up to 18px
	j('#story-font-size #large').click(function(){
		var cFont = currentFontSize;
		var fSize = parseInt(cFont+1);
		
		if(cFont <= 18){
			currentFontSize = fSize;
			j(storyFontSizeDiv).css('font-size',fSize+'px');
			j.cookie('story-font-size',fSize)
		}
		return false;
	});
	
	// get poll results
	function getPollResultsOld(pollPost)
	{
		j.ajax({
			type: "GET",
			url: pollPost+'?action=poll:results',
			dataType: "json",
			success: function(result){ 
				var chartType = j('#blox-poll #blox-poll-type').attr('title');
				var chartHeight = j('#blox-poll #blox-poll-height').attr('title');
				var chartWidth = j('#blox-poll #blox-poll-width').attr('title');
				
				var p=0;
				var pollXML = '';
				var pollSeries = '';
				var pollGraph = '';
				var pollColors = '';
				
				var swfFile = (chartType!='pie' ? 'amcolumn.swf' : 'ampie.swf');
				var poll = new SWFObject('/content/tncms/live/global/resources/flash/'+swfFile, "ampie", chartWidth, chartHeight, "8", "#FFFFFF");
				
				// loop json and build xml per chart type
				j.each(result.results,function(i,item){
					p++;
					if(chartType!='pie'){
						pollSeries += "<value xid='"+p+"'><![CDATA["+item.text+"]]></value>";
						pollGraph += "<value xid='"+p+"' color='"+item.color+"'>"+item.votes+"</value>";
					} else {
						pollXML += "<slice title='"+item.text+"'>"+item.votes+"</slice>";
						pollColors +=item.color+',';
					}
				});
				
				if(chartType!='pie'){
					poll.addVariable("path","/content/tncms/live/global/resources/flash/");
					poll.addVariable("chart_data", encodeURIComponent("<chart><series>"+pollSeries+"</series><graphs><graph>"+pollGraph+"</graph></graphs></chart>"));
					poll.addVariable("chart_settings", encodeURIComponent("<settings><type>bar</type><data_type>xml</data_type><font>Georgia</font><text_size>12</text_size><decimals_separator>.</decimals_separator><thousands_separator>,</thousands_separator><digits_after_decimal>2</digits_after_decimal><depth>10</depth><angle>30</angle><colors></colors><column><type></type><width>85</width><spacing>2</spacing><grow_time>2</grow_time><grow_effect></grow_effect><sequenced_grow>true</sequenced_grow><data_labels_text_color></data_labels_text_color><data_labels_text_size></data_labels_text_size><data_labels_position></data_labels_position></column><plot_area><margins><left>120</left></margins></plot_area><legend><enabled>false</enabled></legend></settings>"));
				} else {
					poll.addVariable("path","/content/tncms/live/global/resources/flash/");
					poll.addVariable("chart_data", encodeURIComponent('<pie>'+pollXML+'</pie>'));                   
					poll.addVariable("chart_settings", encodeURIComponent("<settings><data_type>xml</data_type><font>georgia</font><text_size>12</text_size><text_color>#000000</text_color><decimals_separator>.</decimals_separator><thousands_separator>,</thousands_separator><digits_after_decimal>1</digits_after_decimal><pie><radius>90</radius><height>10</height><angle>15</angle><start_angle>90</start_angle><colors>"+pollColors+"</colors></pie><animation><start_time>2</start_time><start_effect>regular</start_effect><pull_out_on_click></pull_out_on_click><pull_out_time>1.5</pull_out_time><pull_out_only_one>true</pull_out_only_one></animation><data_labels><show><![CDATA[{title}: {percents}%]]></show></data_labels><balloon><alpha>80</alpha></balloon><legend><enabled>false</enabled></legend></settings>"));
				}
				// write results
				poll.write("blox-poll-results");
			}
		});
	}

	// get poll results
	function getPollResults(pollPost) {

			j.ajax({
				type: "GET",
				url: pollPost+'?action=poll:results',
				dataType: "json",
				success: function(result){

					var chartType = j('#blox-poll #blox-poll-type').attr('title');
					var chartHeight = j('#blox-poll #blox-poll-height').attr('title');
					var chartWidth = j('#blox-poll #blox-poll-width').attr('title');

					if(chartType=='pie') {
					
					var p=0;
					var pollXML = '';
					var pollSeries = '';
					var pollGraph = '';
					var pollColors = '';
					
					var poll = new SWFObject('/content/tncms/live/global/resources/flash/ampie.swf', "ampie", chartWidth, chartHeight, "8", "#FFFFFF");
					
					// loop json and build xml per chart type
					j.each(result.results,function(i,item){
						p++;
						pollXML += "<slice title='"+item.text+"'>"+item.votes+"</slice>";
						pollColors +=item.color+',';
					});

					poll.addVariable("path","/content/tncms/live/global/resources/flash/");
					poll.addVariable("chart_data", encodeURIComponent('<pie>'+pollXML+'</pie>'));                   
					poll.addVariable("chart_settings", encodeURIComponent("<settings><data_type>xml</data_type><font>georgia</font><text_size>12</text_size><text_color>#000000</text_color><decimals_separator>.</decimals_separator><thousands_separator>,</thousands_separator><digits_after_decimal>1</digits_after_decimal><pie><radius>90</radius><height>10</height><angle>15</angle><start_angle>90</start_angle><colors>"+pollColors+"</colors></pie><animation><start_time>2</start_time><start_effect>regular</start_effect><pull_out_on_click></pull_out_on_click><pull_out_time>1.5</pull_out_time><pull_out_only_one>true</pull_out_only_one></animation><data_labels><show><![CDATA[{title}: {percents}%]]></show></data_labels><balloon><alpha>80</alpha></balloon><legend><enabled>false</enabled></legend></settings>"));

					// write results
					poll.write("blox-poll-results");

					} else {

					var p=0;
					var totalVotes = 0;
					var results_html = "<div id='poll-container'><div id='poll-results'><dl class='graph'>\n";

					// loop json to find total votes
					j.each(result.results,function(i,item){
						totalVotes += item.votes;
					});
					
					// loop json and build xml per chart type
					j.each(result.results,function(i,item){
						p++;
						var percent = 0;
						var barwidth = 1;
						if(totalVotes > 0) {
							percent = Math.round((item.votes / totalVotes) * 100);
							if(percent > 0) { barwidth = percent; }
						}

						results_html += "<dt class='bar-title'>"+item.text+"</dt><dd class='bar-container'><div id='bar"+p+"'style='width:"+barwidth+"%;background-color:"+item.color+";'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";

					});

					results_html += "</dl><p>Total Votes: "+totalVotes+"</p></div></div>\n";
					
					// write results
					j('#blox-poll-results').replaceWith(results_html);
					
					}
				}
			});

        }
	
	// poll cookie
	var pollCookie = j('#blox-poll #blox-poll-cookie').attr('title');
	// if poll and cookie present
	if(j('#blox-poll').length > 0){
		j('#blox-poll').show();
		j('.loading-poll').hide();
		if(j.cookie(pollCookie)){
			j('.loading-poll').show().html('<strong>You voted</strong>: '+ j.cookie(pollCookie));
			var pollPost = j('#poll-vote-form').attr('action');
			getPollResults(pollPost);
		}
	}
	
	// poll submit action
	j('#poll-vote-form').submit(function(){
		var pollPost = j(this).attr('action');
		var pollAnswer = j("#poll-vote-form input[@name='answer']:checked").val();
		var pollAnswerNice = j("#poll-vote-form input[@name='answer']:checked").attr('title');
		
		if(!pollAnswer){
			alert('Please make a selection!');
			return false;
		}
		
		j.ajax({
			type: "POST",
			url: pollPost,
			data: "format=json&action=poll:vote&answer="+pollAnswer,
			success: function(result){ 
				// set cookie
				j.cookie(pollCookie,pollAnswerNice);
				// grab results
				getPollResults(pollPost); 
			},
			error: function(result){ alert('An Error Ocurred!'); }
		});
		
		return false;
	});
// end doc ready
});

// peel ad expand
function peelAd(w,h){
	j('#blox-peel-ad embed').attr('height',w).attr('width',h);
}

// load weather header
	if(j('#blox-weather').length > 0){
		j.ajax({
			type: "GET",
			url: "/app/weather/qwikcast_feed0.xml",
			dataType: "xml",
			success: function(xml)
			{
				var xPathNode= j('data>obs', xml);
				var wData = {};
				xPathNode.children().each(function(){
					wData[this.tagName] = j(this).text();
				});
				var icoPath ='/content/tncms/live/global/resources/images/weather_icons/';
				// change to night icons
				icoTime = new Date();
				currIco = icoTime.getHours();
				if(currIco >= 19 || currIco < 6){
					icoPath = icoPath+'night/';
				}
				j('#blox-weather').css('background-image','url('+icoPath+wData['code']+'.gif)');
				j('#blox-weather #wTemp').html(wData['temp']+'&deg;');
				j('#blox-weather #wTempUnit').html(wData['tempUnit']);
			}  
		}); 
	}