// Adapted from DOM Ready extension by Dan Webb
// http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
// which was based on work by Matthias Miller, Dean Edwards and John Resig
//
// Usage:
//
// Event.onReady(callbackFunction);
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (Event._timer)  clearInterval(Event._timer);

    Event._readyCallbacks.each(function(f) { f() });
    Event._readyCallbacks = null;

  },
  onReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady;

      if (domReady.done) return f();

      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);

        /*@cc_on @*/
        /*@if (@_win32)
            var dummy = location.protocol == "https:" ?  "https://javascript:void(0)" : "javascript:void(0)";
            document.write("<script id=__ie_onload defer src='" + dummy + "'><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") { domReady(); }
            };
        /*@end @*/

        if (/WebKit/i.test(navigator.userAgent)) {
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady();
          }, 10);
        }

        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});

function showTopNavbar( options )
{
	var params = new Array();
	params.push( 'op=topnavbarcontent' );
	if( options.activity ) params.push( 'activity=true' );
	if( options.inpage_bookmarklet ) params.push( 'load_inpage_bookmarklet=true' );
	ganjaAjaxUpdater( 'navigation', '/index.php?'+ params.join( '&' ) ,'', 'Loading...' );
}

var ActivityAgent = Class.create();
ActivityAgent.prototype = {
	posts: $A(),
	acts: {},
	options:{},
	initialize: function(logs){
		this.acts = logs;
		this.posts = this.getPostDivs();
	},
	getPostDivs: function() {
		var posts_local = $A();
		$$('div.post[id], div.post-quicklinks[id]').each(function(el){
			posts_local.push({timestamp: el.id.split('_')[2], id: el.id, activity: 0, acts: [], before: true});
		});
		if(posts_local.length > 0) posts_local.push({timestamp: (posts_local[posts_local.length-1].timestamp - 7200), id: posts_local[posts_local.length-1].id, activity: 0, acts: [], before: false});
		return posts_local;
	},
	sortToSlots: function() {
		var j = 0;
		for(var i = 0; i < this.posts.length; i++){
			while(j < this.acts.length) {
				if(this.acts[j].val.issued > this.posts[i].timestamp) {
					this.posts[i].acts.push(this.acts[j]);
				} else break;
				j++;
			}
		}
	},
	summarizeActions: function(dudes, targets, context) {
		var name = context.val.commenterUserName;
		var post_pl = context.val.postPermalink == undefined ? '' : context.val.postPermalink;
		var target_user = context.val.userUserName == undefined ? '' : context.val.userUserName;
		if(dudes[name] == undefined) dudes[name] = {follow:new $H(), leave: new $H(), comment: new $H(), clip: new $H(), messages: new $H(), newposts: new $H(), displayName: context.val.commenterDisplayName};
		switch(context.type){
			case 'COMMENT' :
				if(targets[post_pl] == undefined) targets[post_pl] = {commented:new $H(), clipped:new $H(), type: 'post', title: context.val.postTitle,titleStripped: context.val.postTitleStripped};
				if(dudes[name].comment[post_pl] == undefined ) dudes[name].comment[post_pl] = 0;
				if(targets[post_pl].commented[name] == undefined ) targets[post_pl].commented[name]	= 0;
				dudes[name].comment[post_pl]++;
				targets[post_pl].commented[name]++;
				break;
			case 'POST' :
				if(context.val.action == 'TAGGED') {
					if(targets[post_pl] == undefined) targets[post_pl] = {commented:new $H(), clipped:new $H(), type: 'post', title: context.val.postTitle,titleStripped: context.val.postTitleStripped};

					if(dudes[name].clip[post_pl] == undefined ) dudes[name].clip[post_pl] = 0;
					if(targets[post_pl].clipped[name] == undefined) targets[post_pl].clipped[name] = 0;
					dudes[name].clip[post_pl]++;
					targets[post_pl].clipped[name]++;
				}
				break;
			case 'USER' :
				if(targets[target_user] == undefined) targets[target_user] = {followed:new $H(), leaved:new $H(), type: 'user', username: context.val.userDisplayName};
				if(context.val.action == 'TAGGED') {
					if(targets[target_user].followed[name] == undefined) targets[target_user].followed[name] = 0;
					if(dudes[name].follow[target_user] == undefined) dudes[name].follow[target_user] = 0;
					targets[target_user].followed[name]++;
					dudes[name].follow[target_user]++;
				} else {
					if(targets[target_user].leaved[name] == undefined) targets[target_user].leaved[name] = 0;
					if(dudes[name].leave[target_user] == undefined) dudes[name].leave[target_user] = 0;
					targets[target_user].leaved[name]++;
					dudes[name].leave[target_user]++;
				}
				break;
			case 'MESSAGE' :
				dudes[name].messages[context.val.postId] = context;
				break;
			case 'NEWPOST' :
				dudes[name].newposts[context.val.postId] = context;
				break;
		}
	},
	dropActivities: function() {	
			var dudes = new $H();
			var targets = new $H();
			for(var i=0; i < this.acts.length; i++){
				this.summarizeActions(dudes, targets, this.acts[i]);
			}
			this.writeDOM(dudes, targets, this.posts[1].id);
		
	},
	getHideBehaviour: function(show_what, hide_what) {
		return function(){
			$(show_what).show();
			$(hide_what).hide();
			return false;
		};
	},
	writeDOM: function(dudes, targets, element_id) {
		var dude_keys = dudes.keys();
		var target_keys = targets.keys();
		var html_array = [];
		var onclick_array = {};
		var groupsize = 3;

		groupsize--; //indexes start from 0, so it's easier this way

		for(var i = 0; i < target_keys.length; i++) {
			var insertHTML = '';
			if(targets[target_keys[i]].type == 'post' && targets[target_keys[i]].commented.size() > 0) {
				insertHTML = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
				insertHTML+=	'<a href="' + target_keys[i] +'" title="Click here to read '+ targets[target_keys[i]].titleStripped +'" alt="Click here to read '+ targets[target_keys[i]].titleStripped +'">'+ targets[target_keys[i]].title +'</a> drew comment from ';
				var keys = targets[target_keys[i]].commented.keys();
				for(var j=0; j < keys.length; j++) {
					insertHTML+= '<a href="/commenter/'+keys[j]+'" class="topTag" title="Click here to go to '+dudes[keys[j]].displayName+'\'s profile" alt="Click here to go to '+dudes[keys[j]].displayName+'\'s profile">'+dudes[keys[j]].displayName+'</a>';
					if(j < keys.length-1) {
						insertHTML+= (j == keys.length-2) ? ' and ' : ', ';
					} else {
						insertHTML+= '.';
					}
				}
				insertHTML+='</p></div>';
				html_array.push(insertHTML);
			}
		}
		for(var i = 0; i < dude_keys.length; i++) {
			var dude_link = '<a href="/commenter/'+dude_keys[i]+'" class="topTag" title="Click here to go to'+dudes[dude_keys[i]].displayName+'\'s profile" alt="Click here to go to'+dudes[dude_keys[i]].displayName+'\'s profile">'+dudes[dude_keys[i]].displayName+'</a>';
			var insertHTML = '';
		/*	if(dudes[dude_keys[i]].comment.size() > 0) {
				insertHTML = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
				insertHTML+=dude_link + ' commented on ';
				var keys = dudes[dude_keys[i]].comment.keys();
				for(var j=0; j < keys.length; j++) {
					if(j == 2) insertHTML+= '<span id="'+ element_id + dude_keys[i] + '_comments" style="display:none;">';
					insertHTML+= '<a href="'+keys[j]+'">'+targets[keys[j]].title+'</a>';
					if(j < keys.length-1) {
						if(j != 1) {
							insertHTML+= (j == keys.length-2) ? ' and ' : ', ';
						}
					} else {
						insertHTML+='.';
					}
				}
				if(j > 2) {
					//insertHTML+= '</span><a id="'+ element_id + dude_keys[i] + '_comments_link" href="#"> ...and '+(j-2)+' other';
					insertHTML+= '</span> ...and '+(j-2)+' other';
					insertHTML+= ((j-2) > 1 ? 's' : '');
					//onclick_array[element_id + dude_keys[i] + '_comments_link'] = this.getHideBehaviour(element_id + dude_keys[i] + '_comments', element_id + dude_keys[i] + '_comments_link');
				}
				insertHTML+='</p></div>';
			}
	*/
			if(dudes[dude_keys[i]].clip.size() > 0) {
				insertHTML = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
				insertHTML+=dude_link + ' clipped ';
				var keys = dudes[dude_keys[i]].clip.keys();
				for(var j=0; j < keys.length; j++) {
					if(j == groupsize) insertHTML+= '<span id="'+element_id + dude_keys[i] + '_clips" style="display:none;">';
					insertHTML += '<a href="'+keys[j]+'">'+targets[keys[j]].title+'</a>';
					if(j < keys.length-1) {
						if(j != (groupsize-1)) {
							insertHTML+= (j == keys.length-2) ? ' and ' : ', ';
						}
					} else {
						insertHTML+='.';
					}
				}
				if(j > groupsize) {
					//insertHTML+= '</span><a id="'+element_id + dude_keys[i] + '_clips_link" href="#"> ...and '+(j-2)+' other';
					insertHTML+= '</span> ...and '+(j-groupsize)+' other';
					insertHTML+= ((j-groupsize) > 1 ? 's' : '');
					//onclick_array[element_id + dude_keys[i] + '_clips_link'] = this.getHideBehaviour(element_id + dude_keys[i] + '_clips', element_id + dude_keys[i] + '_clips_link');
				}
				insertHTML +='</p></div>';
			}
			if(dudes[dude_keys[i]].follow.size() > 0) {
				insertHTML = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
				insertHTML+=dude_link + ' is following ';
				var keys = dudes[dude_keys[i]].follow.keys();
				for(var j=0; j < keys.length; j++) {
					if(j == groupsize) insertHTML+= '<span id="'+element_id + dude_keys[i] + '_follows" style="display:none;">';
					insertHTML += '<a href="/commenter/'+keys[j]+'">'+targets[keys[j]].username+'</a>';
					if(j < keys.length-1) {
						if(j != (groupsize-1)) {
							insertHTML+= (j == keys.length-2) ? ' and ' : ', ';
						}
					} else {
						insertHTML+='.';
					}
				}
				if(j > groupsize) {
					//insertHTML+= '</span><a id="'+element_id + dude_keys[i] + '_follows_link" href="#"> ...and '+(j-4)+' other';
					insertHTML+= '</span> ...and '+(j-groupsize)+' other';
					insertHTML+= ((j-groupsize) > 1 ? 's' : '');
					//onclick_array[element_id + dude_keys[i] + '_follows_link'] = this.getHideBehaviour(element_id + dude_keys[i] + '_follows', element_id + dude_keys[i] + '_follows_link');
				}
				insertHTML +='</p></div>';
			}
			if(dudes[dude_keys[i]].leave.size() > 0) {
				insertHTML = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
				insertHTML+=dude_link + ' removed ';
				var keys = dudes[dude_keys[i]].leave.keys();
				for(var j=0; j < keys.length; j++) {
					if(j == groupsize) insertHTML+= '<span id="'+element_id + dude_keys[i] + '_leaves" style="display:none;">';
					insertHTML += '<a href="/commenter/'+keys[j]+'">'+targets[keys[j]].username+'</a>';
					if(j < keys.length-1) {
						if(j != (groupsize-1)) {
							insertHTML+= (j == keys.length-2) ? ' and ' : ', ';
						}
					} else {
						insertHTML+='.';
					}
				}
				if(j > groupsize) {
					//insertHTML+= '</span><a id="'+element_id + dude_keys[i] + '_leaves_link" href="#"> ...and '+(j-4)+' other';
					insertHTML+= '</span> ...and '+(j-groupsize)+' other';
					insertHTML+= ((j-groupsize) > 1 ? 's' : '');
					//onclick_array[element_id + dude_keys[i] + '_leaves_link'] = this.getHideBehaviour(element_id + dude_keys[i] + '_leaves', element_id + dude_keys[i] + '_leaves_link');
				}
				insertHTML +='</p></div>';
			}
			if(dudes[dude_keys[i]].messages.size() > 0) {
				var messages_src = '';
				var keys = dudes[dude_keys[i]].messages.keys();
				for(var j=0; j < keys.length; j++) {
					messages_src = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
					messages_src+=dude_link + ' sent you a message: ';
					messages_src += dudes[dude_keys[i]].messages[keys[j]].val.text;
					messages_src +='</p></div>';
					insertHTML+=messages_src;
				}
			}
			if(dudes[dude_keys[i]].newposts.size() > 0) {
				var newposts_src = '';
				var keys = dudes[dude_keys[i]].newposts.keys();
				for(var j=0; j < keys.length; j++) {
					newposts_src = '<div class="post-activity"><p><img src="'+ulIconUrl+'" class="ulIcon" />';
					newposts_src +=dude_link + ' wrote: ';
					newposts_src += '<a href="'+dudes[dude_keys[i]].newposts[keys[j]].val.postPermalink +'">';
					newposts_src += dudes[dude_keys[i]].newposts[keys[j]].val.postTitle + '</a>';
					newposts_src +='</p></div>';
					insertHTML+=newposts_src;
				}
			}
			if(insertHTML.length > 0) html_array.push(insertHTML);
		}

		var src = '<div class="post-activity-frame"><div style="margin-bottom:10px"><a href="/friends/" class="topTag">what your friends are up to</a></div>';
		var visible_count = 3;
		for(var i=0; i < (html_array.length > 10 ? 10 : html_array.length); i++) {
			if(i == visible_count) src+= '<div id="activity_'+element_id+'" style="display:none;">';
			src+= html_array[i];
		}		
		if(i > visible_count) {
			if(html_array.length > 10) src+= '<div class="post-activity"><p><a href="/activity/'+userData.username+'">see all activity &raquo;</a></p></div>';
			src+= '</div><div class="post-activity"><p><a id=\'activity_'+element_id+'_show\' href="#">more &raquo;</a></p></div>';
		}
		if(html_array.length < 3) src+="<div class=\"post-activity\">Make friends: Next time you see a comment that's brilliantly illuminating and life-changing, click the \"Follow Commenter\" <a class=\"user_actions commentToolAdd\" style=\"display:inline;margin:4px\"><img src=\"/assets/base.v5a/img/x.gif\" width=\"16\" border=\"0\" /></a> icon next to it.</div>";
		if(src.length > 0) {
			src+= '</div>';
			src+= '<hr class="separator clear" />';
			new Insertion.Before(element_id, src);
			if(i > visible_count) $("activity_"+element_id+"_show").onclick = function(e){ var a = e.target.id.split('_'); $(a[0]+'_'+a[1]+'_'+a[2]+'_'+a[3]).show(); $(e.target.id).hide(); return false;};
		}
		/*for(var name in onclick_array) {
			if(onclick_array.hasOwnProperty(name)){
				$(name).onclick = onclick_array[name];
			}
		}
		*/
	}
};

