/* 
	BLOX CORE EDITORIAL APPLICATION COMMON JS
	Last Update: 6/2/2009
*/

// 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,{}))

$(function() {

        // tooltips
        $('.tn-tooltip').tooltip({
	    track: true,
	    delay: 0,
	    showURL: false,
	    fade: 250
        });

	// profanity filter and replace
	$(".profanity").text("[expletive deleted]");

	// header definitions
	
	var searchTextEl = '#blox-search-form .search-bar';
	
	// externals
	$('a[rel="external"]').click(function(){
          window.open($(this).attr('href'));
          return false;
        });
	
	// set homepage
	$('#makeHomePage').click(function(){
		if(window.showModalDialog){
			setHomePage($(this).attr('href'));
			window.open($(this).attr('href'));
		} else {
			alert('Please drag this link onto home icon!');
		}
		return false;
	});
	
	
	// original login dialog box
	// login-dialog-popup (using ui.dialog.js | ui.draggable.js | ui.resizeable.js)
		//$.ui.dialog.defaults.bgiframe = true;
	//$('#login-dialog-popup').dialog({ autoOpen: false });
	//	$('.login-link').click(function() {
	//			$('#login-dialog-popup').dialog('open');
	//	});
	
	//$('#logout-dialog-popup').dialog({ autoOpen: false });	
	//	$('.logout-link').click(function() {
	//			$('#logout-dialog-popup').dialog('open');
	//	});
	
	
	
	
	// screen tabs
	$('#most_popular > ul').tabs();
	$('#market_place > ul').tabs();
	$('#blox-calendar-widget > ul').tabs({ fx: [null, { width: 'show' }] });
	
	// 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>';
			}
			$('#blox-center-piece ol').before('<div id="center-piece-nav"></div><div class="clear"></div>');
			$('#center-piece-nav').html(nStr);
		}
		
		// add paging event
		$('#center-piece-nav a').bind('click', function() {
			carousel.scroll($.jcarousel.intval($(this).text()));
			carousel.startAuto(0);
			return false;
		});
	};
	
	// init callback for centerpiece paging
	function cpPaging(carousel, state)
	{
		$('#center-piece-nav a').removeClass('selected');
		cpSelected = '#center-piece-page_'+carousel.first;
		$(cpSelected).addClass('selected');
	};
	
	
	// carousels
	$('#blox-slideshow-widget li, #blox-story-photos-page li, #blox-story-photos-children li, #blox-story-photos-keywords li, #blox-story-photos-sections li, #blox-slider-featured li, #blox-center-piece li,.blox-ticker li').show();
	$('#blox-slideshow-widget').jcarousel();
	$('#blox-slideshow-gallery2').jcarousel();

	// $('#blox-story-photos-page, #blox-story-photos-children, #blox-story-photos-keywords, #blox-story-photos-sections').jcarousel({scroll: 6,animation: 'slow' });
	// $('#blox-story-video-page').jcarousel({scroll: 6,animation: 'slow' });

	$('#blox-slider-featured').jcarousel({scroll: 2,animation: 'slow' });
	$('#blox-center-piece ol').jcarousel({
        auto: 10,
		scroll: 1,
		animation: 'slow',
		buttonNextHTML: null,
		buttonPrevHTML: null,
        wrap: 'last',
		itemLoadCallback: cpPaging,
        initCallback: centerPieceDisplay
    });
	$('.blox-ticker').jcarousel({
        auto: 6,
		scroll: 1,
		animation: false,
		buttonNextHTML: null,
		buttonPrevHTML: null,
        wrap: 'last'
    });

	// load yahoo content match
	//if($('#yahoo-contentmatch').length > 0){
	//	$.ajax({
	//		type: "GET",
	//		url: "/app/yahoo/contentmatch/index.php",
	//		data: "cat=" + $('#ycm_url_path').html() + '&ctxtUrl=' + location.href.escape,
	//		dataType: "html",
	//		success: function(result){ $('#yahoo-contentmatch').html(result); }
	//	});
	//}
	
	// load topad rss feeds
	$('.get-feed').each(function(){ 
		eval($(this).attr('title'));
		if(!feedLimit){ var feedLimit=''; }
		var rId = $(this).attr('id');
		if(rId && feedUrl){
			$.get("/app/scripts/rss/get.php", { type:feedType,limit:feedLimit,feed:feedUrl }, 
				function(result){ 
					$('#'+rId).html(result); 
				}
			);
		}
	});
	
	// get cookie
	var $cookie_name = 'sitename-FontSize';
	var originalFontSize = $('#blox-story-text').css('font-size');
	
	// if exists load saved value, otherwise store it
	if($.cookie($cookie_name)) {
		var $getSize = $.cookie($cookie_name);
		$('#blox-story-text').css({fontSize : $getSize + ($getSize.indexOf('px')!=-1 ? '' : 'px')}); // IE fix for double "pxpx" error
	} else {
		$.cookie($cookie_name, originalFontSize);
	}
		
	// Increase Font Size
	$('#large').click(function(){
		var currentFontSize = $('#blox-story-text').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum*1.2;
		$('#blox-story-text').css('font-size', newFontSize);
		return false;
	});
	// Decrease Font Size
	$('#default').click(function(){
		var currentFontSize = $('#blox-story-text').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum*0.8;
		$('#blox-story-text').css('font-size', newFontSize);
		return false;
	});
	
	// peel hack
	if($('#blox-peel-ad').length > 0){

		$('#blox-peel-container embed')
		.attr('allowScriptAccess','always')
		.attr('wmode','transparent')
		.attr('height','75')
		.attr('width','75');
		
		var peelHTML = $('#blox-peel-container div').html();
		
		$('#blox-peel-ad').html(peelHTML);
	}
