//$Id: grupthink.js 4850 2011-08-30 22:02:07Z ssundheim $

var fadeballot;
var pollid;
var fullboxID;


/* JQUERY STUFF */
/* Change framerate for Jquery effects (milliseconds)  */
jQuery.fx.interval = 20;

/* Site-wide Jquery-driven behaviors */
$(function(){ 
// Hide the adv search box when user clicks outside header
  $("#header").bind( "clickoutside", function(event){
	$("#advsearch").hide();
  });
  
//FancyBox	
  /* Apply fancybox to multiple items */ 
  $("a.lightbox").fancybox({
	  'transitionIn'	:	'elastic',
	  'transitionOut'	:	'elastic',
	  'speedIn'		    :	200, 
	  'speedOut'	    :	200, 
	  'overlayShow'	    :	true,
	  'type'            :   'image',
	  'showCloseButton'    : true,
	  'enableEscapeButton' : true
  });
});
/* End JQuery behaviors */

//Get URL values passed in the hash "#"
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('!') + 1).split('&'); 
	//Note, you can change the '#' to '?' if you want the 'real" query string values
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;	
}

/* TInyMCE- Related */
/* This will initialize TinyMCE editor on textareas with class "richedit" */

function initTinyMCE(admin) {
   //Show advanced styling if this is an elevated member
   admincontrols = '';
   if(admin){
       admincontrols = ',|,forecolor,backcolor,code';
   }   
   
   // Now, do the normal TinyMCE initialization
   $('textarea.richedit').tinymce({
      script_url : '/libs/tinymce/jscripts/tiny_mce/tiny_mce.js',
	  mode : "specific_textareas",
	  editor_selector : "richedit",
	  theme : "advanced",
	  extended_valid_elements : "textarea[cols|rows|disabled|name|readonly|class],pre[name|class]", 
	  oninit : "setPlainText",
	  plugins : "safari,style,advhr,advlink,contextmenu,paste,noneditable,xhtmlxtras,syntaxhl",  
	  // Theme options
	  theme_advanced_buttons1 : "formatselect,|,syntaxhl,bold,italic,strikethrough,blockquote,bullist,numlist,outdent,indent"+admincontrols,
	  theme_advanced_buttons2 : "",
	  theme_advanced_buttons3 : "",
	  theme_advanced_toolbar_location : "top",
	  theme_advanced_toolbar_align : "left",
	  theme_advanced_statusbar_location : "bottom",
	  theme_advanced_resizing : true,
	  theme_advanced_blockformats : "p,pre",
	  content_css : "/css/style_screen.css"
	  
   });	
	
}

/* End TinyMCE */

/* Syntax HIghlighter */

	/*Set paths for autoload*/

function initSyntaxHighlighter() {
	
	SyntaxHighlighter.autoloader(
	  'js jscript javascript  /libs/syntaxhighlighter/scripts/shBrushJScript.js',
	  'applescript            /libs/syntaxhighlighter/scripts/shBrushAppleScript.js',
	  'actionscript3 as3      /libs/syntaxhighlighter/scripts/shBrushAS3.js',
	  'bash shell             /libs/syntaxhighlighter/scripts/shBrushBash.js',
	  'coldfusion cf          /libs/syntaxhighlighter/scripts/shBrushColdFusion.js',
	  'cpp c                  /libs/syntaxhighlighter/scripts/shBrushCpp.js',
	  'c# c-sharp csharp      /libs/syntaxhighlighter/scripts/shBrushCSharp.js',
	  'css                    /libs/syntaxhighlighter/scripts/shBrushCss.js',
	  'delphi pascal          /libs/syntaxhighlighter/scripts/shBrushDelphi.js',
	  'diff patch pas         /libs/syntaxhighlighter/scripts/shBrushDiff.js',
	  'erl erlang             /libs/syntaxhighlighter/scripts/shBrushErlang.js',
	  'groovy                 /libs/syntaxhighlighter/scripts/shBrushGroovy.js',
	  'java                   /libs/syntaxhighlighter/scripts/shBrushJava.js',
	  'jfx javafx             /libs/syntaxhighlighter/scripts/shBrushJavaFX.js',
	  'js jscript javascript  /libs/syntaxhighlighter/scripts/shBrushJScript.js',
	  'perl pl                /libs/syntaxhighlighter/scripts/shBrushPerl.js',
	  'php                    /libs/syntaxhighlighter/scripts/shBrushPhp.js',
	  'text plain             /libs/syntaxhighlighter/scripts/shBrushPlain.js',
	  'py python              /libs/syntaxhighlighter/scripts/shBrushPython.js',
	  'ruby rails ror rb      /libs/syntaxhighlighter/scripts/shBrushRuby.js',
	  'sass scss              /libs/syntaxhighlighter/scripts/shBrushSass.js',
	  'scala                  /libs/syntaxhighlighter/scripts/shBrushScala.js',
	  'sql                    /libs/syntaxhighlighter/scripts/shBrushSql.js',
	  'vb vbnet               /libs/syntaxhighlighter/scripts/shBrushVb.js',
	  'xml xhtml xslt html    /libs/syntaxhighlighter/scripts/shBrushXml.js'
	);
	
	
	/*options*/
	SyntaxHighlighter.defaults['gutter'] = false;
	
	SyntaxHighlighter.all();
}
/* End Syntax Highlighter*/


function fetchfeedViaHash(defaulttype, grupID) {
	
    //if the feed is already trying to load something, ajax could be stuck on something, so let's reload the whole page.
	if($('#feed_table').hasClass('faded')) {window.location.reload();}
		
	//Read any URL parameters in the hash
	var req_feed_type = getUrlVars()["t"];
	var req_feed_page = getUrlVars()["p"];
	var req_feed_tag = getUrlVars()["tag"];
	//Use defaults if the values above aren't set
	if(typeof req_feed_page == "undefined") { req_feed_page = 1; }		
	if(typeof req_feed_type == "undefined") { req_feed_type = defaulttype;}
	
	fetchFeed(req_feed_type, 1, grupID, req_feed_tag, req_feed_page);	
}

/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
/* End jQuery hashchange event code */

/*
 * jQuery outside events - v1.1 - 3/16/2010
 * http://benalman.com/projects/jquery-outside-events-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,c,b){$.map("click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup".split(" "),function(d){a(d)});a("focusin","focus"+b);a("focusout","blur"+b);$.addOutsideEvent=a;function a(g,e){e=e||g+b;var d=$(),h=g+"."+e+"-special-event";$.event.special[e]={setup:function(){d=d.add(this);if(d.length===1){$(c).bind(h,f)}},teardown:function(){d=d.not(this);if(d.length===0){$(c).unbind(h)}},add:function(i){var j=i.handler;i.handler=function(l,k){l.target=k;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!==i.target&&!j.has(i.target).length){j.triggerHandler(e,[i.target])}})}}})(jQuery,document,"outside");
/*  End Jquery Outside Events Code */