dropFriendsActivity = function(friendsComments) {
	var agent = new ActivityAgent();
	agent.initialize(friendsComments);
	//agent.sortToSlots();
	agent.dropActivities();
}

function swapBackground(element, classname){
	var sb = document.getElementById(element);
	sb.className = classname;
}

function checkSearchForm(form){
	if($('term').value == ''){
		//alert('Please provide a search phrase.');
		ganjaShowMessage('error','Please provide a search phrase.');
		return false;
	}

	form.action = form.action+'/'+$('term').value;
	if( $('searchall').value == 1 ) {
		form.action = form.action + '/all';
	}
	//if(!$('searchbydate') || $('searchbydate').value == 1){
	if($('searchbydate').value == 1){
		form.action = form.action + '/bydate';
		return true;
	}
}

function OpenEmail (c) {
    window.open(c,
        'email',
        'width=500,height=315,scrollbars=yes,status=yes');
}

function pf( a, b ) {
	window.status = a +' '+ window.status;
}

function searchSubmit()
{
	sf = $('search');
	if(sf.q.value == '')
	{
		alert('Please provide a search phrase.');
		return false;
	}
	else
	{
		lochref = sf.prefix.value + encodeURI(sf.q.value.replace(/\s/g,'+')) + '/';
		if(sf.bydate.value == 1)
		{
			lochref = lochref + 'bydate/';
		}
		document.location = lochref;
		return false;
	}
}