// end doc ready
});

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


/* Poll */
jQuery(document).ready(function(){
 var pollCookies = jQuery('.blox-poll-asset .blox-poll .blox-poll-cookie');
 jQuery("#blox-poll .poll-option-wrapper .poll-view-options").hide();

  // if poll and cookie present
  if(pollCookies.length > 0){
    pollPosition = 0;
    jQuery.each(pollCookies,function(){
      var pollCookie = jQuery(this);
			
      if(jQuery.cookie(pollCookie.attr("title")) != null){
	  var pollPost = pollCookie.parent().find(".blox-poll-results form").attr('action');
	  var pollFlashPath = pollCookie.parent().find(".blox-poll-results form input[name='path']").val();
          getPollResults(pollPosition,pollPost,pollFlashPath);
	  
jQuery(jQuery('.poll-option-wrapper')[pollPosition]).find(".poll-submit").hide();
jQuery(jQuery('.poll-option-wrapper')[pollPosition]).find(".poll-view-results").hide(); 
jQuery(jQuery('.poll-option-wrapper')[pollPosition]).html("<strong>You voted</strong>: "+ jQuery.cookie(pollCookie.attr("title")));
	 
	jQuery(jQuery('.loading-poll')[pollPosition]).hide();
      } else {
	  jQuery(jQuery('.blox-poll')[pollPosition]).show();
	  jQuery(jQuery('.loading-poll')[pollPosition]).hide();
      }
      pollPosition++;
    });
  } else { jQuery(".loading-poll").css({'display':'none'}); }

  // view poll results without voting
  jQuery('.poll-view-results').bind("click",function(){
    var pollCount = jQuery(this).parents("form").find("input[name='number']").val();
    var pollFlashPath = jQuery(this).parents("form").find("input[name='path']").val();
    var pollPost = jQuery(this).parents("form").attr('action');

    jQuery(this).parents(".poll-option-wrapper").find(".poll-submit").hide();
    jQuery(this).parents(".poll-option-wrapper").find(".poll-view-results").hide();
    jQuery(this).parents(".poll-option-wrapper").find(".poll-view-options").show();
		
    getPollResults(pollCount,pollPost,pollFlashPath); 
  return false;});

  // view poll answers after viewing the results
  jQuery('.poll-view-options').bind("click",function(){
    jQuery(this).parents(".blox-poll").find(".blox-poll-output").hide();
    jQuery(this).parents(".blox-poll").find(".blox-poll-results").find(".poll-answers").show();

    jQuery(this).parents(".poll-option-wrapper").find(".poll-submit").show();
    jQuery(this).parents(".poll-option-wrapper").find(".poll-view-results").show();
    jQuery(this).parents(".poll-option-wrapper").find(".poll-view-options").hide();
  return false; });

  // poll submit action



  jQuery('.poll-vote-form').submit(function(){
    var pollPreview = jQuery(this).find("input[name='preview']").val();
    var pollFlashPath = jQuery(this).find("input[name='path']").val();
if(pollPreview=="true"){
     alert("Voting Disabled in Preview");
     return false;
}else{
    var pollId = jQuery(this).find("input[name='id']").val();
    var pollCount = jQuery(this).find("input[name='number']").val();
    var pollCookie = jQuery(jQuery('.blox-poll-asset .blox-poll .blox-poll-cookie')[pollCount]);
    var pollPost = jQuery(this).attr('action');
    var pollAction = jQuery(this).find("input[name='action']").val();
    var pollAnswer = jQuery(this).find("input[name='answer']:checked").val();
    var pollAnswerNice = jQuery(this).find("input[name='answer']:checked").attr('title');
	
    if(!pollAnswer){
      alert('Please make a selection!');
    return false;}

		
    jQuery.ajax({
      type: "POST",
      url: pollPost,
      data: "format=json&action=poll:vote&answer="+pollAnswer,
      success: function(result){ //alert("success");
	jQuery.cookie(pollCookie.attr("title"),pollAnswerNice);
	
	getPollResults(pollCount,pollPost,pollFlashPath,pollAnswerNice);
				
	jQuery(jQuery('.poll-option-wrapper')[pollCount]).find(".poll-submit").hide();
	jQuery(jQuery('.poll-option-wrapper')[pollCount]).find(".poll-view-results").hide();
	jQuery(jQuery('.poll-option-wrapper')[pollCount]).html("<strong>You voted</strong>: "+ pollAnswerNice);

	jQuery(jQuery('.loading-poll')[pollCount]).hide();
      }
    });
  return false; }
});

});