/* END JQUERY STUFF */

function changeText(containerID, text) {
	$('#'+containerID).html(text);
}


function htmlEntityDecode(str) {
	var ta = document.createElement("textarea");
	ta.innerHTML = str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}


function viewanyway(answerID) {
  
  answersummary = 'answersummary' + answerID
  votebutton = 'votebutton_spot' + answerID;
  answerimage = 'answerimage' + answerID;
  message_more = 'showmore' + answerID;
  message_less = 'showless' + answerID;
  
  toggleme(answersummary); 
  toggleme(votebutton,0); 
  toggleme(answerimage, 0);
  toggleme(message_more, 0);
  toggleme(message_less, 0);
  
}


function gotopage(pagenum) {
	document.samesearch.page.value = pagenum;
	document.samesearch.submit();
}
	
function sortme(column) {
	if (column == 'voters') {
		if (document.samesearch.sortby.value == 'num_voters') { 
			// They clicked what it was already sorted by so we'll change direction
			if (document.samesearch.sortdir.value == 'DESC') {
				document.samesearch.sortdir.value = 'ASC';
			} else {
				document.samesearch.sortdir.value = 'DESC';
			}
		}
		else 
		{
			document.samesearch.sortby.value = 'num_voters';
			document.samesearch.sortdir.value = 'DESC';
		}
   	} else {
		if (document.samesearch.sortby.value == 'topic_date') { 
			// they clicked the same sortby, lets change dir
			if (document.samesearch.sortdir.value == 'DESC') {
				document.samesearch.sortdir.value = 'ASC';
			} else {
				document.samesearch.sortdir.value = 'DESC';
			}
		} else {
			document.samesearch.sortby.value = 'topic_date';
			document.samesearch.sortdir.value = 'DESC';
		}
	}
	document.samesearch.submit();
}

function speak (id, what) {
	var element = document.getElementById(id);
	element.innerHTML = 'Clicked ' + what;
}

function showBallotError(input, results, success) {
    alert(results[0].getElementsByTagName('errortext')[0].firstChild.data);

	// If they also told us to reload the ballot, then we are going to
	if (results[0].getElementsByTagName('ballotreload')[0].firstChild.data == 'reload') {	
		var topicID = results[0].getElementsByTagName('topicid')[0].firstChild.data;
		var userConfirmReload = confirm('Click "OK" to re-sync your ballot.');
		if (userConfirmReload) {
			window.location.reload();
		}
	}
}
	
function showcommentform(form_element, input_element) {
  	toggleme(form_element); 
  
  	if(document.getElementById(form_element).style.display != 'none' && document.getElementById(form_element) != null) { 
		// if comment form is visible, put focus on input field 
		document.getElementById(input_element).focus(); 
	}
}

function storeanswerdatainsession() {
	var desc = encodeURI(document.answers.description.value);
	var topicid = document.answers.topicid.value;
	var postString = 'desc=' + desc + '&topicid=' +topicid;
	var postURI = '/ajaxserver/ainfosession.php5';

	// now prevent IE caching
	var d = new Date();
	var t = d.getTime();
	postString += '&TIME=' + t;

	loadXMLDocPost(postURI, postString);
}

function storetopicdatainsession() {
	var tags = encodeURI(document.newquestion.tags.value);
	var megatagString = 'mega';
	var megatags = '';
	var topicForm = document.newquestion;
	var topicFormElements = topicForm.elements;
	for (ii=0; ii<=topicFormElements.length; ii++) {
		var topicElement = topicFormElements[ii];
		if (topicElement != null) {
			if (topicElement.type == 'checkbox') {
				if (topicElement.name.indexOf(megatagString) != -1) {
					if (topicElement.checked) {
						megatags += topicElement.value + ',';
					}
				}
			}
		}
	}

	var body = encodeURI(document.newquestion.description.value);
	var postString = 'tags=' + tags + '&body=' + body + '&megatags=' + megatags;
	var grupidElement = document.newquestion.grupid;
	if (grupidElement != null) {
		var grupid = grupidElement.value;
		postString += '&grupid=' + grupid;
		if (document.getElementById('privacytypewideopen').checked) {
			var grupprivacytype = 'wideopen';
		} else if (document.getElementById('privacytypepanel').checked) {
			var grupprivacytype = 'panel';
		} else {
			var grupprivacytype = 'privateroom';
		}
		postString += '&grupprivacytype=' + grupprivacytype;
		postString += '&publistperm=';
		if (document.getElementById('publistperm').checked) {
			postString += '1';
		} else {
			postString += '0';
		}
	}
	var postURI = '/ajaxserver/qinfoinsession.php5';

	// now prevent IE caching
	var d = new Date();
	var t = d.getTime();
	postString += '&TIME=' + t;

	loadXMLDocPost(postURI, postString);
}

function redirectToAsk(input, results, success) {
	grupid = results[0].getElementsByTagName('grupid')[0].firstChild.data;
	if (grupid != 0) {
		var uri = '/ask/?grupid=' + grupid;
	} else {
		var uri = '/ask/';
	}
	document.location = uri;
}

function redirectToAdd(input, results, success) {
	topicid = results[0].getElementsByTagName('topicid')[0].firstChild.data;
	var uri = '/answer/add.php5?topicid=' + topicid;
	document.location = uri;
}

//The AJAX call and response functions for next/prev topic filter
function setTopicFilter(topicid, filtertype, override) {
	var postString = 'topicid='+topicid+'&filtertype='+filtertype;
	if (override == 'False') {
		postString += '&override=false';
	}
	// now prevent IE caching   
	var d = new Date();
	var t = d.getTime();
	postString += '&amp;TIME=' + t;
	var postURI = '/ajaxserver/settopicfilter.php5';
	loadXMLDocPost(postURI, postString);
}


function setTopicFilterAnswer(topicid, filtertype) {
	var postString = 'answerid='+topicid+'&filtertype='+filtertype;
	// now prevent IE caching   
	var d = new Date();
	var t = d.getTime();
	postString += '&amp;TIME=' + t;
	var postURI = '/ajaxserver/settopicfilter.php5';
	loadXMLDocPost(postURI, postString);
}

function viewTopicFiltered(input, results, success) {
   newloc = "/topic/" + results[0].getElementsByTagName('topicid')[0].firstChild.data;
   document.location = newloc;
}

