jQuery(document).ready(function(){

	$('.answer').click(function() {
		var form = $(this).parents('form');

		var question_id = form.children('[name="question_id"]').val();
		var answer_id;
		if (!(answer_id = $(this).val())) answer_id = $(this).attr('answer_id');
		
		
		$.post("/polls/ajax-vote.php", { "question_id" : question_id, "answer_id" : answer_id }, function(data) {
		
			if (data.success) {
				form.find('.response').html('<div style=\"color:green;padding:5px 0 5px 0;\">Thanks for voting!</div>' + '<div>' + data.html + '</div>');
				form.find('.answers').hide();
			}
			else {
				var error_msg;
				if (data.error) error_msg = data.error;
				else error_msg = 'Unknown error voting in poll';
				
				form.find('.response').html('<div style=\"color:red;\">' + error_msg + '</div>');

				if (data.html) form.find('.response').append(data.html);

				form.find('.answers').hide();
				
			}
		},"json");
		
		return true;
	});
	
	$('.sharebar').sharebar({horizontal:'true',swidth:'65',minwidth:1120,position:'left',leftOffset:25,rightOffset:10});	

	jQuery('.star').click(function()
	{	
		container = jQuery(this).parent().parent();
		raterValue = jQuery(this).children('a').attr('rating');
		
		jQuery.post("/ajax-vote.php", { "rating": raterValue, "object_id": container.attr('object_id') }, function(data){
			container.children('.star-rating-response').html(data.response);
			if (data.rating) {
				var newWidth = Math.floor(20 * data.rating);
				container.children('.star-rating').children('.current-rating').css({width:newWidth+'%'});				
				container.children('.star-rating-numeric').children('.value_swap').html(data.rating + " / 5.0");
			}

			if (data.total_votes) container.children('.star-rating-votes').children('.votes').html(data.total_votes);
		}, "json");
		
		return false;
	});


	jQuery('#detect-characters').click(function() {
		var quote = jQuery('#quote').val();

		//Remove emotions
		quote = quote.replace(/ \[[^\]]+\]:/,':');
		quote = quote.replace(/ \([^\)]+\):/,':');

		var foundCharacters = false;

		jQuery('.character').each(function() {
			var character = jQuery(this).attr('title');
			jQuery(this).removeAttr('checked');
			
			//Try Full Name First
			if (quote.indexOf(character + ':') != -1) jQuery(this).attr('checked','checked');			
			else { //Try individual names if unique
				var names = character.split(' ');
				for (i in names) {
					var name = names[i];
					name = name.replace('"',''); //Strip out quotes for nicknames
					name = name.replace('"',''); //Strip out quotes for nicknames
					if (jQuery('.character').filter(function (index) { return (jQuery(this).attr("title").search(name) != -1); }).length == 1) { //Unique!
						if (quote.toLowerCase().indexOf(name.toLowerCase() + ':') != -1) {
							jQuery(this).attr('checked','checked');			
							foundCharacters = true;
							break;
						}
					}
				
				}
			}
		});
	});
	
	$('.show').click(function() { //Eric show function will show the <a>'s target, hide .show button
		var target = $(this).attr('target');
		$(target).show();
		$(this).hide();
		
		//Store defaults of inputs in case they cancel
		$(target).children('input').each(function(index) {
			$(this).attr('restore_val',$(this).val());
		});
		
		return false;
	});

	$('.hide').click(function() { //Eric hide function will hide target div and show the .show button.  Also rest any form elements
		var target = $(this).attr('target');
		$(target).hide();		
		$('.show[target*="'+target+'"]').show();


		//Restore values of inputs in case they cancel
		$(target).children('input').each(function(index) {
			$(this).val($(this).attr('restore_val'));
		});

		return false;
	});	
});


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function login_update() //Use AJAX to just update dynamic parts
{
	var object_id;
	
	object_id = jQuery('#object_id').val();
	
	if (object_id > 0) {
		jQuery('#comment_box').load('/ajax/comment_box/' + object_id + '/');
	}
}




	
jQuery.fn.sharebar = function(options) {
	var defaults = {horizontal: true, swidth: 65, minwidth: 1000, position: 'left', leftOffset: 20, rightOffset: 10};
	var opts = jQuery.extend(defaults, options); var o = jQuery.meta ? jQuery.extend({}, opts, jQueryjQuery.data()) : opts;

	var w = jQuery(window).width();
	var sharebar = jQuery('#sharebar');
	var sharebarx = jQuery('#sharebarx');
	var parent = jQuery(sharebar).parent().width();
	var start = sharebar_init();

	function sharebar_init(){
		//jQuery(sharebar).css('width',o.swidth+'px');
		if (o.position == 'left') jQuery(sharebar).css('marginLeft',(0-o.swidth-o.leftOffset));
		else {
			jQuery(sharebar).css('marginLeft',(parent+o.rightOffset));
		}
		if(w < o.minwidth && o.horizontal) jQuery(sharebarx).slideDown();
		else jQuery(sharebar).fadeIn();
		jQuery.event.add(window, "scroll", sharebar_scroll);
		jQuery.event.add(window, "resize", sharebar_resize);
		if (jQuery(sharebar).offset()) return jQuery(sharebar).offset().top;
	}
	function sharebar_resize() {
		var w = jQuery(window).width();
		if(w<o.minwidth){
			jQuery(sharebar).fadeOut();
			if(o.horizontal) jQuery(sharebarx).slideDown();
		}else{
			jQuery(sharebar).fadeIn();
			if(o.horizontal) jQuery(sharebarx).slideUp();
		}
	}
	function sharebar_scroll() {
		var p = jQuery(window).scrollTop();
		var w = jQuery(window).width();
		jQuery(sharebar).css('position',((p+10)>start) ? 'fixed' : 'absolute');
		jQuery(sharebar).css('top',((p+10)>start) ? '10px' : '');
	}

};