// get poll results
function getPollResults(pollId, pollPost, pollFlashPath, pollAnswer){
	jQuery.ajax({
		type: "GET",
		url: pollPost+'?action=poll:results',
		dataType: "json",
		success: function(result){ //alert("get poll results success");
			var bloxPoll=jQuery('#blox-poll').find(".blox-poll")[pollId];
			var chartType = jQuery(bloxPoll).find('.blox-poll-type').attr('title');
			var chartHeight = jQuery(bloxPoll).find('.blox-poll-height').attr('title');
			var chartWidth = jQuery(bloxPoll).find('.blox-poll-width').attr('title');
				
			var p=0;
			var pollXML = '';
			var pollSeries = '';
			var pollGraph = '';
			var pollColors = '';
			//if(pollAnswer != null){ alert(pollAnswer); }

			var swfFile = (chartType!='pie' ? 'amcolumn.swf' : 'ampie.swf');
			var poll = new SWFObject(pollFlashPath+swfFile, "ampie", chartWidth, chartHeight, "8", "#FFFFFF");
				
			// loop json and build xml per chart type
			jQuery.each(result.results,function(i,item){
				p++;
				if(chartType!='pie'){
					if(item.text == pollAnswer){
						pollSeries += "<value xid='"+p+"'><![CDATA["+item.text+"]]></value>";
						pollGraph += "<value xid='"+p+"' color='"+item.color+"'>"+(item.votes+1)+"</value>";
					} else {
						pollSeries += "<value xid='"+p+"'><![CDATA["+item.text+"]]></value>";
						pollGraph += "<value xid='"+p+"' color='"+item.color+"'>"+item.votes+"</value>";
					}
					pollColors +=item.color+',';
				} else {
					if(item.text == pollAnswer){
						pollXML += "<slice title='"+item.text+"'>"+(item.votes+1)+"</slice>";
					} else {
						pollXML += "<slice title='"+item.text+"'>"+item.votes+"</slice>";
					}
					pollColors +=item.color+',';
				}
			});
			
			if(chartType!='pie'){ //alert("chart type bar");
				poll.addVariable("path",pollFlashPath);
				poll.addVariable("chart_data", encodeURIComponent("<chart><series>"+pollSeries+"</series><graphs><graph>"+pollGraph+"</graph></graphs></chart>"));
				poll.addVariable("chart_settings", encodeURIComponent("<settings><type>column</type><data_type>xml</data_type><data_labels></data_labels><depth>10</depth><angle>30</angle><legend><enabled>false</enabled></legend><values><category><enabled>true</enabled></category><value><integers_only>true</integers_only></value></values><plot_area><margins><left>30</left></margins></plot_area></settings>"));
			} else { //alert("chart type pie");
				poll.addVariable("path",pollFlashPath);
				poll.addVariable("chart_data", encodeURIComponent('<pie>'+pollXML+'</pie>'));                   
				poll.addVariable("chart_settings", encodeURIComponent("<settings><data_type>xml</data_type><font>arial</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><x>140</x><y>100</y><radius>100</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><radius>-10%</radius><show></show><show_lines>false</show_lines></data_labels><plot_area><margins><top>30px</top></margins></plot_area><balloon><alpha>80</alpha></balloon><legend><y>225</y><enabled>true</enabled><values><enabled>true</enabled><text><![CDATA[{percents}%]]></text></values></legend></settings>"));
			}
			// write results
			jQuery("#blox-poll-results-"+pollId+" .poll-answers").hide();
			poll.write("blox-poll-output-"+pollId); 
			jQuery("#blox-poll-output-"+pollId).show();
			jQuery('.blox-poll').show();
		},
		complete: function(){ /*alert("get poll results complete"); */},
		error: function(XMLHttpRequest, textStatus, errorThrown){ /*alert('An Error Ocurred while getting poll results!' + errorThrown);*/ }
	});
}