function viewTopicFilteredAnswer(input, results, success) {
   newloc = "/answer/" + results[0].getElementsByTagName('answerid')[0].firstChild.data;
   document.location = newloc;
}



function stripHTML(text) {
  var re= /<\S[^><]*>/g;
  return text.value.replace(re, "");
}

// For limiting the length on text areas
function checkinputlength(field, maxlimit) {
	if (field != null) {
		if (field.value.length > maxlimit) {
			field.value = field.value.substring(0, maxlimit);
			alert("Your input has been truncated. There is a " + maxlimit + " character limit on this field.");
		}
	}
}


// SHOW/HIDE Hint popup
function togglehintpop() {      
	//Functions that grab screen dimensions
   	var arrayPageSize = getPageSize(); 
	var arrayPageScroll = getPageScroll(); 
	
	//ID's for affected html elements	
	hintboxID = 'hintpop'; 
	
	hintbox = document.getElementById(hintboxID);
	if (hintbox != null) {
		hintbox.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 500) / 2) + 'px'); 
		hintbox.style.left = (((arrayPageSize[0] - 500) / 2) + 'px');
	}
	   
	toggleme(hintboxID);   
}

function closefull() {
	/* This used to be used for our home-grown lightbox code. Now it's only used to close license pop-up notifications */ 
	if (document.getElementById('linkaccountserror') == null) {
		toggleme('fullimagebox');
		if (document.getElementById('fulllicensebox') != null && document.getElementById('fulllicensebox').style.display != 'none') {
			toggleme('fulllicensebox');
		}
		// Bug in IE6 where dropdown boxes show through
		var dropDowns = document.getElementsByTagName('select');
		for (var ii = 0; ii < dropDowns.length; ii++) {
			if (dropDowns[ii].style.display == 'none') {
				dropDowns[ii].style.display = '';
			} else {
				dropDowns[ii].style.display = 'none';
			}
		}
	}
}

function closeVotingPopup(dontRemind) {
	if (document.getElementById('votingreminder') != null) {
		if (dontRemind == "never") {
			// Then we are going to start an ajax transaction
			var ajaxurl = '/ajaxserver/dontremindvotingpopup.php5';
			var postString = 'dontremind=1';
			
			// Prevent IE caching
			var d = new Date();
			var t = d.getTime();
			postString += '&TIME=' + t;
			loadXMLDocPost(ajaxurl, postString);
		} else {
			finishClosingVotingPopup();
		}
	}
}

function closeRankingPopup(dontRemind) {
	if (document.getElementById('rankingreminder') != null) {
		if (dontRemind == "never") {
			// Then we are going to start some AJAX action
			var ajaxurl = '/ajaxserver/dontremindrankingpopup.php5';
			var postString = 'dontremind=1';
			
			// Prevent IE caching
			var d = new Date();
			var t = d.getTime();
			postString += '&TIME=' + t;
			loadXMLDocPost(ajaxurl, postString);
		} else {
			finishClosingRankingPopup();
		}
	}
}

function finishClosingVotingPopup() {
	var votingReminder = document.getElementById('votingreminder');
	if (votingReminder != null) {
		hideme('votingreminder');
	}
}

function finishClosingRankingPopup() {
	var votingReminder = document.getElementById('rankingreminder');
	if (votingReminder != null) {
		hideme('rankingreminder');
	}
}

// SHOW/HIDE ITEMS

function delay() {
  return true;	
}

function toggleme(id,fade) //Set fade to 0 if you don't want the fade effect. Default is on.
{	
	el = document.getElementById(id); 
	// Make sure the element actually exists
	if (el != null) {
		if (el.style.display == 'none' && fade != 0) {
			fademein(id, fade);
		}
		else if (el.style.display == 'none') {
			$(el).show();
		}
		else {
			// We are going to hide it
			el.style.display = 'none'; 	   
		}
	}
}


function toggleme2(element) {
 
  if(document.getElementById(element).style.visibility =='hidden') {
	showme(element);
  }  else {
	document.getElementById(element).style.visibility ='hidden'; 	   
  }
}

function showme(element,fade) //Set fade to 0 if you don't want the fade effect. Default is on.
{ 
	if (document.getElementById(element) != null) {
		if( document.getElementById(element).style.display == 'none') {
			fademein(element, fade);
		}
		
		if (document.getElementById(element).style.visibility == 'hidden') {
			document.getElementById(element).style.display ='none'; //Temporary kludge: doing this for JQuery's sake
			document.getElementById(element).style.visibility ='visible'; 
			fademein(element, fade);
		}
	}
}

function hideme(elementID, visibilityonly) {
  element = document.getElementById(elementID);
  if(visibilityonly == 1) {
    element.style.visibility = 'hidden';
  } else if(element.style.display != 'none') {
	element.style.display ='none'; 
  }
}

// END SHOW/HIDE ITEMS

//GENERAL FADE EFFECTS FOR UNIQUE ELEMENTS
function fademein(element) {
   /*JQuery*/
   $('#'+element).fadeIn('slow', function(){
   });
}

function fademeout(element) {
   /*JQuery*/
   $('#'+element).fadeOut('slow', function(){
   });
}
//END GENERAL FADE EFFECTS


function el(name) {
  return document.getElementById( name );
}


function changedisplay(element,display) {
  if (display=='on') {  document.getElementById(element).style.display =''; } else { document.getElementById(element).style.display ='none';}
}


// Change style class on any object
function changeclass(id, newClass) {
	identity = document.getElementById(id);
	if (identity != null) {
		identity.className = newClass;
	}
}


// Toggle between two classes on an object. Third value (class2) is optional.
function toggleclass(id, class1, class2) {
	if (typeof class2 == 'undefined') {  
		class2 = '';
	}
	identity = document.getElementById(id);
	if (identity != null) {
		if (identity.className==class1) {
			identity.className=class2;
		} else {
			identity.className=class1; 
		}
	}
}	

/* Month and year values must be in two-digit format, eg "09" */
function chooseTime(beginMonth, beginYear) {
	document.getElementById('timelineFilterStart').value = beginMonth+'/'+beginYear;
	//alert(beginMonth + ' ' + beginYear);
	document.frmTimelineFilter.submit();
}	

function getPolls( search, searchdisp, userid ) {
   document.mysearch.advsearchoptions.value = search;
   document.mysearch.searchtxt.value = searchdisp;
   if( document.mysearch.userid )
     document.mysearch.userid.value = userid;
   document.mysearch.submit();
}

function disableAnswerSubmit() {
	showme('submit_progress');
	hideme('answersubmit_container');
}