function ajaxPost( link )
{
	var parameters = new Array();
	parameters.push( 'format=ajax' );

	parameters = parameters.join( '&' );
	ganjaAjaxUpdater( 'Posts', link, parameters, false );
}

function ganjaExtension( extName, argsArr )
{
	var containerId = Math.random();
	document.write('<div id="'+extName+'Div_'+ containerId +'"></div>');

	var params = new Array();
	params.push( extName+'Id=' + containerId );

	if(argsArr != undefined && argsArr != null) {
		for(var i=0;i<argsArr.length;i++)
		{
			params.push(argsArr[i]);
		}
	}

	ganjaAjaxUpdater(extName+'Div_'+containerId, '/extensions/'+extName+'/index.php', params.join( '&' ), false);
}

function galleryPost( tag, numImages, galleryTitle, layoutType )
{
	if( typeof onLiveblogSite != 'undefined' && onLiveblogSite == true ) return false;
	if(!layoutType) var layoutType = 'grid';

	document.write('<div class="GalleryPreview">');

	if(galleryTitle != null)
	{
		// document.write('<h3 class="galleryTitle"><a href="/photogallery/' + niceurlencode(tag) + '/">' + galleryTitle + '</h3></a>');

		var header  = '<h3 class="galleryTitle">';
		if( typeof permalink  != 'undefined' )
		{
			header += '<a href="' + permalink + '">'+ galleryTitle +'</a>';
		}
		else
		{
			header += galleryTitle;
		}
		header += '</h3>';
		document.write(header);
	}

	var containerId = Math.random();
	document.write('<div id="gallery' + containerId +'"></div>');

	var params = new Array();
	var pagetype = 'postlist';
	if( numImages < 1 || numImages > 150 || numImages == undefined || numImages == null )
	{
		// default to 6 images
		numImages = 6;
	}
	if( typeof pageType  != 'undefined' && pageType == 'post' )
	{
		pagetype = 'post';
		numImages = 50;
	}
	params.push( 'maxReturned=' + numImages);
	params.push( 'tagName=' + niceurlencode(tag) );
	params.push( 'format=ajax' );
	params.push( 'galleryLayoutType='+layoutType );
	params.push( 'pagetype='+ pagetype );
	if( typeof permalink  != 'undefined' )
	{
		params.push( 'permalink='+ niceurlencode(permalink) );
	}

	params = params.join('&');

	var req = new Ajax.Updater( 'gallery'+containerId, '/photogallery/', {
		method: 'get',
		parameters: params,
		evalScripts: false,
		asynchronous: true});

	document.write('<hr class="clearer"/></div>');
}