// GA Analytics

/**
 * Namespace.
 * @type {Object}.
 */
var _ga = _ga || {};


/**
 * Ensure global _gaq Google Anlaytics queue has be initialized.
 * @type {Array}
 */
var _gaq = _gaq || [];


/**
 * Helper method to track social features. This assumes all the social
 * scripts / apis are loaded synchronously. If they are loaded async,
 * you might need to add the nextwork specific tracking call to the
 * a callback once the network's script has loaded.
 * @param {string} opt_pageUrl An optional URL to associate the social
 *     tracking with a particular page.
 * @param {string} opt_trackerName An optional name for the tracker object.
 */
_ga.trackSocial = function(opt_pageUrl, opt_trackerName) {
  _ga.trackFacebook(opt_pageUrl, opt_trackerName);
  _ga.trackTwitter(opt_pageUrl, opt_trackerName);
};


/**
 * Tracks Facebook likes, unlikes and sends by suscribing to the Facebook
 * JSAPI event model. Note: This will not track facebook buttons using the
 * iFrame method.
 * @param {string} opt_pageUrl An optional URL to associate the social
 *     tracking with a particular page.
 * @param {string} opt_trackerName An optional name for the tracker object.
 */
_ga.trackFacebook = function(opt_pageUrl, opt_trackerName) {
  var trackerName = _ga.buildTrackerName_(opt_trackerName);
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push([trackerName + '_trackSocial', 'facebook', 'like',
            targetUrl, opt_pageUrl]);
      });
      FB.Event.subscribe('edge.remove', function(targetUrl) {
        _gaq.push([trackerName + '_trackSocial', 'facebook', 'unlike',
            targetUrl, opt_pageUrl]);
      });
      FB.Event.subscribe('message.send', function(targetUrl) {
        _gaq.push([trackerName + '_trackSocial', 'facebook', 'send',
            targetUrl, opt_pageUrl]);
      });
    }
  } catch (e) {}
};


/**
 * Returns the normalized tracker name configuration parameter.
 * @param {string} opt_trackerName An optional name for the tracker object.
 * @return {string} If opt_trackerName is set, then the value appended with
 *     a . Otherwise an empty string.
 * @private
 */
_ga.buildTrackerName_ = function(opt_trackerName) {
  return opt_trackerName ? opt_trackerName + '.' : '';
};


/**
 * Tracks everytime a user clicks on a tweet button from Twitter.
 * This subscribes to the Twitter JS API event mechanism to listen for
 * clicks coming from this page. Details here:
 * http://dev.twitter.com/pages/intents-events#click
 * This method should be called once the twitter API has loaded.
 * @param {string} opt_pageUrl An optional URL to associate the social
 *     tracking with a particular page.
 * @param {string} opt_trackerName An optional name for the tracker object.
 */
_ga.trackTwitter = function(opt_pageUrl, opt_trackerName) {
  var trackerName = _ga.buildTrackerName_(opt_trackerName);
  try {
    if (twttr && twttr.events && twttr.events.bind) {
      twttr.events.bind('tweet', function(event) {
        if (event) {
          var targetUrl; // Default value is undefined.
          if (event.target && event.target.nodeName == 'IFRAME') {
            targetUrl = _ga.extractParamFromUri_(event.target.src, 'url');
          }
          _gaq.push([trackerName + '_trackSocial', 'twitter', 'tweet',
            targetUrl, opt_pageUrl]);
        }
      });
    }
  } catch (e) {}
};


/**
 * Extracts a query parameter value from a URI.
 * @param {string} uri The URI from which to extract the parameter.
 * @param {string} paramName The name of the query paramater to extract.
 * @return {string} The un-encoded value of the query paramater. underfined
 *     if there is no URI parameter.
 * @private
 */
_ga.extractParamFromUri_ = function(uri, paramName) {
  if (!uri) {
    return;
  }
  var uri = uri.split('#')[0];  // Remove anchor.
  var parts = uri.split('?');  // Check for query params.
  if (parts.length == 1) {
    return;
  }
  var query = decodeURI(parts[1]);

  // Find url param.
  paramName += '=';
  var params = query.split('&');
  for (var i = 0, param; param = params[i]; ++i) {
    if (param.indexOf(paramName) === 0) {
      return unescape(param.split('=')[1]);
    }
  }
  return;
};







//Drop down menu for tabs
var timeout	= 500;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer

function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose;