function addToNotify(topicid) {
	var topicid = topicid;
	var postURI = '/ajaxserver/addtonotify.php5';
	
	// now prevent IE caching
	var d = new Date();
	var t = d.getTime();
	postString = 'topicid=' + topicid + '&TIME=' + t;

	// Now send the request away
	loadXMLDocPost(postURI, postString);
}

function addNotifyDone( input, results, success ) {
	
	showme( 'notifymsg' );
	hideme( 'removenotifymsg' );
	showme( 'notifymeoff' );
	hideme( 'notifyme' );	
}

function removeFromNotify(topicid) {
	var topicid = topicid;
	var postURI = '/ajaxserver/removefromnotify.php5';
	
	// now prevent IE caching
	var d = new Date();
	var t = d.getTime();
	postString = 'topicid=' + topicid + '&TIME=' + t;

	// Now send the request away
	loadXMLDocPost(postURI, postString);
}

function removeFromNotifyDone( input, results, success ) {
	showme( 'notifyme' );
	hideme( 'notifymeoff' );
	showme( 'removenotifymsg' );
	hideme( 'notifymsg' );
}

function commentNotify(contentid, contenttype, remove) {
	var contentid = contentid;
	var contenttype = contenttype;
	var remove = remove;
	var postURI = '/ajaxserver/commentnotify.php5';
	
	// now prevent IE caching
	var d = new Date();
	var t = d.getTime();
	postString = 'contentid=' + contentid + '&contenttype=' + contenttype + '&remove=' + remove + '&TIME=' + t;

	// Now send the request away
	loadXMLDocPost(postURI, postString);
}

function commentNotifyDone( input, results, success ) {
  var removeaction = results[0].getElementsByTagName('actionremove')[0].firstChild.data;
  
  var modmsg = document.getElementById( 'answerremovenotifymsg' );
  if (modmsg != undefined)
     modmsg.style.display = 'none';
  var modmsg = document.getElementById( 'answernotifymsg' );
  if (modmsg != undefined)
     modmsg.style.display = 'none';
  
  if (removeaction == "0") // we removed the notification
  {
     hideme( 'removenotifymsg' );
     showme( 'notifymsg' );
     hideme( 'notifyme' );
     showme( 'notifymeoff' );
  } else {
     showme( 'removenotifymsg' );
     hideme( 'notifymsg' );
     showme( 'notifyme' );
     hideme( 'notifymeoff' );
  }
}

function modComment( id, mod ) {
  var ajaxurl = '/ajaxserver/modcomment.php5?id=' + id + '&mod=' + mod;
  loadXMLDoc(ajaxurl);
}

function modCommentDone( input, results, success ) {
  var id = results[0].getElementsByTagName('commentid')[0].firstChild.data;
  id = parseInt( id, 10 );
  var mod = results[0].getElementsByTagName('moderation')[0].firstChild.data;

  // first, turn them all on
  document.getElementById( 'modhelpful' + id ).className = '';
  document.getElementById( 'modunhelpful' + id ).className = '';
  document.getElementById( 'modinappropriate' + id ).className = '';

  // then, turn the selected one off
  document.getElementById( 'mod' + mod + id ).className = 'disabled';

  var modmsg = document.getElementById( 'commentmodmsg' + id );
  modmsg.style.display = '';
}

function modAnswer( id, mod, deleteme ) {
  var ajaxurl = '/ajaxserver/modanswer.php5?id=' + id + '&mod=' + mod;
  if (deleteme)
     ajaxurl += '&delete=1';
  // now prevent IE caching
   var d = new Date();
   var t = d.getTime();
   ajaxurl += '&TIME=' + t;
  loadXMLDoc(ajaxurl);
}

function modAnswerDone( input, results, success ) {
  var id = results[0].getElementsByTagName('answerid')[0].firstChild.data;
  id = parseInt( id, 10 );
  var mod = results[0].getElementsByTagName('moderation')[0].firstChild.data;
  var on = results[0].getElementsByTagName('on')[0].firstChild.data;

  // first, turn them all on
  //document.getElementById( 'modinappropriate' + id ).className = '';
  //document.getElementById( 'modadult' + id ).className = '';

  // then, turn the selected one off
  // document.getElementById( 'mod' + mod + id ).className = 'disabled';
  
  if (mod == 'adult') {
     var modadult = document.getElementById( 'modadult' + id);
     if (on == "1") {
        modadult.firstChild.data = 'Not Adult';
        modadulton = true;
     } else {
        modadult.firstChild.data = 'Adult';
        modadulton = false;
     }
  } else if (mod == 'inappropriate') {
     var modinap = document.getElementById( 'modinappropriate' + id);
     if (on == "1") {
        modinap.firstChild.data = 'Relevant';
        modinapon = true;
     } else {
        modinap.firstChild.data = 'Not Relevant';
        modinapon = false;
     }
  }

  var modmsg = document.getElementById( 'answermodmsg' + id );
  modmsg.style.display = '';
}

function modPoll( id, mod, deleteme ) {
  var ajaxurl = '/ajaxserver/modpoll.php5?id=' + id + '&mod=' + mod;
  if (deleteme)
     ajaxurl += "&delete=1";
  // now prevent IE caching
   var d = new Date();
   var t = d.getTime();
   ajaxurl += '&TIME=' + t;
  loadXMLDoc(ajaxurl);
}

function modPollDone( input, results, success ) {
  var id = results[0].getElementsByTagName('pollid')[0].firstChild.data;
  id = parseInt( id, 10 );
  var mod = results[0].getElementsByTagName('moderation')[0].firstChild.data;
  var on = results[0].getElementsByTagName('on')[0].firstChild.data;

  var pollmod = document.getElementById( 'pollmodadult' + id );
  if (on == "1") {
     pollmod.firstChild.data = "Not Adult";
     modadulton = true;
  } else {
     pollmod.firstChild.data = "Adult";
     modadulton = false;
  }

  var modmsg = document.getElementById( 'pollmodmsg' + id );
  modmsg.style.display = '';
}


function addToSessionAynom(key, value) {
  var ajaxurl = '/ajaxserver/addtosession.php5?key=' + key + '&value=' + value;
  // now prevent IE caching
   var d = new Date();
   var t = d.getTime();
   ajaxurl += '&TIME=' + t;
   loadAynomXMLDoc(ajaxurl);
}

function addToSession(key, value) {
  var ajaxurl = '/ajaxserver/addtosession.php5?key=' + key + '&value=' + value;
  // now prevent IE caching
   var d = new Date();
   var t = d.getTime();
   ajaxurl += '&TIME=' + t;
   loadXMLDoc(ajaxurl);
}

function genericAjaxSuccess( input, results, success ) {
  // call the overide function if it is defined
  if (self.genericOveride) 
     genericOveride();
}