function niceurlencode( str )
{
    from = [ '_', ' ', '\'', '-', '+','.',  ':', '/'  ];
    to   = [ '=', '-', '.',  '_', ' ','\'', '|', '\\' ];

    retval = '';
    len = str.length;

    for( i = 0; i < len; i++ )
    {
        found = false;
        for( key in from)
        {
        	chr = str.charAt(i);
            fromchar = from[key];
            if( fromchar == chr )
            {
                chr = chr.replace( fromchar, to[key] );
                retval = retval + chr;
                found = true;
                break;
            }
        }
        if(!found)
        {
            retval = retval + str.charAt(i);
        }
    }

	retval = escape(retval);

    /* this one is not by the standards */
    retval.replace( '\%20', '+' );

    return retval;
}


function liveBlog( url )
{
	if( !url ) return false;
	var lbId = Math.floor( ( Math.random() * 100 ) );
	document.write('<div id="lb'+ lbId +'">helo</div>');
	ganjaAjaxUpdater('lb'+ lbId , url );
}


/*
 *  The following functions enable hover action on image links
 */

function GM_preloadImages()
{
  var d=document; if(d.images){ if(!d.GM_p) d.GM_p=new Array();
    var i,j=d.GM_p.length,a=GM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.GM_p[j]=new Image; d.GM_p[j++].src=a[i];}}
}