function checkForCommentText(formElementId) {
	var formElementName = '#'+formElementId;
	if ($(formElementName).find('textarea').val().length <= 0) {
		if ($(formElementName).children(':first').attr('id') != 'error') {
			$(formElementName).prepend('<div id="error">You cannot propose a blank comment.</div>');
		} else {
			$(formElementName).children(':first').show();
		}
		$(formElementName).children(':first').delay(2000).fadeOut();
		return false;
	} else {
		return true;
	}
}

//-------------------Positioning -------------------------//

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//------------------End Positioning ----------------------//

		/*********************************************************************
		 * No onMouseOut event if the mouse pointer hovers a child element 
		 * *** Please do not remove this header. ***
		 * This code is working on my IE7, IE6, FireFox, Opera and Safari
		 * 
		 * Usage: 
		 * <div onMouseOut="fixOnMouseOut(this, event, 'JavaScript Code');"> 
		 *		So many childs 
		 *	</div>
		 *
		 * @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com		
		**/
		function is_child_of(parent, child) {
			if( child != null ) {			
				while( child.parentNode ) {
					if( (child = child.parentNode) == parent ) {
						return true;
					}
				}
			}
			return false;
		}
		function fixOnMouseOut(element, event, JavaScript_code) {
			var current_mouse_target = null;
			if( event.toElement ) {				
				current_mouse_target 			 = event.toElement;
			} else if( event.relatedTarget ) {				
				current_mouse_target 			 = event.relatedTarget;
			}
			if( !is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
				eval(JavaScript_code);
			}
		}


/*********************************************************************/
/* Javascript for Grupthink-Facebook Integration */

//$Id: grupthink.js 4850 2011-08-30 22:02:07Z ssundheim $

function fbLogin() {
	
	var facebookContainer = document.getElementById('facebookconnectcontainer');
	var facebookSignInContainer = document.getElementById('facebookconnectcontainersignin');
	var facebookHeaderContainer = document.getElementById('facebookconnectcontainerheader');
	
	if (facebookContainer != null) {
		document.getElementById('facebookconnectbutton').style.display = 'none';
		document.getElementById('facebookconnectchecking').style.display = '';
	}
	
	if (facebookHeaderContainer != null) {
		document.getElementById('facebookconnectbuttonheader').style.display = 'none';
		document.getElementById('facebookconnectcheckingheader').style.display = '';
	}	
	
	if (facebookSignInContainer != null) {
		document.getElementById('facebookconnectbuttonsignin').style.display = 'none';
		document.getElementById('facebookconnectcheckingsignin').style.display = '';
	}	
	
	var postURI = '/ajaxserver/handlefacebooklogin.php5';
	var postString = '';
	loadXMLDocPost(postURI, postString);
	
}

function redirectToMystuff() {
	window.location = '/';
}

function redirectToLinkSuccess() {
	window.location = '/facebook/facebook_link_success.php5';
}

function redirectToProfileLink() {
	window.location = '/facebook/facebook_link_success.php5?new';
}

function redirectToConfirmRegistration() {
	window.location = '/confirm_registration.php5';
}

function redirectToLocation(input, results, success) {
	var redirectLocation = results[0].getElementsByTagName('location')[0].firstChild.data;
	window.location = redirectLocation;
}

function closeFacebookConnectWindow() {
	toggleme('fullimagebox');
	
	document.getElementById('facebookconnectbutton').style.display = '';
	document.getElementById('facebookconnectchecking').style.display = 'none';


	var facebookSignInContainer = document.getElementById('facebookconnectcontainersignin');

	if (facebookSignInContainer != null) {
		document.getElementById('facebookconnectbuttonsignin').style.display = '';
		document.getElementById('facebookconnectcheckingsignin').style.display = 'none';
	}
}

function toggleFacebookSigninBox(input, results, success) {
	// First, if we aren't on the signing page, take them there. 
	// Eg, if we don't have the correct elements on the page, then we need to take 'em to the signin page where they can finish
	alert("Running toggleFacebookSigninBox")
	
	if (document.getElementById('linkaccountserror') == null) {
		window.location = '/signin.php5?finishfacebooklogin';
		return
	}

	var facebookName = results[0].getElementsByTagName('facebookname')[0].firstChild.data;

	//Functions that grab screen dimensions
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	//ID's for affected html elements	
	fullboxID = 'fullimagebox';

	fullbox = document.getElementById(fullboxID);
	fullbox.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 500) / 2) + 'px');
	fullbox.style.left = (((arrayPageSize[0] - 600) / 2) + 'px');

	// Bug in IE6 where dropdown boxes show through
	var dropDowns = document.getElementsByTagName('select');
	for (var ii = 0; ii < dropDowns.length; ii++) {
		if (dropDowns[ii].style.display == 'none') {
			dropDowns[ii].style.display = '';
		} else {
			dropDowns[ii].style.display = 'none';
		}
	}
	
	var facebookNameArea = document.getElementById('facebooknamearea');
	if (facebookNameArea != null && facebookName != null && facebookName != '') {
		if (facebookNameArea.hasChildNodes()) {
			while (facebookNameArea.childNodes.length >= 1) {
				facebookNameArea.removeChild(facebookNameArea.firstChild);
			}
		}
		facebookNameArea.appendChild(document.createTextNode(facebookName));
	}

	toggleme(fullboxID);
}

function checkLogin() {
	// Grab our inputs
	var userName = document.getElementById('loginusername').value;
	var password = document.getElementById('loginpassword').value;

	// Make sure they aren't null
	if (userName == null || userName == '') {
		alert("You must provide a non-empty username.");
	} else if (password == null || password == '') {
		alert("You must provide a non-empty pasword.");
	} else {
		// Let's give it a shot. First we'll clear the button
		document.getElementById('linkaccountsbutton').style.display = 'none';

		// Also, we'll clear out any errors that may be there
		document.getElementById('linkaccountserror').style.display = 'none';

		// Now we'll show them a loading image to let 'em know we're doing something
		document.getElementById('linkaccountloading').style.display = '';
		var postURI = '/ajaxserver/checklogin.php5';
		var postString = 'username='+userName+'&password='+password;
		
		loadXMLDocPost(postURI, postString);
	}
}

function facebookLinkFail() {
	// A fatal error occurred while trying to sign in
	var linkAccountsError = document.getElementById('linkaccountserror');
	
	if (linkAccountsError.hasChildNodes()) {
		while (linkAccountsError.childNodes.length >= 1) {
			linkAccountsError.removeChild(linkAccountsError.firstChild);
		}
	}

	linkAccountsError.appendChild(document.createTextNode("There was an error that occurred while trying to check your username and password. Please contact the administrative team."));
	linkAccountsError.appendChild(document.createElement('br'));
	linkAccountsError.appendChild(document.createElement('br'));
	linkAccountsError.style.display = '';
}

function facebookCreateFail() {
	// A fatal error occurred while trying to sign in
	var newAccountsError = document.getElementById('newaccountserror');
	
	if (newAccountsError.hasChildNodes()) {
		while (newAccountsError.childNodes.length >= 1) {
			newAccountsError.removeChild(newAccountsError.firstChild);
		}
	}

	newAccountsError.appendChild(document.createTextNode("There was an error that occurred while trying to check the availability of your username and email address. Please contact the administrative team."));
	newAccountsError.appendChild(document.createElement('br'));
	newAccountsError.appendChild(document.createElement('br'));
	newAccountsError.style.display = '';
}

function facebookLinkAuthFail() {
	// A fatal error occurred while trying to sign in
	var linkAccountsError = document.getElementById('linkaccountserror');
	
	if (linkAccountsError.hasChildNodes()) {
		while (linkAccountsError.childNodes.length >= 1) {
			linkAccountsError.removeChild(linkAccountsError.firstChild);
		}
	}

	linkAccountsError.appendChild(document.createTextNode("Sorry that username or password was incorrect. Please try again or click \"forgot password\". You can retry this process at any time by clicking the Facebook login button."));
	linkAccountsError.appendChild(document.createElement('br'));
	linkAccountsError.appendChild(document.createElement('br'));
	linkAccountsError.style.display = '';
	
	// Give them their button back
	document.getElementById('linkaccountloading').style.display = 'none';
	document.getElementById('linkaccountsbutton').style.display = '';
}

function facebookCreateDeny(input, results, success) {
	// A fatal error occurred while trying to sign in
	var newAccountsError = document.getElementById('newaccountserror');
	var message = results[0].getElementsByTagName('denyreason')[0].firstChild.data; 
	
	if (newAccountsError.hasChildNodes()) {
		while (newAccountsError.childNodes.length >= 1) {
			newAccountsError.removeChild(newAccountsError.firstChild);
		}
	}

	newAccountsError.appendChild(document.createTextNode(message));
	newAccountsError.appendChild(document.createElement('br'));
	newAccountsError.appendChild(document.createElement('br'));
	newAccountsError.style.display = '';
	
	// Give them their button back
	document.getElementById('newaccountloading').style.display = 'none';
	document.getElementById('newaccountsbutton').style.display = '';
}

function checkAccountAvailibility() {
	// Grab our variables
	var emailAddress = document.getElementById('newemail').value;

	// Confirm they aren't empty and verify the email address is legit and that the passwords match
	if (emailAddress == null || emailAddress == '') {
		alert("You must provide a non-empty email address.");
	} else if (emailAddress.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/) == false) {
		alert("You must provide a valid email address.");
	} else {
		// Let's give it a shot. First we'll clear the button
		document.getElementById('newaccountsbutton').style.display = 'none';

		// Remove any errors that may be there
		document.getElementById('newaccountserror').style.display = 'none';

		// Show them the loading image to let 'em know we're checking
		document.getElementById('newaccountloading').style.display = '';

		var postURI = '/ajaxserver/checkregistration.php5';
		var postString = 'email='+emailAddress;
		
		loadXMLDocPost(postURI, postString);
	}
}

/* END GRupthink-FAcebook Scripts */
/*********************************************************************/