function GM_swapImgRestore()
{
  var i,x,a=document.GM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function GM_findObj( n, d )
{
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=GM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function GM_swapImage()
{
  var i,j=0,x,a=GM_swapImage.arguments; document.GM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=GM_findObj(a[i]))!=null){document.GM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function report( section )
{
	var longi = 0;

	if(ganjaReports == undefined)
	{
		console.log('No reports available.');
	}
	else if(section == undefined)
	{
		console.group('Available reports:');
		console.log('all');
		for( var s in ganjaReports )
		{
			console.log(s);
		}
	}
	else if (section == 'all')
	{
		for( var s in ganjaReports )
		{
			report(s);
		}
	}
	else
	{
		if(ganjaReports[section] != undefined)
		{
			console.group('Report: ' + section);

			data = ganjaReports[section];
			for( i=0; i<data.length; i++)
			{
				longi = 0;
				for( j=0; j<data[i].length; j++)
				{
					if(data[i][j].indexOf('\n') != -1)
					{
						longi = 1;
					}
				}

				if(longi == 1)
				{
					console.group(data[i][0]);
					tmp = data[i][0];
					data[i][0] = '';
					console.log(data[i].join('\t'));
					data[i][0] = tmp;
					console.groupEnd();
				}
				else
				{
					console.log( data[i].join('\t'));
				}
			}
		}
	}

	console.groupEnd();
}

function toggleAdminTool(){
	if(document.getElementById('shade').style.display=='none'){
		at.show();
	}else{
		at.hide();
	}
}

function changeReportRow(rowId){
	if(document.getElementById(rowId).style.display=='none'){
		new Effect.BlindDown(rowId, {duration:0.1});
	}else{
		new Effect.BlindUp(rowId, {duration:0.1});
	}
}

var AdminTool = Class.create();
AdminTool.prototype = {
	initialized: 0,
	shade: undefined,
	win: undefined,
	report: undefined,
	initialize: function()
	{
		var shade = document.createElement('div');
		var report = document.createElement('div');

		document.body.appendChild(shade);
		document.body.appendChild(report);

		shade.style.display = 'none';
		report.style.display = 'none';

		var w = document.width;
		shade.id = 'shade';
		report.style.position = 'fixed';
		report.style.zIndex = '200';
		report.style.top = '30px';
		report.style.width = '98%';
		report.style.padding = '10px';
		report.style.background = '#F1F1F1';
		report.style.font = 'normal 12px Arial, Verdana';

		this.initialized = 1;
		this.shade = shade;
		this.report = report;
	},

	show: function()
	{
		if(!this.initialized)
		{
			this.initialize();
		}
		var dcState = Cookie.get("GanjaDebug");
		if(dcState==null) dcState="off";
		this.shade.innerHTML="<div style=\"position:absolute;top:5px;right:15px;width:50px;height:5px;\" nowrap=\"yes\"><a href=\"javascript:void(0)\" onclick=\"at.hide()\" style=\"border-bottom:0px;\">close&nbsp;[x]<a></div>";
		this.shade.innerHTML+="<div style=\"position:absolute;left:670px;width:200px;padding:0px;color:#FFFFFF;display:none;\" id=\"ganjaDelResp\"></div>";
		this.shade.innerHTML+="<ul><li><a href=\"javascript:void(0)\" onclick=\"javascript:toggleDebugCookie('"+dcState+"')\" title=\"toggle debugcookie\">debug is "+dcState+"</a></li></ul>";
		if(dcState=="on"){
			this.shade.innerHTML+="<ul><strong>reports</strong><li><a href=\"javascript:void(0)\" onclick=\"javascript:at.changeReport('config')\">config</a></li><li><a href=\"javascript:void(0)\" onclick=\"javascript:at.changeReport('cache')\">cache</a></li><li><a href=\"javascript:void(0)\" onclick=\"javascript:at.changeReport('tmpl')\">tmpl</a></li></ul>\n";
		}
		if(postRefId!='-1') this.shade.innerHTML+="<ul><strong>stats</strong><li><a href=\"/admin/stat/\" target=\"_blank\">site</a></li><li><a href=\"/admin/stat/?postUrl="+postRefId+"\" target=\"_blank\">post</a></li></ul>";
		else this.shade.innerHTML+="<ul><strong>stats</strong><li><a href=\"/admin/stat/\">site</a></li></ul>";

		if(postRefId!='-1') this.shade.innerHTML+="<ul><strong>refresh</strong><li><a href=\"javascript:void(0);\" onclick=\"flushPostFromCache("+siteId+",'','"+canonicalHost+"'); return false;\">main</a><li><a href=\"javascript:void(0);\" onclick=\"flushPostFromCache("+siteId+","+postRefId+",'"+canonicalHost+"'); return false;\">post</a></li></ul>";
		else this.shade.innerHTML+="<ul><strong>refresh</strong><li><a href=\"javascript:void(0);\" onclick=\"flushPostFromCache("+siteId+",'','"+canonicalHost+"'); return false;\">front</a></li></ul>";
		if(this.shade.style.display=='none') Effect.BlindDown( this.shade,{ duration: 0.1});
	},

	changeReport: function(what)
	{
		if(typeof ganjaReports!='undefined'){
			var data = ganjaReports[what];
			var reportContent = "<h3>"+what+"</h3>";
			reportContent+="<table cellpadding=1 cellspacing=1 id=\"reportTable\"><tbody>";
				for( i=0; i<data.length; i++)
				{
					if(Math.round(i - (Math.floor(i/2)*2))=='0') reportContent+="<tr>";
					else reportContent+="<tr class=\"coloured\">";

					var cellData=new String(data[i]);
					longi = 0;
					for( j=0; j<data[i].length; j++)
					{
						if(data[i][j].indexOf('\n') != -1)
						{
							longi = 1;
						}
					}

					if(longi == 1)
					{
						cellData = cellData.split(",");
						reportContent+="<td><a href=\"javascript:void(0)\" onclick=\"javascript:changeReportRow('configRow_"+i+"');\">"+cellData[0]+"</a><br /><div id=\"configRow_"+i+"\" style=\"display:none;float:left;\"><pre style=\"font-size:10px;\">"+cellData[2]+"</pre></div></td>";
					}
					else
					{
						cellData = cellData.replace(/, /g, "<br />");
						cellData = cellData.replace(/,/g, "</td><td>");
						reportContent+="<td>"+cellData+"</td>";
					}

					reportContent+="</tr>";
				}
			reportContent+="</tbody></table>";
			this.report.style.display = 'block';
			this.report.innerHTML = reportContent;
		}
	},

	hide: function()
	{
		this.report.style.display = 'none';
		Effect.BlindUp( this.shade,{ duration: 0.1});
	},

	displayNone: function( effect )
	{
		effect.element.style.display = 'none';
	}
}

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

function ganjaClip( postId, onoff, callerAnchor, messageId )
{
	var parameters = new Array();
	parameters.push('op=saveusertag');
	parameters.push('objectType=POST');
	parameters.push('objectId=' + postId);
	parameters.push('messageId=' + messageId);
	if(onoff == true)
	{
		parameters.push('tagName=favorite');
	}
	else
	{
		parameters.push('unTagName=favorite')
	}

	parameters = parameters.join( '&' );
	ganjaAjaxUpdater( callerAnchor, '/index.php', parameters );
	return false;
}

function ganjaBuddy( userId, onoff, callerAnchor, anchorId, messageId )
{
	var parameters = new Array();
	parameters.push('op=saveusertag');
	parameters.push('objectType=USER');
	parameters.push('objectId=' + userId);
	parameters.push('anchorId=' + anchorId);
	parameters.push('messageId=' + messageId);
	if(onoff == true)
	{
		parameters.push('tagName=buddy');
	}
	else
	{
		parameters.push('unTagName=buddy')
	}

	parameters = parameters.join( '&' );
	ganjaAjaxUpdater( callerAnchor, '/index.php', parameters );
	return false;
}

function toggleBuddyStatus(buddyId, anchorId, messageId)
{
	if( !$('buddy_'+ anchorId) )
	{
		// reload page
		location.href = location.href;
		return false;
	}

	var buddy = $('buddy_'+ anchorId);
	if( buddy.hasClassName('user-friend-follow') )
	{
		// change to 'remove commenter'
		buddy.removeClassName('user-friend-follow');
		buddy.addClassName('user-friend-remove');
		buddy.addClassName('commentToolRemove');
		buddy.removeClassName('commentToolAdd');
		buddy.alt = "Remove this commenter from your friends";
		buddy.title = "Remove this commenter from your friends";
		buddy.setAttribute('onclick', "return ganjaBuddy( "+ buddyId +", false, 'ganjaBuddyDiv', "+ anchorId +", '"+ messageId +"' );");
	}
	else
	{
		// change to 'follow commenter'
		buddy.addClassName('user-friend-follow');
		buddy.removeClassName('user-friend-remove');
		buddy.addClassName('commentToolAdd');
		buddy.removeClassName('commentToolRemove');
		buddy.alt = "Follow this commenter's contributions";
		buddy.title = "Follow this commenter's contributions";
		buddy.setAttribute('onclick', "return ganjaBuddy( "+ buddyId +", true, 'ganjaBuddyDiv', "+ anchorId +", '"+ messageId +"' );");
	}
}

/* post state change functions */
function changePostStatus( postId, state, realm, linkobj, needsConfirm)
{
	var skip = false;
	if(needsConfirm)
	{
		if( !confirm('Delete post?') )
		{
			skip = true;
		}
	}
	if( !skip )
	{
		var params = new Array;
		params.push( 'op=changepoststatus' );
		params.push( 'id='+ postId );
		params.push( 'publishStatus='+ state );
		params.push( 'realm='+ realm );

		new Ajax.Updater('postStatusResponse', "/index.php", {
			parameters : params.join('&'),
			evalScripts: true
		});
	}
}

function changeTagpagecommentStatus(postId, state)
{
	var params = new Array;
	params.push( 'op=changetagcommentstatus' );
	params.push( 'id='+ postId );
	params.push( 'publishStatus='+ state );

	new Ajax.Updater('postStatusResponse', "/index.php", {
		parameters : params.join('&'),
		evalScripts: true
	});
}

/* remove site tag from post */
function removeSiteTag( postId, postIssued, listFingerprint )
{
	var params = new Array;
	params.push( 'op=removesitetag' );
	params.push( 'postId='+ postId );
	params.push( 'postIssued='+ postIssued );
	params.push( 'listFingerprint='+ listFingerprint );

	new Ajax.Updater('postStatusResponse', "/index.php", {
		parameters : params.join('&'),
		evalScripts: true
	});
}

function removePostFromPage(postId)
{
	$('id_'+postId).style.display = 'none';
	if( $('hr_'+postId) ) $('hr_'+postId).style.display = 'none';
	if( $('post_separator_'+postId) ) $('post_separator_'+postId).style.display = 'none';
}

function toggleTagRemoveButton(postId, post_issued)
{
	if( $('tagToggleLinkRemove'+postId).hasClassName('deleteButton') )
	{
		$('tagToggleLinkRemove'+postId).removeClassName('deleteButton');
		$('tagToggleLinkRemove'+postId).addClassName('addButton');
		$('tagToggleLinkRemove'+postId).title = 'Add this crosspromoted post to this site';
		$('tagToggleLinkRemove'+postId).alt = 'Add this crosspromoted post to this site';
	}
	else
	{
		$('tagToggleLinkRemove'+postId).removeClassName('addButton');
		$('tagToggleLinkRemove'+postId).addClassName('deleteButton');
		$('tagToggleLinkRemove'+postId).title = 'Remove this crosspromoted post from this site';
		$('tagToggleLinkRemove'+postId).alt = 'Remove this crosspromoted post from this site';
	}
}

function togglePostStatusButton(postId, state, realm)
{
	if ($('statusToggleLinkPromote'+postId)!=undefined) var linkdiv = $('statusToggleLinkPromote'+postId);
	else if($('statusToggleLinkDemote'+postId)!=undefined) var linkdiv = $('statusToggleLinkDemote'+postId);

	switch(state)
	{
		case 'PUBLISHED':
			linkdiv.href = "javascript:changePostStatus(" +postId + ",'REVIEWED', '" + realm + "', this)";
			linkdiv.className = 'deleteButton';
			ganjaShowMessage('info', 'Status changed to:<br />'+state, 'poststatusMessage_'+postId);
		break;

		default:
			linkdiv.href = "javascript:changePostStatus(" +postId + ",'PUBLISHED', '" + realm + "', this)";
			linkdiv.className = 'addButton';
			ganjaShowMessage('info', 'Status changed to:<br />'+state, 'poststatusMessage_'+postId);
		break;
	}
}

function jumpToComment( postId, commentDivClass, commentId )
{
	if(commentId == undefined)
	{
		commentId = document.location.hash;
	}
	else
	{
		pos = commentId.lastIndexOf('#');
		if(pos > 0)
		{
			commentId = commentId.substr(pos);
		}
	}

	var cId = parseInt(commentId.substr(2));

	if((commentId != '') && (cId > 0))
	{
		comments = document.getElementsByClassName(commentDivClass);
		found = false;
		for(var comment in comments)
		{
			commentDiv = comments[comment];
			if( commentId == ( '#' + commentDiv.id ) )
			{
				found = true;
			}
		}

		if(found == false)
		{
			var parameters = new Array();
			parameters.push( 'op=comments' );
			parameters.push( 'postId=' + postId );
			parameters.push( 'cId=' + cId);
			parameters = parameters.join( '&' );
			ganjaAjaxUpdater( 'CommentListWrapper', '/index.php', parameters );
			return false;
		}
		else
		{
			document.location.hash = '#c' + cId;
			return false;
		}
	}
	return true;
}

function latestHeadlines( siteId, num )
{
	document.write('<div class="LatestHeadlines">');

	var containerId = Math.random();
	document.write('<div id="latestHeadlines' + containerId +'"></div>');

	var params = new Array();
	params.push( 'maxReturned=' + num );
	params.push( 'parentId=' + siteId );
	params.push( 'format=ajaxheadlines' );

	params = params.join('&');

	var req = new Ajax.Updater( 'latestHeadlines'+containerId, '/', {
		method: 'get',
		parameters: params,
		evalScripts: false,
		asynchronous: true});

	document.write('<hr class="clearer"/></div>');

}

/* css editor functions */
function cssEditorWindow()
{
	win = new Window({className: "alphacube", title: "CSS Editor", width:400, destroyOnClose: true, recenterAuto:false});
	win.setAjaxContent('?op=csseditor', '');
	win.showCenter();
}

function setClassStyle( className, styleElement, value )
{
	var newStyle = new Array();
	newStyle[styleElement] = value;

	var classDivs = $$('.'+className);
	for( var i = 0; i < classDivs.length; i++ )
	{
		Element.setStyle( classDivs[i], newStyle );
	}
}

function setIdStyle( divId, styleElement, value )
{
	var newStyle = new Array();
	newStyle[styleElement] = value;

	var classDiv = $(divId);
	if( classDiv ) classDiv.setStyle( newStyle );
}

function setTagStyle( tagName, styleElement, value )
{
	var newStyle = new Array();
	newStyle[styleElement] = value;

	var classTags = document.getElementsByTagName(tagName);
	for( var i = 0; i < classTags.length; i++ )
	{
		Element.setStyle( classTags[i], newStyle );
	}
}

function changeCssValue(elem)
{
	var fullPath = elem.name;
	var cssPath = fullPath.substring( 0, fullPath.indexOf(':') );
	var cssElement = fullPath.substring( fullPath.indexOf(':')+1 );

	if( cssPath.substring(0, 1) == '.' )
	{
		// it's a classname
		cssPath = cssPath.substring(1);
		setClassStyle( cssPath, cssElement, elem.value );
	}
	else if( cssPath.substring(0, 1) == '#' )
	{
		// it's an id
		cssPath = cssPath.substring(1);
		setIdStyle( cssPath, cssElement, elem.value );
	}
	else
	{
		// tagname, maybe?
		setTagStyle( cssPath, cssElement, elem.value );
	}
}

function makeQuickLinksEditable(){
	var quicklinks = document.getElementsByClassName('quicklink');

	if(quicklinks.length>0)
	{
		for(i=0;i<quicklinks.length;i++)
		{
			quicklinks[i].className = $(quicklinks[i]).className+' editor';
			quicklinks[i].onclick = function()
			{
				if ( et.currentedited != null )
				{
					et.ganjaCancelQuicklink( et.currentedited.split('_')[1], et.currentedited.split('_')[2] );
					et.currentedited = null;
				}
				var postId = this.id.split("_")[1];
				var parameters = 'op=quicklink_edit&postId='+postId;
				var editorId = this.id.replace("id_","edit_");
				ganjaAjaxUpdater( editorId, '/index.php', parameters );
				this.style.display = 'none';
				$(editorId).style.display = 'block';
				et.currentedited = this.id;
			}
			quicklinks[i].getElementsByClassName('topTag')[0].onclick = disableLink.bindAsEventListener();
		}
	}
}

function disableLink(){
	return false;
}

function loadStyleSheet (sheetURL, mediaTypes) {
	var link;
	var doc = document;
	if (doc.createElement && (link = doc.createElement('link')))
	{
		link.rel = 'stylesheet';
		link.href = sheetURL;
		link.type = 'text/css';
		if (mediaTypes) {
			link.media = mediaTypes;
		}
		var head = doc.getElementsByTagName('head')[0];
		if (head) {
			head.appendChild(link);
		}
	}
}

function loadJavascript (url) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	document.getElementsByTagName('head')[0].appendChild(script);
}

function google_ad_request_done(google_ads) {
  var i;
  // Display the feedback link if available
  if (google_info.feedback_url) {
      document.write("<p><b><a href='" + google_info.feedback_url + "'>Feedback</a></b></p>");
  }
  // Display each ad in turn
  for(i = 0; i < google_ads.length; ++i) {
    document.write('<p>');
    document.write('<a href=' + google_ads[i].url +'class="headlink" target="_blank"><strong>' + google_ads[i].line1 + '</strong></a>' + '<br/><a class="asl2" href=' + google_ads[i].url +'>' + google_ads[i].line2 + google_ads[i].line3 + '<br/><span style="color:#666;">' + google_ads[i].visible_url) + '</span></a>';
    document.write('</p>');
  }
}

var mouseOverHandler = function(e) {
	if((Event) && Event.element){
		if(Event.element(e).hasClassName('super-permalink')||Event.element(e).up().hasClassName('super-permalink')) {
			var postdiv = Event.element(e).up();
			while(! (postdiv.hasClassName('post') || postdiv.hasClassName('post-quicklinks')) ) { postdiv = postdiv.up(); }
			postdiv.addClassName('highlited');
		}
	}
};

var mouseOutHandler = function(e) {
	if((Event) && Event.element){
		if(Event.element(e).hasClassName('super-permalink')||Event.element(e).up().hasClassName('super-permalink')) {
			var postdiv = Event.element(e).up();
			while(! (postdiv.hasClassName('post') || postdiv.hasClassName('post-quicklinks')) ) { postdiv = postdiv.up(); }
			postdiv.removeClassName('highlited');
		}
	}
};

var activateDynamicContent = function ()
{
	var id;
	var method;
	var params;
	
	for(i=0;i<ganjaDynamicContent.length;i++)
	{
		id = ganjaDynamicContent[i].id;
		method = ganjaDynamicContent[i].method;
		params = ganjaDynamicContent[i].params;		
		dcMethod[method](id, params);
	}
};

var dcMethod = {
	'dfpad': function ( id, params ) {
		var iframe = $(id + '_iframe');
		var script = $(id + '_script');
		if(iframe != undefined)
		{
			iframe.src = 'http://ad.doubleclick.net/adi/' + params['site'] + '/' + params['zone'] + ';ptile=' + params['ptile'] + ';sz=' + params['width'] + 'x' + params['height'] + ';' + params['key'] + 'ord=' + params['random'] + '?';
		}
		if(script != undefined)
		{
			script.src = 'http://ad.doubleclick.net/adj/' + params['site'] + '/' + params['zone'] + ';ptile=' + params['ptile'] + ';sz=' + params['width'] + 'x' + params['height'] + ';' + params['key'] + 'ord=' + params['random'] + '?';
		}
	}
};