/*********************************************************************/
		
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 * 
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function(b){var m,t,u,f,D,j,E,n,z,A,q=0,e={},o=[],p=0,d={},l=[],G=null,v=new Image,J=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,W=/[^\.]\.(swf)\s*$/i,K,L=1,y=0,s="",r,i,h=false,B=b.extend(b("<div/>")[0],{prop:0}),M=b.browser.msie&&b.browser.version<7&&!window.XMLHttpRequest,N=function(){t.hide();v.onerror=v.onload=null;G&&G.abort();m.empty()},O=function(){if(false===e.onError(o,q,e)){t.hide();h=false}else{e.titleShow=false;e.width="auto";e.height="auto";m.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');
F()}},I=function(){var a=o[q],c,g,k,C,P,w;N();e=b.extend({},b.fn.fancybox.defaults,typeof b(a).data("fancybox")=="undefined"?e:b(a).data("fancybox"));w=e.onStart(o,q,e);if(w===false)h=false;else{if(typeof w=="object")e=b.extend(e,w);k=e.title||(a.nodeName?b(a).attr("title"):a.title)||"";if(a.nodeName&&!e.orig)e.orig=b(a).children("img:first").length?b(a).children("img:first"):b(a);if(k===""&&e.orig&&e.titleFromAlt)k=e.orig.attr("alt");c=e.href||(a.nodeName?b(a).attr("href"):a.href)||null;if(/^(?:javascript)/i.test(c)||
c=="#")c=null;if(e.type){g=e.type;if(!c)c=e.content}else if(e.content)g="html";else if(c)g=c.match(J)?"image":c.match(W)?"swf":b(a).hasClass("iframe")?"iframe":c.indexOf("#")===0?"inline":"ajax";if(g){if(g=="inline"){a=c.substr(c.indexOf("#"));g=b(a).length>0?"inline":"ajax"}e.type=g;e.href=c;e.title=k;if(e.autoDimensions)if(e.type=="html"||e.type=="inline"||e.type=="ajax"){e.width="auto";e.height="auto"}else e.autoDimensions=false;if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=
false;e.enableEscapeButton=false;e.showCloseButton=false}e.padding=parseInt(e.padding,10);e.margin=parseInt(e.margin,10);m.css("padding",e.padding+e.margin);b(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){b(this).replaceWith(j.children())});switch(g){case "html":m.html(e.content);F();break;case "inline":if(b(a).parent().is("#fancybox-content")===true){h=false;break}b('<div class="fancybox-inline-tmp" />').hide().insertBefore(b(a)).bind("fancybox-cleanup",function(){b(this).replaceWith(j.children())}).bind("fancybox-cancel",
function(){b(this).replaceWith(m.children())});b(a).appendTo(m);F();break;case "image":h=false;b.fancybox.showActivity();v=new Image;v.onerror=function(){O()};v.onload=function(){h=true;v.onerror=v.onload=null;e.width=v.width;e.height=v.height;b("<img />").attr({id:"fancybox-img",src:v.src,alt:e.title}).appendTo(m);Q()};v.src=c;break;case "swf":e.scrolling="no";C='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+c+
'"></param>';P="";b.each(e.swf,function(x,H){C+='<param name="'+x+'" value="'+H+'"></param>';P+=" "+x+'="'+H+'"'});C+='<embed src="'+c+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+P+"></embed></object>";m.html(C);F();break;case "ajax":h=false;b.fancybox.showActivity();e.ajax.win=e.ajax.success;G=b.ajax(b.extend({},e.ajax,{url:c,data:e.ajax.data||{},error:function(x){x.status>0&&O()},success:function(x,H,R){if((typeof R=="object"?R:G).status==200){if(typeof e.ajax.win==
"function"){w=e.ajax.win(c,x,H,R);if(w===false){t.hide();return}else if(typeof w=="string"||typeof w=="object")x=w}m.html(x);F()}}}));break;case "iframe":Q()}}else O()}},F=function(){var a=e.width,c=e.height;a=a.toString().indexOf("%")>-1?parseInt((b(window).width()-e.margin*2)*parseFloat(a)/100,10)+"px":a=="auto"?"auto":a+"px";c=c.toString().indexOf("%")>-1?parseInt((b(window).height()-e.margin*2)*parseFloat(c)/100,10)+"px":c=="auto"?"auto":c+"px";m.wrapInner('<div style="width:'+a+";height:"+c+
";overflow: "+(e.scrolling=="auto"?"auto":e.scrolling=="yes"?"scroll":"hidden")+';position:relative;"></div>');e.width=m.width();e.height=m.height();Q()},Q=function(){var a,c;t.hide();if(f.is(":visible")&&false===d.onCleanup(l,p,d)){b.event.trigger("fancybox-cancel");h=false}else{h=true;b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");f.is(":visible")&&d.titlePosition!=="outside"&&f.css("height",f.height());l=o;p=q;d=e;if(d.overlayShow){u.css({"background-color":d.overlayColor,
opacity:d.overlayOpacity,cursor:d.hideOnOverlayClick?"pointer":"auto",height:b(document).height()});if(!u.is(":visible")){M&&b("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});u.show()}}else u.hide();i=X();s=d.title||"";y=0;n.empty().removeAttr("style").removeClass();if(d.titleShow!==false){if(b.isFunction(d.titleFormat))a=d.titleFormat(s,l,p,d);else a=s&&s.length?
d.titlePosition=="float"?'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+s+'</td><td id="fancybox-title-float-right"></td></tr></table>':'<div id="fancybox-title-'+d.titlePosition+'">'+s+"</div>":false;s=a;if(!(!s||s==="")){n.addClass("fancybox-title-"+d.titlePosition).html(s).appendTo("body").show();switch(d.titlePosition){case "inside":n.css({width:i.width-d.padding*2,marginLeft:d.padding,marginRight:d.padding});
y=n.outerHeight(true);n.appendTo(D);i.height+=y;break;case "over":n.css({marginLeft:d.padding,width:i.width-d.padding*2,bottom:d.padding}).appendTo(D);break;case "float":n.css("left",parseInt((n.width()-i.width-40)/2,10)*-1).appendTo(f);break;default:n.css({width:i.width-d.padding*2,paddingLeft:d.padding,paddingRight:d.padding}).appendTo(f)}}}n.hide();if(f.is(":visible")){b(E.add(z).add(A)).hide();a=f.position();r={top:a.top,left:a.left,width:f.width(),height:f.height()};c=r.width==i.width&&r.height==
i.height;j.fadeTo(d.changeFade,0.3,function(){var g=function(){j.html(m.contents()).fadeTo(d.changeFade,1,S)};b.event.trigger("fancybox-change");j.empty().removeAttr("filter").css({"border-width":d.padding,width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2});if(c)g();else{B.prop=0;b(B).animate({prop:1},{duration:d.changeSpeed,easing:d.easingChange,step:T,complete:g})}})}else{f.removeAttr("style");j.css("border-width",d.padding);if(d.transitionIn=="elastic"){r=V();j.html(m.contents());
f.show();if(d.opacity)i.opacity=0;B.prop=0;b(B).animate({prop:1},{duration:d.speedIn,easing:d.easingIn,step:T,complete:S})}else{d.titlePosition=="inside"&&y>0&&n.show();j.css({width:i.width-d.padding*2,height:e.autoDimensions?"auto":i.height-y-d.padding*2}).html(m.contents());f.css(i).fadeIn(d.transitionIn=="none"?0:d.speedIn,S)}}}},Y=function(){if(d.enableEscapeButton||d.enableKeyboardNav)b(document).bind("keydown.fb",function(a){if(a.keyCode==27&&d.enableEscapeButton){a.preventDefault();b.fancybox.close()}else if((a.keyCode==
37||a.keyCode==39)&&d.enableKeyboardNav&&a.target.tagName!=="INPUT"&&a.target.tagName!=="TEXTAREA"&&a.target.tagName!=="SELECT"){a.preventDefault();b.fancybox[a.keyCode==37?"prev":"next"]()}});if(d.showNavArrows){if(d.cyclic&&l.length>1||p!==0)z.show();if(d.cyclic&&l.length>1||p!=l.length-1)A.show()}else{z.hide();A.hide()}},S=function(){if(!b.support.opacity){j.get(0).style.removeAttribute("filter");f.get(0).style.removeAttribute("filter")}e.autoDimensions&&j.css("height","auto");f.css("height","auto");
s&&s.length&&n.show();d.showCloseButton&&E.show();Y();d.hideOnContentClick&&j.bind("click",b.fancybox.close);d.hideOnOverlayClick&&u.bind("click",b.fancybox.close);b(window).bind("resize.fb",b.fancybox.resize);d.centerOnScroll&&b(window).bind("scroll.fb",b.fancybox.center);if(d.type=="iframe")b('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0" '+(b.browser.msie?'allowtransparency="true""':"")+' scrolling="'+e.scrolling+'" src="'+d.href+'"></iframe>').appendTo(j);
f.show();h=false;b.fancybox.center();d.onComplete(l,p,d);var a,c;if(l.length-1>p){a=l[p+1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}if(p>0){a=l[p-1].href;if(typeof a!=="undefined"&&a.match(J)){c=new Image;c.src=a}}},T=function(a){var c={width:parseInt(r.width+(i.width-r.width)*a,10),height:parseInt(r.height+(i.height-r.height)*a,10),top:parseInt(r.top+(i.top-r.top)*a,10),left:parseInt(r.left+(i.left-r.left)*a,10)};if(typeof i.opacity!=="undefined")c.opacity=a<0.5?0.5:a;f.css(c);
j.css({width:c.width-d.padding*2,height:c.height-y*a-d.padding*2})},U=function(){return[b(window).width()-d.margin*2,b(window).height()-d.margin*2,b(document).scrollLeft()+d.margin,b(document).scrollTop()+d.margin]},X=function(){var a=U(),c={},g=d.autoScale,k=d.padding*2;c.width=d.width.toString().indexOf("%")>-1?parseInt(a[0]*parseFloat(d.width)/100,10):d.width+k;c.height=d.height.toString().indexOf("%")>-1?parseInt(a[1]*parseFloat(d.height)/100,10):d.height+k;if(g&&(c.width>a[0]||c.height>a[1]))if(e.type==
"image"||e.type=="swf"){g=d.width/d.height;if(c.width>a[0]){c.width=a[0];c.height=parseInt((c.width-k)/g+k,10)}if(c.height>a[1]){c.height=a[1];c.width=parseInt((c.height-k)*g+k,10)}}else{c.width=Math.min(c.width,a[0]);c.height=Math.min(c.height,a[1])}c.top=parseInt(Math.max(a[3]-20,a[3]+(a[1]-c.height-40)*0.5),10);c.left=parseInt(Math.max(a[2]-20,a[2]+(a[0]-c.width-40)*0.5),10);return c},V=function(){var a=e.orig?b(e.orig):false,c={};if(a&&a.length){c=a.offset();c.top+=parseInt(a.css("paddingTop"),
10)||0;c.left+=parseInt(a.css("paddingLeft"),10)||0;c.top+=parseInt(a.css("border-top-width"),10)||0;c.left+=parseInt(a.css("border-left-width"),10)||0;c.width=a.width();c.height=a.height();c={width:c.width+d.padding*2,height:c.height+d.padding*2,top:c.top-d.padding-20,left:c.left-d.padding-20}}else{a=U();c={width:d.padding*2,height:d.padding*2,top:parseInt(a[3]+a[1]*0.5,10),left:parseInt(a[2]+a[0]*0.5,10)}}return c},Z=function(){if(t.is(":visible")){b("div",t).css("top",L*-40+"px");L=(L+1)%12}else clearInterval(K)};
b.fn.fancybox=function(a){if(!b(this).length)return this;b(this).data("fancybox",b.extend({},a,b.metadata?b(this).metadata():{})).unbind("click.fb").bind("click.fb",function(c){c.preventDefault();if(!h){h=true;b(this).blur();o=[];q=0;c=b(this).attr("rel")||"";if(!c||c==""||c==="nofollow")o.push(this);else{o=b("a[rel="+c+"], area[rel="+c+"]");q=o.index(this)}I()}});return this};b.fancybox=function(a,c){var g;if(!h){h=true;g=typeof c!=="undefined"?c:{};o=[];q=parseInt(g.index,10)||0;if(b.isArray(a)){for(var k=
0,C=a.length;k<C;k++)if(typeof a[k]=="object")b(a[k]).data("fancybox",b.extend({},g,a[k]));else a[k]=b({}).data("fancybox",b.extend({content:a[k]},g));o=jQuery.merge(o,a)}else{if(typeof a=="object")b(a).data("fancybox",b.extend({},g,a));else a=b({}).data("fancybox",b.extend({content:a},g));o.push(a)}if(q>o.length||q<0)q=0;I()}};b.fancybox.showActivity=function(){clearInterval(K);t.show();K=setInterval(Z,66)};b.fancybox.hideActivity=function(){t.hide()};b.fancybox.next=function(){return b.fancybox.pos(p+
1)};b.fancybox.prev=function(){return b.fancybox.pos(p-1)};b.fancybox.pos=function(a){if(!h){a=parseInt(a);o=l;if(a>-1&&a<l.length){q=a;I()}else if(d.cyclic&&l.length>1){q=a>=l.length?0:l.length-1;I()}}};b.fancybox.cancel=function(){if(!h){h=true;b.event.trigger("fancybox-cancel");N();e.onCancel(o,q,e);h=false}};b.fancybox.close=function(){function a(){u.fadeOut("fast");n.empty().hide();f.hide();b.event.trigger("fancybox-cleanup");j.empty();d.onClosed(l,p,d);l=e=[];p=q=0;d=e={};h=false}if(!(h||f.is(":hidden"))){h=
true;if(d&&false===d.onCleanup(l,p,d))h=false;else{N();b(E.add(z).add(A)).hide();b(j.add(u)).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");j.find("iframe").attr("src",M&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank");d.titlePosition!=="inside"&&n.empty();f.stop();if(d.transitionOut=="elastic"){r=V();var c=f.position();i={top:c.top,left:c.left,width:f.width(),height:f.height()};if(d.opacity)i.opacity=1;n.empty().hide();B.prop=1;
b(B).animate({prop:0},{duration:d.speedOut,easing:d.easingOut,step:T,complete:a})}else f.fadeOut(d.transitionOut=="none"?0:d.speedOut,a)}}};b.fancybox.resize=function(){u.is(":visible")&&u.css("height",b(document).height());b.fancybox.center(true)};b.fancybox.center=function(a){var c,g;if(!h){g=a===true?1:0;c=U();!g&&(f.width()>c[0]||f.height()>c[1])||f.stop().animate({top:parseInt(Math.max(c[3]-20,c[3]+(c[1]-j.height()-40)*0.5-d.padding)),left:parseInt(Math.max(c[2]-20,c[2]+(c[0]-j.width()-40)*0.5-
d.padding))},typeof a=="number"?a:200)}};b.fancybox.init=function(){if(!b("#fancybox-wrap").length){b("body").append(m=b('<div id="fancybox-tmp"></div>'),t=b('<div id="fancybox-loading"><div></div></div>'),u=b('<div id="fancybox-overlay"></div>'),f=b('<div id="fancybox-wrap"></div>'));D=b('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(f);
D.append(j=b('<div id="fancybox-content"></div>'),E=b('<a id="fancybox-close"></a>'),n=b('<div id="fancybox-title"></div>'),z=b('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),A=b('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));E.click(b.fancybox.close);t.click(b.fancybox.cancel);z.click(function(a){a.preventDefault();b.fancybox.prev()});A.click(function(a){a.preventDefault();b.fancybox.next()});
b.fn.mousewheel&&f.bind("mousewheel.fb",function(a,c){if(h)a.preventDefault();else if(b(a.target).get(0).clientHeight==0||b(a.target).get(0).scrollHeight===b(a.target).get(0).clientHeight){a.preventDefault();b.fancybox[c>0?"prev":"next"]()}});b.support.opacity||f.addClass("fancybox-ie");if(M){t.addClass("fancybox-ie6");f.addClass("fancybox-ie6");b('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(D)}}};
b.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#000",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",
easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};b(document).ready(function(){b.fancybox.init()})})(jQuery);

/* END FANCY BOX */
