// these might not work the same way as regular element methods because they are defined
// after some prototype extension magic...
Object.extend(Element, {
  // topix (sawka): move an element to an absolute position...
  moveTo: function(elem, x, y) {
    Element.setStyle($(elem), { position: 'absolute', left: x + 'px', top: y + 'px' });
  },

  // topix (sawka)
  moveTo4: function(elem, top, right, bottom, left) {
    Element.setStyle($(elem), { position: 'absolute' });
    if (top != null) { Element.setStyle($(elem), { top: top + 'px' }); }
    if (right != null) { Element.setStyle($(elem), { right: right + 'px' }); }
    if (bottom != null) { Element.setStyle($(elem), { bottom: bottom + 'px' }); }
    if (left != null) { Element.setStyle($(elem), { left: left + 'px' }); }
  },

  // topix (sawka)
  moveToWithFit: function(elem, x, y) {
    var dims = Element.getDimensions(elem);
    Element.moveTo(elem, Position.fitXInViewport(x, dims.width), Position.fitYInViewport(y, dims.height));  
  }
});

Object.extend(Position, {
  // topix (sawka) - no longer necessary in the new prototype (but for backward compat)
  absoluteOffset: function(element) {
    var dims = Position.page(element);
    dims[0] += Client.scrollLeft();
    dims[1] += Client.scrollTop();
    return dims;
  },

  // topix (sawka)
  fitXInViewport: function(x, width) {
    var viewportwidth = Client.viewportWidth();
    var scrollleft = Client.scrollLeft();
    if (x + width - scrollleft > viewportwidth - 20)
        x = scrollleft + viewportwidth - width - 20;
    if (x < scrollleft)
        x = scrollleft;
    return x;
  },

  // topix (sawka)
  fitYInViewport: function(y, height) {
    var viewportheight = Client.viewportHeight();
    var scrolltop = Client.scrollTop();
    if (y + height - scrolltop > viewportheight - 20)
        y = scrolltop + viewportheight - height - 20;
    if (y < scrolltop)
        y = scrolltop;
    return y;
  }
});

// topix (sawka): added some code to get the viewport width / height
//     from: http://www.andrewdupont.net/categories/web/development/javascript/
// which was adapted from the functions posted on QuirksMode
//     http://www.quirksmode.org/viewport/compatibility.html
var Client = {
  viewportWidth: function() {
    return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
  },

  viewportHeight: function() {
    return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
  },
  
  viewportSize: function() {
    return { width: this.viewportWidth(), height: this.viewportHeight() };
  },

  // topix (sawka): added these 3 functions as direct adaptations of quicksmode.org code
  scrollTop: function() {
    return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  },

  scrollLeft: function() {
    return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
  },

  scrollOffsets: function() {
    return { left: this.scrollLeft(), top: this.scrollTop() };
  }
};


// topix (sawka): add a wrapper class to do ajax requests with HTML form objects
Ajax.FormRequest = Class.create();
Ajax.FormRequest.prototype = Object.extend(Ajax.Request, {
    initialize: function(form, options) {
        form = $(form);
        options.parameters = Form.serialize(form);
        options.method = form.method;
        return new Ajax.Request(form.action, options);
    }
});


var topix_respondToReadyState = function(readyState) {
    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);

    if (state == 'Complete') {
      // topix (sawka): add pre-handlers (use responseJSON)
      try {
        Ajax.Responders.dispatch('onPre' + (this.success() ? 'Success' : 'Failure'), this, response, response.responseJSON);
      } catch(e) {
        this.dispatchException(e);
      }
        
      try {
        this._complete = true;
        // topix (sawka): use reponseJSON
        (this.options['on' + response.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(response, response.responseJSON);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && this.isSameOrigin() && contentType
          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
        this.evalResponse();
    }

    try {
      // topix (sawka): use reponseJSON  
      (this.options['on' + state] || Prototype.emptyFunction)(response, response.responseJSON);
      Ajax.Responders.dispatch('on' + state, this, response, response.responseJSON);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  };

Ajax.Request.prototype.respondToReadyState = topix_respondToReadyState;
Ajax.Updater.prototype.respondToReadyState = topix_respondToReadyState;


/* Topix JS functions 
/*--------------------------------------------------------------------------*/


var g_ajaxresp = new Object();
var page_node;   // declared in chrome
var topix_google_skip = 0;
var t_v;         // declared in chrome

function ajax_onCreate(ajaxobj, ajaxtransport)
{
    g_ajaxresp = new Object();
    g_ajaxresp.url = ajaxobj.url;
    g_ajaxresp.parameters = {};
    if (ajaxobj.options.method == 'post')
    {
        g_ajaxresp.url += " (post)";
        g_ajaxresp.parameters = ajaxobj.options.parameters;
    }

    if (g_ajaxdebug)
    {
        var out = "DEBUG AJAX\n" + ajaxobj.url;
        if (ajaxobj.options.method == 'post')
        {
            out += " (post)\n";
            if (ajaxobj.options.parameters)
            {
                out += ajaxobj.options.parameters.toQueryString();
            }
        }
        alert(out);
    }
}

function ajax_onPreSuccess(ajaxobj, x)
{
    try
    {
        g_ajaxresp.tt = x.getResponseHeader("X-Topix-TT");
        g_ajaxresp.action = x.getResponseHeader("X-Topix-Action");
    }
    catch(e) { }
}

function ajax_successWrapper(origfn)
{
    return function(x, json) {
        // older responseText way to throw errors
        var resp = x.responseText;
        if (resp.indexOf("error:") == 0)
        {
            alert(resp.replace("error: ", ""));
            return;
        }

        // new structured way to throw errors from the server
        if (json && json.error) 
        {
            alert(json.error);
            return;
        }

        return origfn(x, json);
    };
}

var topix_responder = { onCreate: ajax_onCreate, onPreSuccess: ajax_onPreSuccess };
Ajax.Responders.register(topix_responder);

function ajax_request(url, params)
{
    if (params.onSuccess)
    {
        params.onSuccess = ajax_successWrapper(params.onSuccess);
    }
    new Ajax.Request(url, params);
}

function ajax_form_request(form, params)
{
    if (params.onSuccess)
    {
        params.onSuccess = ajax_successWrapper(params.onSuccess);
    }
    new Ajax.FormRequest(form, params);
}

function add_favorite(cat)
{
    ajax_request("/member/profile-edit-cats", {
        parameters: { ajax: 1, add: 1, cat: cat },
        onSuccess: function(x) {
            window.location = "";
        }
    });
}

function showForumTrackerNav(elem)
{
    var div = $("forumTrackerDiv");
    if (!Element.visible(div))
    {
        ajax_request("/forum/tracker/ajax", {
            onSuccess: function(x) {
                var link = elem || $("forumTrackerLink");
                Element.update(div, x.responseText);
                var pos = Position.absoluteOffset(link);
                Element.moveToWithFit(div, pos[0] + 20, pos[1] + 20);
                Element.show(div);
                if ($('dartframe_iframe'))
                    Element.setStyle('dartframe_iframe', { visibility: "hidden" });
            }
        });
    }
    else
    {
        closeForumTracker();
    }
    return false;
}

function showForumTracker(elem)
{
    var div = $("forumTrackerDiv");
    if (!Element.visible(div))
    {
        ajax_request("/forum/tracker/ajax", {
            onSuccess: function(x) {
                var link = elem || $("forumTrackerLink");
                Element.update(div, x.responseText);
                var pos = Position.absoluteOffset(link);
                Element.moveToWithFit(div, pos[0] - 120, pos[1] + 20);
                Element.show(div);
                if ($('dartframe_iframe'))
                    Element.setStyle('dartframe_iframe', { visibility: "hidden" });
            }
        });
    }
    else
    {
        closeForumTracker();
    }
    return false;
}   

function closeForumTracker()
{
    if ($('dartframe_iframe'))
        Element.setStyle('dartframe_iframe', { visibility: "visible" });
    Element.hide("forumTrackerDiv");
}

function excludeFTItem(threadid)
{
    ajax_request("/forum/tracker/exclude", {
        parameters: { threadid: threadid },
        onSuccess: function(x) {
            Element.update("forumTrackerDiv", x.responseText);
        }
    });
    return false;
}


function getAndPopulate (url, divId, nonsync)
{
    ajax_request(url, {
        onSuccess: function(x) {
            Element.update(divId, x.responseText);
        }
	, method : "get"
    });
}


function sendForm(form, callback)
{
    ajax_form_request(form, { onSuccess: function(x) { callback(x); } });
}


function sendUrl(url, callback)
{
    ajax_request(url, { onSuccess: function(x) { callback(x); }, method: 'get' });
}

function addLinkTracker()
{
    if (!document.getElementsByTagName) return false;
    
    var elements = document.getElementsByTagName('a');
    for (var i = 0; i < elements.length; i++) 
    {
	// Only track a link with attribute t set
	if (! elements[i].getAttribute('t') )
	    continue; 
	addEvent(elements[i], 'mousedown', recordClick);
	// alert("added mousedown event on " + elements[i].getAttribute('href'));
    }
}


function addLinkTrackerToContainer( container )
{
    container = $(container);
    if (!container || !container.getElementsByTagName) return false;
    
    var elements = container.getElementsByTagName('a');
    for (var i = 0; i < elements.length; i++) 
    {
        // Only track a link with attribute t set
	    if (! elements[i].getAttribute('t') )
	       continue; 
	       addEvent(elements[i], 'mousedown', recordClick);
	    // alert("added mousedown event on " + elements[i].getAttribute('href'));
    }

}

function updateLinksToNewWindow(container)
{
    container = $(container);
    if (!container || !container.getElementsByTagName)
        return false;

    var elements = container.getElementsByTagName("a");
    for (var i = 0; i < elements.length; i++) 
    {
        elements[i].target = "_blank";
    }

    elements = container.getElementsByTagName("form");
    for (var i = 0; i < elements.length; i++) 
    {
        elements[i].target = "_blank";
    }

    return true;
}



function documentClickHandler( event )
{
    var elem = Event.element( event );

    if( elem.tagName == "A" && elem.getAttribute('t') )
    {
        recordClick( event );
    }
}


function addEvent(elm, evType, fn) 
{
    // alert("Adding listener " + fn + " to event " +  evType);
    // cross-browser event handling
    if (elm.addEventListener) { 
	elm.addEventListener(evType, fn, false); 
	return true; 
    } else if (elm.attachEvent) { 
	var r = elm.attachEvent('on' + evType, fn); 
	return r; 
    } else {
	elm['on' + evType] = fn;
    }
}

function recordClick(e)
{
    if (typeof e == 'undefined')
        e = window.event;

    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    } else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    } else {
        return true;
    }

    var lid;
    var elem = source;
    var durl;
    var htarget;
    while (elem && elem.tagName != "BODY")
    {
        if (elem.tagName == "A")
        {
            lid = elem.getAttribute("t");
            durl = elem.getAttribute("href");
            htarget = elem.getAttribute("target");
            break;
        }
        elem = elem.parentNode;
    }

    sendClickEvent(lid, durl, htarget);

    return false;
}

function sendClickEvent(lid, durl, htarget)
{
    durl = "" + durl;
    if (durl.length > 300)
        durl = durl.substr(0, 300);
    if (t_v == undefined)
        return false;
    var url;
    if (t_v.indexOf("/clk") == -1)
        url = "/clk?v=" + t_v;
    else
        url = t_v;
    url += "&lid=" + lid + "&ht=" + escape(htarget) + "&durl=" + escape(durl);
    ajax_request(url, { 
        onSuccess: function(x) { 
            // alert("Sent clk event " + url);
        } 
    });
   
    return true;
}

addEvent(window, 'load', addLinkTracker);

// addEvent( window, 'load', function() { Event.observe( document, 'mousedown', documentClickHandler ) });

function recordLoadTime()
{
    var load_time = ((new Date()).getTime() - start_time) / 1000;
    document.images["tr"].src =
	"/t6track/ld?" +
        "lt=" + load_time +
        "&v=" + encodeURIComponent(ld_v);

}

var activeHide;

function showHideThreadLink(td, elem)
{
    elem = $(elem);
    if (activeHide == elem) return;
    if (activeHide) Element.hide(activeHide);
    var pos = Position.absoluteOffset(td);
    var dims = Element.getDimensions(elem);
    Element.moveToWithFit(elem, pos[0] - dims.width - 2, pos[1]);
    Element.show(elem);
    activeHide = elem;
}


var flagpost_current;

function flagPost_closePopup()
{
    Element.hide('flagpostdiv');
    flagpost_current = null;
}

function flagPost_popup(elem, forum, threadid, postid)
{
    if ($('flagpostdiv') == null) return;
    var fpid = threadid + postid;
    if (fpid == flagpost_current)
    {
        flagPost_closePopup();
        return;
    }
   
    $('flagpostdiv_flaglink').onclick = function() { flagPost(forum, threadid, postid); return false; };
    var permalink = "http://www.topix.com/forum/" + forum + "/T" + threadid + "/post" + postid;
    $('flagpostdiv_paidlink').onclick = function() { open_feedback('', { 'node' : forum, 'type' : 'postpaid', 'permalink1': permalink }); return false; };

    Element.hide("flagpostdiv_flaglinkmsg");
    Element.show("flagpostdiv_flaglink");

    var pos = Position.absoluteOffset(elem);
    Element.moveTo('flagpostdiv', pos[0] - 140, pos[1] + 20);
    Element.show('flagpostdiv');
    flagpost_current = fpid;
}

function flagPost(forum, threadid, postid)
{
    ajax_request("/forum/flag", {
        parameters: { forum: forum, threadid: threadid, postid: postid }
    });
    Element.hide("flagpostdiv_flaglink");
    Element.show("flagpostdiv_flaglinkmsg");
    return false;
}

function showHistogram( url, div )
{
	ajax_request( url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );
}

function setHistogram( source )
{
	if ( source.getAttribute && source.getAttribute( "goto" ) )
		ajax_update_search( 'main', source.getAttribute( "goto" ) );

	var next = source;
	while ( next = next.nextSibling )
	{
		var tmpstr = next.className;
		if ( tmpstr && tmpstr.match( /histogramBar/ ) )
		{
			next.className = tmpstr.replace( /hist(enable|select)/, "histdisable" );
		}
	}

	var next = source;
	while ( next = next.previousSibling )
	{
		var tmpstr = next.className;
		if ( tmpstr && tmpstr.match( /histogramBar/ ) )
		{
			next.className = tmpstr.replace( /hist(disable|select)/, "histenable" );
		}
	}

	var tmpstr = source.className;
	if ( tmpstr && tmpstr.match( /histogramBar/ ) )
	{
		source.className = tmpstr.replace( /hist(disable|select|enable)/, 'histselect' );
	}
}

function ajax_update_search( main, url )
{
	Element.update( main, $( 'loading' ).innerHTML );
	Element.scrollTo( 'wrapper' );
	ajax_request( url, { onSuccess : function ( x ) { Element.update( main, x.responseText ) }, method : "get" } );
}

var calendar_curmonth = 0;
var calendar_monthlist = new Array();
var calendar_curdisplay;

function calendar_addMonth( month )
{
  calendar_monthlist.push( month );
}

function calendar_showMonth()
{
  if ( calendar_curdisplay )
    $( calendar_curdisplay ).style.display = 'none';

  calendar_curdisplay = $( calendar_monthlist[calendar_curmonth] );

  if ( calendar_curdisplay )
  { 
    $( calendar_curdisplay ).style.display = 'block';
  }
}

function calendar_lastMonth()
{
  calendar_curmonth = calendar_monthlist.length - 1;
  calendar_showMonth();
}

function calendar_nextMonth()
{
  if ( calendar_curmonth < calendar_monthlist.length - 1 )
  {
    calendar_curmonth++;
    calendar_showMonth();
  }
}
function calendar_prevMonth()
{
  if ( calendar_curmonth > 0 )
  {
    calendar_curmonth--;
    calendar_showMonth();
  }
}

function searchValidate (frm)
{
	if (frm.elements['q'] == '')
	{
	    return false;
	}

	var lid = frm.getAttribute("t");
	if (lid) {
	    sendClickEvent(lid, null, null);
	}

	return true;
}

function setBlogs (n, frm)
{			
    if (frm && frm.elements['blogs'])
    {
    	frm.elements['blogs'].value = n;		
    }
}

function showFavorites()
{
    var pos = Position.absoluteOffset($('favoritesdiv'));
    Element.moveToWithFit("favoritesblock", pos[0] - 30, pos[1] + 20);
    Element.toggle("favoritesblock");
    
}

function toggleClassSingle(element, classname)
{
    if (Element.hasClassName(element, classname))
    {
        Element.removeClassName(element, classname);
    }
    else
    {
        Element.addClassName(element, classname);
    }
}

function showAndHide(elemtoshow, elemstohide)
{
    elemtoshow = $(elemtoshow);
    Element.show(elemtoshow);
    if (elemstohide != null)
    {
        for (var i=0; i<elemstohide.length; i++)
        {
            var tohide = $(elemstohide[i]);
            if (tohide != null && tohide != elemtoshow)
            {
                Element.hide(tohide);
            }
        }
    }
}

function toggleClass (allElements, activeElement, active)
{
	allElements.each (function (elem) {Element.removeClassName (elem,active)});
	Element.addClassName (activeElement,active);
}

function gridme() {
	var grid = document.createElement("div");
	grid.setAttribute("style","width:100%; height:3000px; position:absolute;top:0px;background:transparent url(http://64.13.129.136/pics/grid_v2.png) top center repeat-y;opacity:0.5;");
	document.body.appendChild(grid);
}

function showExplore(explorelinkdiv)
{
    closeOtherHatBlocks("exploreblock");
    var pos = Position.absoluteOffset(explorelinkdiv);
    Element.moveToWithFit("exploreblock", pos[0] - 0, pos[1] + 26);
    Element.toggle("exploreblock");
}

function closeOtherHatBlocks(id)
{
    if (id != "editorblock" && $('editorblock')) Element.hide ('editorblock');
    if (id != "adminblock" && $('adminblock')) Element.hide ('adminblock');
    if (id != "timesblock" && $('timesblock')) Element.hide ('timesblock');
    if (id != "exploreblock" && $('exploreblock')) Element.hide ('exploreblock');
}


function google_ad_request_done(google_ads)
{
    if (google_ads.length == 0)
    {
        return;
    }
    var s = '';
    if (google_ads[0].type == "flash")
    {   
        s = '<a href="' + google_info.feedback_url + '" style="color:000000; font-size:11px">Ads by Google</a><br>' +
            '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
            ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="' +
            google_ad.image_width + '" HEIGHT="' +
            google_ad.image_height + '"> <PARAM NAME="movie" VALUE="' +
            google_ad.image_url + '">' +
            '<PARAM NAME="quality" VALUE="high">' +
            '<PARAM NAME="AllowScriptAccess" VALUE="never">' +
            '<EMBED src="' + google_ad.image_url +
            '" WIDTH="' + google_ad.image_width +
            '" HEIGHT="' + google_ad.image_height +
            '" TYPE="application/x-shockwave-flash"' +
            ' AllowScriptAccess="never" ' +
            ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';
        topix_google_skip = topix_topix_google_skip + 1;
    }
    else if (google_ads[0].type == "image")
    {
        s = '<div style="margin:auto; width:468px"><div style="text-align:left"><a href="' + google_info.feedback_url +
            '" style="color:#000000; font-size:11px">Ads by Google</a></div>' +
            '<a href="' + google_ads[0].url +
            '" target="_top" title="go to ' + google_ads[0].visible_url +
            '" onmouseout="window.status=\'\'; return true;" onmouseover="window.status=\'go to ' +
            google_ads[0].visible_url + '\';return true;"><img border="0" src="' + google_ads[0].image_url +
            '"width="' + google_ads[0].image_width +
            '"height="' + google_ads[0].image_height + '"></a></div>';
        topix_google_skip = topix_google_skip + 1;
    }
    else if (google_ads[0].type == "html")
    {
        s = google_ads[0].snippet;
        topix_google_skip = topix_google_skip + 1;
    }
    else if (google_ads.length > 1 && topix_custom_adtype == "forum")
    {
        // 200px ad + 2 * 3px margin = 206
        var adswidth = (206 * google_ads.length) + 2;
        s = '<div style="margin:auto; width:' + adswidth + 'px">';
        s += '<a href="' + google_info.feedback_url + '" style="margin:3px; color:#000000; font-size:11px">Ads by Google</a>';
        for (i = 0; i < google_ads.length; ++i)
        {
            s += '<div style="float:left; text-align:left; width:200px; margin: 3px"><a href="' + google_ads[i].url + '" ' + 
                'onmouseout="window.status=\'\'; return true;" ' +
                'onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\'; return true;" style="text-decoration:none; color:#164c97">' +
                '<span style="text-decoration:underline"><b>' + google_ads[i].line1 + '</b></span></a>' + 
                '<span style="color:#000000; font-size:11px"><br>' +
                google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br>' +
                '<a href="' + google_ads[i].url + '" ' + 
                'onmouseout="window.status=\'\'; return true;" ' +
                'onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\'; return true;" style="text-decoration:none; color:#164c97">' +
                '<span style="color:#' + topix_urlcolor + '; font-size:11px">' +
                google_ads[i].visible_url + '</span></a></div>';
        }
        s += '<div class="divclear"></div></div>';
        topix_google_skip = topix_google_skip + google_ads.length;
    }
    else
    {
        var i;
        s = '<a href="' + google_info.feedback_url + '" style="color:#000000; font-size:11px">Ads by Google</a>';
        for (i = 0; i < google_ads.length; ++i)
        {
            s += '<div style="padding-top:3px"><a href="' + google_ads[i].url + '" ' + 
                'onmouseout="window.status=\'\'; return true;" ' +
                'onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\'; return true;" style="text-decoration:none; color:#164c97">' +
                '<span style="text-decoration:underline"><b>' + google_ads[i].line1 + '</b></span></a>' + 
                '<span style="color:#000000; font-size:11px"> - ' +
                google_ads[i].line2 + ' ' + google_ads[i].line3 + '</span><br>' +
                '<a href="' + google_ads[i].url + '" ' + 
                'onmouseout="window.status=\'\'; return true;" ' +
                'onmouseover="window.status=\'go to ' +
                google_ads[i].visible_url + '\'; return true;" style="text-decoration:none; color:#164c97">' +
                '<span style="color:#' + topix_urlcolor + '; font-size:11px">' +
                google_ads[i].visible_url + '</span></a></div>';
        }
        topix_google_skip = topix_google_skip + google_ads.length;
    }
    document.write(s);
    return;
} 


function set_user_pref(userid, name, value, callback)
{
    var params = { targetuserid : userid };
    params[name] = value;

    ajax_request("/member/set-prefs",
    {
        parameters: params,
        onSuccess: function() { callback(value); }
    });
    return false;
}

function toggle_hidegeo(hidden)
{
    if (hidden)
    {
        Element.hide("profile_geoip_shown");
        Element.show("profile_geoip_hidden");
    }
    else
    {
        Element.hide("profile_geoip_hidden");
        Element.show("profile_geoip_shown");
    }
}


function toggle_recentposts(isprivate)
{
    if (isprivate)
    {
        Element.addClassName("user_recentposts", "rp_private");
    }
    else
    {
        Element.removeClassName("user_recentposts", "rp_private");
    }
}

function homepage_showMoreActive()
{
    ajax_request("/ajax/homepage-activity",
    {
        onSuccess: function(x) { Element.update("homepage_activeUsers", x.responseText) }
    });
}

function addthis_click(obj, addthis_url, addthis_title, addthis_pub)
{
    var aturl  = 'http://www.addthis.com/bookmark.php';
    aturl += '?v=1';
    aturl += '&pub='+addthis_pub;
    aturl += '&url='+encodeURIComponent(addthis_url);
    aturl += '&title='+encodeURIComponent(addthis_title);
    window.open(aturl,'addthis','scrollbars=yes,menubar=no,width=620,height=520,resizable=yes,toolbar=no,location=no,status=no,screenX=200,screenY=100,left=200,top=100');
    return false;
}

function poll_vote(polluiid, pollid, optionidx, timestamp, answerhash, redir_url, mode)
{
    ajax_request('/poll/vote', {
        parameters: {
            pollid: pollid,
            optionidx: optionidx,
            timestamp: timestamp,
            answerhash: answerhash,
            mode: mode },
        onSuccess: function(x) {
            if (redir_url != null && redir_url.length > 0)
            {
                window.location = redir_url;
            }
            else
            {
                Element.update('pollwrapper-' + polluiid, x.responseText);
            }
        }
    });
    sendClickEvent('poll/vote', redir_url);
}

function poll_mover(e) { Element.addClassName(e, 'mousehover'); }
function poll_mout(e) { Element.removeClassName(e, 'mousehover'); }

// remove background image flicker in IE
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

function zoomMap (selected_pic, tab_id)
{
	var source = selected_pic.getAttribute ('href');
	var pos = Position.absoluteOffset ($('weather_maps'));
	Element.show ('weather_maps_zoom');	
	Element.moveTo ('weather_maps_zoom', pos[0] + 10, pos[1] + 35);
	$('placeholder').setAttribute ('src', source);
	toggleClass ($$ ('#weather_maps_zoom li a'),tab_id,'active');
}

function swapMap (selected_pic)
{
	var source = selected_pic.getAttribute ('href');
	$('placeholder').setAttribute ('src', source);
	toggleClass ($$ ('#weather_maps_zoom li a'),selected_pic,'active');
}

function hide_random_quote()
{
    var div = $("randomPostDiv");
    if (Element.visible(div))
    {
        Element.hide("randomPostDiv");
    }
    return false;
}

function show_random_quote(userid, elem)
{
    var div = $("randomPostDiv");
    ajax_request("/member/random-post", {
        parameters: { userid : userid },
        onSuccess: function(x, json) {
            if (json && json.content)
            {
                Element.update(div, json.content);
            }
            var pos = Position.absoluteOffset(elem);
            var dim = Element.getDimensions(div);
            Element.moveToWithFit(div, pos[0] - 36, pos[1] - 106 - dim.height);
            Element.show(div);
        }
    });
    return false;
}

var Spotlight = Class.create();

Spotlight.prototype = { 

    initialize: function( textfield_id, callback ) 
    {

        // Controls whether or not we display the results
        this.sp_closed = 0;

        // Textfield we are watching
        this.textfield_id = textfield_id; 
        
        // Controls out of order requests
        this.sid = 0;

        // Use this to not blur on spotlight clicks
        this.cancel_blur = 0;

        if( callback )
        {
            this.onclick_callback_fn = callback;
        }

        this.create_and_append_container();
        
        this.textfield_handler = this.observer_callback.bindAsEventListener( this );
        Event.observe( this.textfield_id, 'keyup', this.textfield_handler );
        
        this.blur_handler = this.handle_blur.bindAsEventListener( this );
        Event.observe( textfield_id, 'blur', this.blur_handler );
        
        if( callback )
        {
            this.document_click_handler = this.handle_document_click.bindAsEventListener( this );
            Event.observe( document, 'click', this.document_click_handler );
        }

        this.document_mousedown_handler = this.handle_document_mousedown.bindAsEventListener( this );
        Event.observe( document, 'mousedown', this.document_mousedown_handler );
    },

    // dispatches click handlers 
    handle_document_click : function( event )
    {
        var elem = Event.element( event );
        var asoc_tf = elem.getAttribute( 'tf' );
                             
        if( asoc_tf == this.textfield_id )
        {
            
            var node = elem.getAttribute( 'node' );
            var pn = elem.getAttribute( 'pn' );                              
                                    
            this.onclick_callback_fn.bind( this );
            
            // Don't call spotlight until we return from the handler
            this.disable_spotlight();

            // If the handler returns true, re-enable spotlight
            if( this.onclick_callback_fn( node, pn ) )
            {
                setTimeout( this.enable_spotlight.bind( this ), 150 );
            }
            this.hide_container();

            return false;
        }

    },

    // Just use this to cancel blurs
    handle_document_mousedown : function( event )
    {
        var elem = Event.element( event );

        if( elem.getAttribute( 'cb' ) )
        {
            this.cancel_blur = 1;
        }
    },

    // Creates and appends the div that holds the spotlight results
    create_and_append_container: function() 
    {
        this.container = document.createElement( 'div' );
        Element.extend( this.container );

        this.container.id = this.textfield_id + '_sp_container';

        var body_ref = document.getElementsByTagName( 'body' ).item(0);
        body_ref.appendChild( this.container );
                     
        Element.hide(this.container);                
    },
        
    // Called on successful ajax return    
    ajax_handler : function( transport, json )
    {
        if( json.sid == this.sid )
        {
            Element.update(this.container, json.content);
            this.attach_to_close();
            this.display_container();           
        }
    },
        
    // Called by the Observer when the textfield changes
    observer_callback : function( element, element_copy )
    {
    
        var value = $F(this.textfield_id);
        if ( this.sp_closed == 0 )
        {
            var params = 'q=' + value + '&sid=' + ++this.sid + '&tf=' + this.textfield_id;
            
            if( this.onclick_callback_fn )
            {
                params = params + '&handler=1';
            }

            var othis = this;            
            new Ajax.Request( '/ajax/spotlight',
                              { method: 'post',
                                parameters: params,
                                onSuccess: function(x, json) { othis.ajax_handler(x, json) }
                              }
                            );
        }

        if( $(this.textfield_id).value == '' )
        {
            this.enable_spotlight();
        }

    },

    display_container : function()
    {
        // Returns left, top
        var dims = Position.absoluteOffset( $(this.textfield_id) );
        var size = $(this.textfield_id).getDimensions();
        Element.moveTo(this.container, dims[0], dims[1] + size.height);
        Element.show(this.container);
    },
     
    handle_blur : function( e ) 
    { 
        if( this.cancel_blur == 1)
        {
            this.cancel_blur = 0;
            Form.Element.focus( this.textfield_id );
        }
        else
        {
            this.hide_container();
        }
        
        return true;
    },

    hide_container : function() { this.container.hide(); },
    
    close_spotlight : function () 
    { 
                           
        this.disable_spotlight();
        this.container.hide(); 

        return false;
    },

    attach_to_close : function()
    {
        var close_links = $(this.container).getElementsBySelector( 'a[id="close_sp_anchor"]' );

        // Should only be 1 element, if > 1 element we have a problem
        if( close_links.length == 1 && $(close_links[0]).id == 'close_sp_anchor' )
        { 
            this.close_link_id = close_links[0].id;
            this.close_link_handler = this.close_spotlight.bindAsEventListener( this );

            Event.observe( close_links[0].id , 'click', this.close_link_handler );
        }
    },

    destroy: function() 
    { 
        $(this.container).remove();
        Event.stopObserving( this.close_link_id, 'click', this.close_link_handler );
        Event.stopObserving( this.textfield_id, 'blur', this.blur_handler );
        Event.stopObserving( document, 'click', this.document_click_handler );
        Event.stopObserving( document, 'mousedown', this.document_mousedown_handler  );
        Event.stopObserving( this.textfield_id, 'keyup', this.textfield_handler );

    },

    enable_spotlight: function()
    {
        this.sp_closed = 0;
    },

    disable_spotlight: function()
    {
        this.sp_closed = 1;
    }
};

function nodebox_init_spotlight(nodeboxid)
{
    Element.hide(nodeboxid + '-nodedisplay'); 
    Element.show(nodeboxid + '-nodeupdate');
    var spotlight = new Spotlight(nodeboxid + '-nodefield-input', spotlight_fill_textfield);
    spotlight.nodeboxid = nodeboxid;
    return false;
}

function spotlight_fill_textfield(node, printname)
{
    $(this.nodeboxid + '-nodefield-input').value = printname;
    $(this.nodeboxid + '-nodefield-pn').innerHTML = printname;
    $(this.nodeboxid + '-config-node').value = node;
    Element.show(this.nodeboxid + '-nodedisplay'); 
    Element.hide(this.nodeboxid + '-nodeupdate');
    this.destroy();
    return false;
}

function nodebox_run_config_callback(callback, nodeboxid)
{
    var data = {};
    data.num_arts = $F(nodeboxid + "-config-num_arts");
    data.num_threads = $F(nodeboxid + "-config-num_threads");
    data.node = $F(nodeboxid + "-config-node");
    data.expand_first_art = $F(nodeboxid + "-config-expand");
    callback(nodeboxid, data);
}


function showBigPic(e)
{
  if ( ! e )
    e = window.event;
  var bigpic = document.getElementById( 'bigpic' );
  if ( bigpic )
    bigpic.style.display = 'block';

  cancelEvent( e );
}

function hideBigPic(e)
{
  if ( ! e )
    var e = window.event;

  var bigpic = document.getElementById( 'bigpic' );
  if ( bigpic )
    bigpic.style.display = 'none';

  cancelEvent( e );
}

function cancelEvent(e)
{
  e.cancelBubble = true;
  if ( e.stopPropagation )
    e.stopPropagation();
}

function show_citysearch_listings(url, div)
{
	ajax_request( url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );
}

function show_krillion_listings(url, div)
{
	ajax_request(url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );
}

function show_blinkx_video(url, div)
{
	ajax_request(url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );
}

function show_oodle_pet_listings(url, div)
{
	ajax_request(url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );

}

function general_ajax_content(url, div)
{
	ajax_request(url, { onSuccess : function ( x ) { Element.update( div, x.responseText ); }, method : "get" } );
}

var flag_judgeCurrent;
var flag_judgeSelected;


var flag_judgePostConflicts =
{
    "brilliant" : [ "clueless" ],
    "clueless" : [ "brilliant" ],
    "touching" : [ "mean" ],
    "mean" : [ "touching" ],
    "agree" : [ "disagree" ],
    "disagree" : [ "agree" ]
};

function flag_judgePost(elem, jid)
{
    if ($('judgediv') == null) return;
    if (jid == flag_judgeCurrent)
    {
        flag_judgePost_closePopup();
        return;
    }

    var pos = Position.absoluteOffset(elem);
    ajax_request("/ajax/flagpost/display", {
        parameters: { ajax: 1, jid: jid },
        onSuccess: function(x) {
            Element.update('judgediv', x.responseText);
            Element.moveTo('judgediv', pos[0] - 140, pos[1] + 20);
            Element.show('judgediv');
            flag_judgeCurrent = jid;
            flag_judgeSelected = [];
        }
    });
}

function flag_judgePost_closePopup()
{
    Element.hide('judgediv');
    flag_judgeCurrent = null;
}


function flag_judgePhoto(elem, jid)
{
    if ($('judgediv') == null) return;
    if (jid == flag_judgeCurrent)
    {
        flag_judgePost_closePopup();
        return;
    }

    var pos = Position.absoluteOffset(elem);
    ajax_request("/ajax/flagphoto/display", {
        parameters: { ajax: 1, jid: jid },
        onSuccess: function(x) {
            Element.update('judgediv', x.responseText);
            Element.moveTo('judgediv', pos[0] - 140, pos[1] + 20);
            Element.show('judgediv');
            flag_judgeCurrent = jid;
            flag_judgeSelected = [];
        }
    });
}

function flag_judgeSubmit(form)
{
    var jitems = $$("#judgediv .judgeitem");
    var selected = [];
    for (var index=0; index<jitems.length; index++)
    {
        var jitem = jitems[index];
        if (Element.hasClassName(jitem, "selected"))
        {
            selected.push(jitem.getAttribute("jtoken"));
        }
    }
    var tokens = selected.join(",");
    form.jtokens.value = tokens;
    ajax_form_request(form, {
        onSuccess: function(x, json) {
            Element.hide('judgediv');
            if (json && json.jid && json.htmlrtn) {
                Element.update("judge-" + json.jid, json.htmlrtn);
                $("judge-" + json.jid).onclick = function() { return false; };
            }
        }
    });
    return false;
}

function del_ad(elem, node, ypid)
{
    var answer = confirm("Are you sure you want to delete this ad?");
    if (!answer) {
	return false;
    }

    ajax_request("/ad/delete/ajax", {
        parameters: { node: node, ypid: ypid },
        onSuccess: function(x) {
            Element.update("editad", x.responseText);
            // var pos = Position.absoluteOffset(elem);
            // Element.moveToWithFit("editaddiv", pos[0] - 50, pos[1] + 20);
            Element.show("editad");
        }
    });
    return false;
}

function unsponsor(ypid, cities_str)
{
    var answer = confirm("Remove sponsorship from these cities?\n" + cities_str);
    if (!answer) {
    return false;
    }
    
    ajax_request("/ajax/yp/unsponsor", {
        parameters: { ypid : ypid },
        onSuccess: function(x) {
            Element.update("unsponsor", x.responseText);
            Element.show("unsponsor");
        }
    });
    return false;
}

function markDeleted(x, key)
{
            // change the "delete" link to "deleted" text
            var del = document.getElementById("del_" + key);
            if (del)
            {
                if (x.responseText == "success")
                {
                    del.innerHTML = "<span class=\"sm\" style=\"color:#aaaaaa\">deleted</span>";
                }
                else
                {
                    del.innerHTML = "<span class=\"sm\" style=\"color:red\">" + x.responseText + "</span>";
                }
            }

            // gray out the image
            var img = document.getElementById("img_" + key);
            if (img)
            {
                img.style.opacity = "0.35";
                img.style.filter = "Alpha(opacity=35)";
                img.style.cursor = "auto";
            }
}

function delete_photo(key, title, callback)
{
    var answer = confirm("Are you sure you want to delete photo entitled '" + title + "'?"); 
    if (!answer) {
        return false;
    }

    var url = "/album/delete/ajax";

    ajax_request(url, {
        method: 'get',
        parameters: {key:key}, 
        onSuccess: function(x){ callback(x, key) }
        });

    return false;
}

function delete_event(delete_url, event_title) {
	var answer = confirm("Are you sure you want to delete the '" + event_title + "' event?");
	if (answer) {
		window.location = delete_url;
	} else {
		return false;
	}
}

function chrome_changecity(form, urltype)
{
    var conduit = 0;
    if(urltype == 'conduitnews')
    {
        conduit = 1;
        urltype = 'news';
    }
    var newLocation;

    $('chrome_changecity_submit').disabled = 'true';
    $('chrome_changecity_submit').value = 'Changing...';
    ajax_form_request(form, {
        onSuccess: function(x, json) {
            if (json.success && json.urls[urltype]) {

                if(conduit == 0)
                {
                    // regular case
                    window.location = json.urls[urltype];
                }
                else
                {
                    RefreshToolbar(); // works in gadget or html component only
                    CloseFloatingWindow();
                }

            }
            else {
                
                var message = json.message || "Could not find a city match.";
                alert(message);
                $('chrome_changecity_submit').disabled = '';
                $('chrome_changecity_submit').value = 'Change It';
            }
        },
        onFailure: function(x, json) {
            alert('Change location failed.');
            $('chrome_changecity_submit').disabled = '';
            $('chrome_changecity_submit').value = 'Change It';
        }
    });  
}


function flag_removeSelected(tag)
{
    if (flag_judgeSelected != null)
    {
        for (var i = 0; i < flag_judgeSelected.length; i++)
        {
            var selectedElem = flag_judgeSelected[i];
            if (tag == selectedElem.getAttribute("judgetype"))
            {
                flag_judgeSelected.splice(i, 1);
                toggleClassSingle(selectedElem, "selected");
                break;
            }
        }
    }
}

function flag_judgeSelect(parent)
{
    var className = "selected";

    if (Element.hasClassName(parent, className))
    {
        var currentTag = parent.getAttribute("judgetype");
        flag_removeSelected(currentTag);
        Element.removeClassName(parent, className);
    }
    else
    {
        // remove any previously selected conflicting items
        if (flag_judgeSelected.length > 0)
        {
            var currentTag = parent.getAttribute("judgetype");
            var conflictArr = flag_judgePostConflicts[currentTag];
            if (conflictArr != null)
            {
                // remove each conflicting tag that has been selected
                for (var i = 0; i < conflictArr.length; i++)
                {
                    flag_removeSelected(conflictArr[i]);
                }
            }
        }

        // if there are still too many selected, remove the earliest
        if (flag_judgeSelected.length >= 3)
        {
            var first = flag_judgeSelected.shift();
            toggleClassSingle(first, className);
        }

        Element.addClassName(parent, className);
        flag_judgeSelected.push(parent);
    }
}


var hiddenSelects = [];
function hideSelects()
{
    var elems = $$("select");
    if (elems == null) return;
    for (var idx=0; idx<elems.length; idx++)
    {
        Element.hide(elems[idx]);
        hiddenSelects.push(elems[idx]);
    }
}

function unhideSelects()
{
    for (var idx=0; idx<hiddenSelects.length; idx++)
    {
        Element.show(hiddenSelects[idx]);
    }
    hiddenSelects = [];
}

function overlay_show(opts)
{
    var dims = Element.getDimensions(document.body);
    hideSelects();
    var bgcolor = "#333333";
    if (opts && opts.backgroundColor) bgcolor = opts.backgroundColor;
    var opacity = 0.8;
    if (opts && opts.opacity) opacity = opts.opacity;
    var ie_opacity = Math.round(opacity * 100);
    var height = dims.height;
    if (height < 1200) height = 1200;
    Element.setStyle('overlaydiv', { height: height + "px", width: dims.width + "px", background: bgcolor,
                                     opacity: opacity, MozOpacity: opacity, filter: "alpha(opacity=" + ie_opacity + ")" });
    Element.show('overlaydiv');
    $('overlaydiv').observe('click', dialog_close);
}

function overlay_hide()
{
    Element.setStyle('overlaydiv', { height: "0px" });
    Element.hide('overlaydiv');
    unhideSelects();
}

var dialog_elem;

function dialog_show(elem, x, y, opts)
{
    if (!$(elem))
        return;
    overlay_show(opts);
    if (!x) x = 100;
    if (!y) y = 50;
    Element.moveToWithFit(elem, x, y);
    Element.show(elem);
    dialog_elem = elem;
}

function dialog_ajax(url, params, xpos, ypos, opts)
{
    if (dialog_elem)
        return;
    if (!xpos) xpos = 200;
    if (!ypos) ypos = 200;
    if (!params)
        params = {};
    if (params.onSuccess)
    {
        var origfn = params.onSuccess;
        params.onSuccess = function(x) { 
            if (origfn(x))
            {
                overlay_show(opts);
                Element.update('dialogdiv', x.responseText); 
                Element.moveToWithFit('dialogdiv', xpos, ypos);
                Element.show('dialogdiv');
                dialog_elem = $('dialogdiv');
            }
        };
    }
    else
    {
        params.onSuccess = function(x) { 
            overlay_show(opts);
            Element.update('dialogdiv', x.responseText); 
            Element.moveTo('dialogdiv', xpos, ypos);
            Element.show('dialogdiv');
            dialog_elem = $('dialogdiv');
        };
    }
    ajax_request(url, params);
}

function dialog_close()
{
    if (dialog_elem)
    {
        Element.hide(dialog_elem);
        dialog_elem = null;
    }
    overlay_hide();
}

function passAgeCheck()
{
    dialog_close();
    ajax_request("/ajax/pass-age-check", {
        onSuccess: function(x) { return; }
    });
}

function failAgeCheck()
{
    ajax_request("/ajax/fail-age-check", {
        onSuccess: function(x) { window.location = "/"; }
    });
}

function show_other_topics(link)
{
	var pos = Position.absoluteOffset ($(link));
	Element.addClassName(link, "active");
	Element.show ('other_topics_menu');	
	Element.moveTo ('other_topics_menu', pos[0] + 1, pos[1] + 18);
}

function hide_other_topics(link)
{
	Element.removeClassName(link, "active");
	Element.hide ('other_topics_menu');	
}

function show_other_topics_sm(link)
{
	var pos = Position.absoluteOffset ($(link));
	Element.addClassName(link, "active");
	Element.show ('other_topics_sm_menu');	
	Element.moveTo ('other_topics_sm_menu', pos[0] + 1, pos[1] + 18);
}

function hide_other_topics_sm(link)
{
	Element.removeClassName(link, "active");
	Element.hide ('other_topics_sm_menu');	
}

function skybox_toggle_pause()
{
    pe.currentlyExecuting = !pe.currentlyExecuting;
    return false;
}

function skybox_play(pe)
{
    if (undefined == pe.i)
    {
        pe.i = 0;
    }
    toggleClass($$('#hat_skybox .skybox_number'), $('skybox_number' + pe.i), 'active');
    Element.show('skybox' + pe.i);

    var next = (pe.i + 1) % 3;
    Element.hide('skybox' + next);

    var prev = (pe.i + 2) % 3;
    Element.hide('skybox' + prev);

    pe.i = next;
    return false;
}

function alerts_unsubscribe_thread(email, threadid, token)
{
    ajax_request("/alerts/unsubscribe-thread", {
        parameters: { email: email, threadid: threadid, token: token },
        onSuccess: function(x) {
            Element.addClassName($("threadrow_" + threadid), "unsubscribed");
            $("sub_" + threadid).hide();
        }
    });
    return false;
}

function alerts_unsubscribe_node(email, node, token)
{
    ajax_request("/alerts/unsubscribe-node", {
        parameters: { email: email, node: node, token: token },
        onSuccess: function(x) {
            Element.addClassName($("newsmail_" + node), "unsubscribed");
            $("sub_" + node).hide();
        }
    });
    return false;
}

function alerts_unsubscribe_forum(email, node, token)
{
    ajax_request("/alerts/unsubscribe-forum", {
        parameters: { email: email, node: node, token: token },
        onSuccess: function(x) {
            Element.addClassName($("forummail_" + node), "unsubscribed");
            $("freq_" + node).hide();
            $("forumsub_" + node).hide();
        }
    });
    return false;
}

function alerts_setdaily_node(email, node, token)
{
    ajax_request("/alerts/setdaily-node", {
        parameters: { email: email, node: node, token: token },
        onSuccess: function(x) {
            $("daily_" + node).innerHTML = "Daily";
        }
    });
    return false;
}

function alerts_setweekly_node(email, node, token)
{
    ajax_request("/alerts/setweekly-node", {
        parameters: { email: email, node: node, token: token },
        onSuccess: function(x) {
            $("daily_" + node).innerHTML = "Weekly";
        }
    });
    return false;
}

function alerts_set_forummail_freq(email, node, token, freq)
{
    ajax_request("/alerts/setfreq-forum", {
        parameters: { email: email, node: node, token: token, freq: freq },
        onSuccess: function(x) {
            $("freq_" + node).innerHTML = freq;
        }
    });
    return false;
}

function alerts_block(email, token)
{
    ajax_request("/alerts/block", {
        parameters: { email: email, token: token },
        onSuccess: function(x) {
            Element.hide("alerts_block");
            Element.show("alerts_unblock");
        }
    });
    return false;
}

function alerts_unblock(email, token)
{
    ajax_request("/alerts/unblock", {
        parameters: { email: email, token: token },
        onSuccess: function(x) {
            Element.show("alerts_block");
            Element.hide("alerts_unblock");
        }
    });
    return false;
}

var yp_flyover_iternum = 0;
var yp_flyover_insubnav = false;
var yp_flyover_inflyover = false;
var yp_flyover_hasfocus = false;

function yp_subnav_mouseover(sn_elem)
{
    yp_flyover_insubnav = true;
    if (Element.visible("subnav_yp_flyover"))
        return;
    var pos = Position.absoluteOffset(sn_elem);
    Element.moveTo("subnav_yp_flyover", pos[0], pos[1] + 33);
    Element.show("subnav_yp_flyover")
}

function yp_subnav_mouseout()
{
    yp_flyover_insubnav = false;
    var iternum = ++yp_flyover_iternum;
    setTimeout(function() { yp_subnav_flyover_tryclose(iternum) }, 1500);
}

function yp_flyover_mouseover()
{
    yp_flyover_inflyover = true;
}

function yp_flyover_mouseout()
{
    yp_flyover_inflyover = false;
    var iternum = ++yp_flyover_iternum;
    setTimeout(function() { yp_subnav_flyover_tryclose(iternum) }, 1500);
}

function yp_flyover_onfocus()
{
    yp_flyover_hasfocus = true;
}

function yp_flyover_onblur()
{
    yp_flyover_hasfocus = false;
    var iternum = ++yp_flyover_iternum;
    setTimeout(function() { yp_subnav_flyover_tryclose(iternum) }, 1500);
}

function yp_subnav_flyover_tryclose(iternum)
{
    if (iternum != yp_flyover_iternum)
        return;
    if (!yp_flyover_insubnav && !yp_flyover_inflyover && !yp_flyover_hasfocus)
    {
        Element.hide("subnav_yp_flyover");
        return;
    }
}

function local_banner_click(ypid)
{
    ajax_request("/ajax/yp/banner_click", { parameters: { ypid : ypid } });
}

function open_feedback(url_prefix, params)
{
	var js_url = escape(document.location.href);
	var js_title = document.title;
	var window_params ='/ext/feedback?clicked_page=' + js_url + '&page_title=' + js_title;

    if (params)
    {
        for (var key in params)
        {
            window_params += '&';
            window_params += key;
            window_params += '=';
            window_params += params[key];
        }
    }

    if (url_prefix)
    {
        window_params = url_prefix + window_params;
    }
	var new_window = window.open(window_params, 'feedback', 'width=660, height=680, scrollbars=yes, resizable=yes');
	new_window.focus();
}

function open_new_window (href) {
	var newWindow = window.open(href, '_blank' );
	newWindow.focus();
	return false;
}

function show_intad(intad)
{
    var intdiv = $('intaddiv');
    if (!intdiv)
        return;
    Element.remove(intdiv);
    $('dialogdiv').appendChild(intdiv);
    Element.show(intdiv);
    var vpwidth = Client.viewportWidth();
    var xpos = (vpwidth - (intad.width + 20)) / 2;
    dialog_show('dialogdiv', xpos, 100);
    setTimeout(function() { dialog_close(); }, intad.timeout);
}

function render_intad(intad)
{
    document.write("<div id=\"intaddiv\" style=\"padding:10px;text-align:middle;background-color:white;position:absolute;z-index:110;border:5px solid black;width:" + (intad.width + 20) + "px;height:" + (intad.height + 30) + "px;display:none\">");
    if (intad.pvimg && intad.pvimg.length > 0)
        document.write("<img width=\"1\" height=\"1\" src=\"" + intad.pvimg + "\"/>");
    if (intad.pvimg2 && intad.pvimg2.length > 0)
        document.write("<img width=\"1\" height=\"1\" src=\"" + intad.pvimg2 + "\"/>");
    document.write("<div id=\"intadclose\" onclick=\"dialog_close(); return false;\" style=\"float:right;cursor:pointer;margin-top:-8px;font-weight:bold;padding:3px\">CLOSE <img src=\"http://topix.cachefly.net/pics/button_close.png\" style=\"border:none;vertical-align:middle;margin-bottom:4px\"/></div>");
    document.write("<div class=\"divclear\"></div>");
    document.write(intad.creative);
    setTimeout(function() { show_intad(intad) }, 2000);
}

function dfp_intad(intad)
{
    intadhook1 = function() { render_intad(intad); };
    intadhook2 = function() { document.write("</div>"); };
}


function postNew()
{
    document.forms['commentForm'].submit();
    return false;
}

function quotePost(postid)
{
    document.forms['commentForm'].quotepostid.value = postid;
    document.forms['commentForm'].submit(); 
    return false;
}

function issue_vote(node, issue, vote, successfn)
{
    ajax_request("/ajax/issue/vote", {
        parameters: { node: node, issue: issue, vote: vote },
        onSuccess: successfn
    });
}

function issue_clickSupport()
{
    var vtc = $('votediv');
    Element.addClassName(Element.down(vtc, "#vote-support"), "highlighted");
    Element.removeClassName(Element.down(vtc, "#vote-oppose"), "highlighted");
    Element.down(vtc, "input[name=vote]").value = "support";
}

function issue_clickOppose()
{
    var vtc = $('votediv');
    Element.addClassName(Element.down(vtc, "#vote-oppose"), "highlighted");
    Element.removeClassName(Element.down(vtc, "#vote-support"), "highlighted");
    Element.down(vtc, "input[name=vote]").value = "oppose";
}

var numbers_str = [ "", "1st", "2nd", "3rd", "4th", "5th" ];

var issue_errmsg_map = {
    "captcha.missing": "Please type in the numbers you see in the image.",
    "captcha": "The numbers you typed in did not match the nubmers in the image.  Please try again.",
    "input.comments": "There was a problem processing your comments.  Please try again.",
    "input.sn": "Invalid or reserved name.  Please enter a different name to post your comment.",
    "profanity.allcaps": "Posting in all caps makes your posts harder to read and is discouraged.",
    "profanity.profanity": "Please refrain from posting profanity or offensive material.  <b>Be polite</b>. Inappropriate posts may be removed by the moderator.",
    "protocol.userauth": "Bad screename or user.  Did you maybe just logout?  Refreshing the page should fix the problem.",
    "protocol.nonce": "Something went wrong processing your comment.  Did you maybe just logout?  Please refresh the page and try again."
};
var issue_defaulterrmsg = "Something went wrong while trying to process your vote.  Please refresh the page and try again.";

var vote_data;

function issue_spawnVoteWindow(initialvote, node, issue_threadid)
{
    if (initialvote == "support")
        issue_clickSupport();
    if (initialvote == "oppose")
        issue_clickOppose();
    var votediv = $('votediv');
    var errdiv = Element.down(votediv, '#vote_errdiv');
    Element.down(votediv, "textarea[name=comments]").value = "";
    Element.down(votediv, "input[name=captcha]").value = "";
    Element.down(votediv, "input[name=node]").value = node;
    Element.down(votediv, "input[name=threadid]").value = issue_threadid;
    errdiv.innerHTML = "";
    var captchaimg = $('vote-captchaimg');
    
    vote_data = {};
    ajax_request("/ajax/forum/forum-captcha", {
        parameters: { ajax: 1, threadid: issue_threadid, node: node },
        onSuccess: function(x, json) {
            if (!json) {
                errdiv.innerHTML = issue_defaulterrmsg;
                return;
            }
            if (json.errorstr) {
                errdiv.innerHTML = json.errorstr;
                return;
            }
            if (json.captcha_params) {
                vote_data.timestamp = json.timestamp;
                vote_data.nonce = json.nonce;
                vote_data.captcha_params = json.captcha_params;
                vote_data.num_errors = 0;
                captchaimg.src = vote_data.captcha_params.captcha_url;
                dialog_show('votediv', 200 + Client.scrollLeft(), 200 + Client.scrollTop());
            }
        }
    });
}


function issue_verifyAndSubmit(issueform, votedonefn)
{
    var commentinput = Element.down(issueform, 'textarea[name=comments]');
    if (commentinput.value && commentinput.value.length > 1 && !commentinput.value.match(/^\s+$/)) {
        issue_verifyAndSubmitWithComment(issueform, votedonefn);
        return;
    }
    var vote = Element.down(issueform, 'input[name=vote]').value;
    var issue = Element.down(issueform, 'input[name=issue]').value;
    var node = Element.down(issueform, 'input[name=node]').value;
    issue_vote(node, issue, vote, votedonefn);
}

function issue_verifyAndSubmitWithComment(issueform, votedonefn)
{
    var cvalue = Element.down(issueform, "input[name=captcha]").value;
    var errdiv = Element.down(issueform, "#vote_errdiv");
    var commentvalue = Element.down(issueform, "textarea[name=comments]").value;
    var snelem = Element.down(issueform, "input[name=screenname]");
    var namevalue;
    if (snelem)
        namevalue = snelem.value;
    var issue_threadid = Element.down(issueform, "input[name=threadid]").value;
    var nodevalue = Element.down(issueform, "input[name=node]").value;

    if (snelem && (!namevalue || namevalue.length == 0)) {
        errdiv.innerHTML = "Name cannot be blank.";
        return;
    }
    if (!commentvalue || commentvalue.length == 0) {
        errdiv.innerHTML = "Comment cannot be blank.";
        return;
    }
    ajax_request("/ajax/forum/forum-captcha-check", {
        parameters: { nonce: vote_data.nonce, node: nodevalue, timestamp: vote_data.timestamp,
                      threadid: issue_threadid, captchavalue: cvalue },
        onSuccess: function(x, json) {
            if (!json || !json.captchaok) {
                vote_data.num_errors++;
                if (vote_data.num_errors > 3) {
                    alert("Sorry, we were unable to process your vote.  If you are unable to see the numbers, please refresh the page and try again.");
                    dialog_close();
                }
                errdiv.innerHTML = "The numbers you typed in did not match the numbers in the image.  Please try again. (" + numbers_str[vote_data.num_errors] + " try)";
                return;
            }
            issue_submitComment(issueform, votedonefn);
        }
    });
}

function issue_submitComment(issueform, votedonefn)
{
    var cvalue = Element.down(issueform, "input[name=captcha]").value;
    var errdiv = Element.down(issueform, "#vote_errdiv");
    var commentvalue = Element.down(issueform, "textarea[name=comments]").value;
    var namevalue;
    var snelem = Element.down(issueform, "input[name=screenname]");
    if (snelem)
        namevalue = snelem.value;
    var issue = Element.down(issueform, "input[name=issue]").value;
    var vote = Element.down(issueform, "input[name=vote]").value;
    var subject = Element.down(issueform, "input[name=subject]").value;
    var issue_threadid = Element.down(issueform, "input[name=threadid]").value;
    var node = Element.down(issueform, "input[name=node]").value;

    ajax_request("/ajax/forum/forum-post", {
        parameters: {
            node: node,
            nonce: vote_data.nonce,
            timestamp: vote_data.timestamp,
            threadid: issue_threadid,
            captchavalue: cvalue,
            comments: commentvalue,
            anon_sn: namevalue,
            issue: issue,
            warned: vote_data.warned,
            issuevote: vote,
            subject: subject
        },
        onSuccess: function(x, json) {
            if (json && json.success) {
                issue_vote(node, issue, vote, votedonefn);
                return;
            }
            if (json && json.errorcode) {
                if (!json.errormsg)
                    json.errormsg = issue_errmsg_map[json.errorcode];
                if (!json.errormsg)
                    json.errormsg = issue_defaulterrmsg;
                errdiv.innerHTML = json.errormsg;
                if (json.setwarned)
                    vote_data.warned = 1;
                if (json.errorcode && json.errorcode.match(/^(protocol|captcha)/)) {
                    alert('There was a problem submitting your comment.  Please refresh the page and try again');
                    dialog_close();
                }
            }
            else {
                errdiv.innerHTML = "Bad Response from the server.  Please try again.";
            }
        }
    });
}

function conduit_refresh()
{
    try 
    { 
        // Only works when called from the main browser page
        RefreshToolbarByCTID("CT2325934"); 
    } 
    catch(e) {}
}

function topixconduit_closeAfterClick()
{
    setTimeout(function() { CloseFloatingWindow(); }, 2000);
    return true;
}

function topix_loadScript(url)
{
    var selem = document.createElement("script");
    selem.setAttribute("src", url);
    selem.setAttribute("type", "text/javascript");
    document.getElementsByTagName("head")[0].appendChild(selem);
}

function topix_loginDisplay(loginDisplay, forgotPasswordDisplay)
{
    var loginDiv = document.getElementById("loginDiv");
    if (loginDiv)
    {
        loginDiv.style.display = loginDisplay;
    }
    var forgotPasswordDiv = document.getElementById("forgotPasswordDiv");
    if (forgotPasswordDiv)
    {
        forgotPasswordDiv.style.display = forgotPasswordDisplay;
    }
    return false;
}

function topix_switchAuth(newOption)
{
    var ids = new Array('at_cookie', 'at_anon', 'at_reg', 'at_login');
    var id = "at_" + newOption;

    // var vis = document.getElementById("visible_tr").style.display;
    var vis = "block";

    for (var i = 0; i < ids.length; i++)
    {
        vis = document.getElementById(ids[i]).style.display;
        if (vis != "none")
        {
            break;
        }
    }
    
	for (var i = 0; i < ids.length; i++)
    {
        if (ids[i] == id)
        {
            topix_setVis(ids[i], vis);
        }
        else
        {
            topix_setVis(ids[i], 'none');
        }
	}
    document.getElementById("authtype_field").value = newOption;
    return false;
}


function topix_forgotPassword(emailFieldId)
{
    var emailElem = document.getElementById(emailFieldId);
    var url = "/member/forgotPassword?login_email=" + escape(emailElem.value);

    sendUrl(url, function(x) {
        if (x.responseText == "success")
        {
            var elem = document.getElementById("forgotPassword");
            elem.innerHTML = "<p style=\"margin-bottom:10px; border:1px solid #f90; background-color:#ffc; padding:4px;\"><strong>Check your Email: </strong>We have sent you an email with instructions on how to reset your password.</p>";
        }
        else
        {
            var elem = document.getElementById("forgotPasswordError");
            elem.innerHTML = x.responseText;
        }
    });
    return false;
}

function topix_setVis(id, visibility)
{
    var elem = document.getElementById(id);
    if (elem)
    {
        elem.style.display = visibility;
    }
}

var art_post_data = new Array();
var ini_post_data = new Array();
var art_click_data = new Array();
var disable_trackArtClick;

function news_trackArtClick(url)
{
    if (!art_click_data[url])
    {
        art_click_data[url] = 1;

        if (disable_trackArtClick)
        {
            return;
        }

        ajax_request("/ajax/track-art-click", {
            parameters: { ajax: 1, url: url, node: page_node }
        });
    }
}

function news_clickHeadline(storyid)
{
    var storyelem = $("storyid-" + storyid);
    news_trackArtClick(storyelem.down("a.headline").href);
    news_toggleHighlightStory(storyid);
    return false;
}

function news_clickFullStory(storyid)
{
    var storyelem = $("storyid-" + storyid);
    news_trackArtClick(storyelem.down("a.headline").href);
    news_highlightStory(storyid);
    return true;
}

function news_verifyAndSpawnCaptcha(storyid, node, threadid)
{
    var storyelem = $('storyid-' + storyid);
    $('storyid-input').value = storyid;
    var errdiv = storyelem.down(".comment_error");
    errdiv.innerHTML = "";  // clear the errors
    var post_data = art_post_data[storyid];
    var asdiv = storyelem.down("input[name=anon_sn]");
    if (asdiv) {
        post_data.anon_sn = asdiv.value;
        if (post_data.anon_sn.length == 0) {
            errdiv.innerHTML = "Name cannot be blank.";
            return false;
        }
        if (!post_data.anon_sn.match(/[a-z].*[a-z].*[a-z]/i)) {
            errdiv.innerHTML = "Name must container at least 3 letters (a-z).";
            return false;
        }
        if (post_data.anon_sn.length > 25) {
            errdiv.innerHTML = "Name can only be 25 characters long (currently " + post_data.anon_sn.length + " characters).";
            return false;
        }
        if (!post_data.anon_sn.match(/^[a-z0-9_ -]+$/i)) {
            errdiv.innerHTML = "Name must only contain alphanumerics, underscore, or dash.";
            return false;
        }
    }

    post_data.comments = storyelem.down("textarea[name=comments]").value;
    if (post_data.comments.length == 0) {
        errdiv.innerHTML = "Comment cannot be blank.";
        return false;
    }

    storyelem.down("input[name=commentsubmit]").disabled = 1;

    if (post_data.captchaok) {
        news_submitPost(storyid);
        return;
    }

    ajax_request("/ajax/forum/forum-captcha", {
        parameters: { ajax: 1, threadid: post_data.threadid, node: page_node },
        onSuccess: function(x, json) {
            storyelem.down("input[name=commentsubmit]").disabled = 0;
            if (!json) {
                errdiv.innerHTML = errmsg_default;
                return;
            }
            if (json.errorstr) {
                errdiv.innerHTML = json.errorstr;
                return;
            }
            if (json.captcha_params) {
                post_data.timestamp = json.timestamp;
                post_data.nonce = json.nonce;
                post_data.captcha_params = json.captcha_params;
                news_spawnCaptcha(storyid);
            }
        }
    });
}

function news_spawnCaptcha(storyid)
{
    var post_data = art_post_data[storyid];
    $('captchaerror').innerHTML = "";
    $('captchasubmit').disabled = 0;
    $('captchainput').value = "";
    $('captchaimg').src = post_data.captcha_params.captcha_url;
    dialog_show('captchadiv', 200 + Client.scrollLeft(), 200 + Client.scrollTop());
    $('captchainput').focus();
}

function news_submitCaptcha()
{
    var storyid = $('storyid-input').value;
    var storyelem = $('storyid-' + storyid);
    var post_data = art_post_data[storyid];
    var captchavalue = $('captchainput').value;
    $('captchasubmit').disabled = 1;
    post_data.captchavalue = captchavalue;
    sendClickEvent("newspage/captcha-submit", storyelem.down("a.headline").href);
    ajax_request("/ajax/forum/forum-captcha-check", {
        parameters: { nonce: post_data.nonce, node: page_node, timestamp: post_data.timestamp,
                      threadid: post_data.threadid, captchavalue: captchavalue },
        onSuccess: function(x, json) {
            $('captchasubmit').disabled = 0;
            if (json && json.captchaok) {
                post_data.captchaok = 1;
                dialog_close();
                news_submitPost(storyid);
            }
            else {
                if (!post_data.captchaerror)
                    post_data.captchaerror = 0;
                post_data.captchaerror++;
                if (post_data.captchaerror >= 3) {
                    art_post_data[storyid] = Object.clone(ini_post_data[storyid]);
                    storyelem.down('.comment_error').innerHTML = news_errmsg_map["captcha"];
                    dialog_close();
                }
                $('captchaerror').innerHTML = "The characters are incorrect.  Please try again.";
            }
        }
    });
    return false;
}

var errmsg_map = {
    "protocol.nonce": "Something went wrong processing your comment.  Did you maybe just logout?  Please refresh the page and try again.",
    "protocol.art": "There is a problem with the article you are trying to comment on.  Please refresh the page and try again.",
    "protocol.userauth": "Bad screename or user.  Did you maybe just logout?  Refreshing the page should fix the problem.",
    "captcha": "The numbers you typed in did not match the nubmers in the image.  Please try again.",
    "input.comments": "There was a problem processing your comments.  Please try again.",
    "input.sn": "Invalid or reserved name.  Please enter a different name to post your comment.",
    "profanity.allcaps": "Posting in all caps makes your posts harder to read and is discouraged.",
    "profanity.profanity": "Please refrain from posting profanity or offensive material.  <b>Be polite</b>. Inappropriate posts may be removed by the moderator."
};
var errmsg_default = "Something went wrong processing your comment.  Please refresh the page and try again.";

function news_submitPost(storyid)
{
    var storyelem = $("storyid-" + storyid);
    var post_data = art_post_data[storyid];
    var errdiv = storyelem.down(".comment_error");
    ajax_request("/ajax/forum/forum-post", {
        parameters: { 
            node: page_node,
            nonce: post_data.nonce,
            timestamp: post_data.timestamp,
            threadid: post_data.threadid,
            captchavalue: post_data.captchavalue,
            comments: post_data.comments,
            anon_sn: post_data.anon_sn,
            artstruct: post_data.artstruct,
            warned: post_data.warned
        },
        onSuccess: function(x, json) {
            storyelem.down("input[name=commentsubmit]").disabled = 0;
            if (json && json.success) {
                news_instantiateThanksForm(storyid);
                Element.addClassName('storyid-' + storyid, "doneposting");
            }
            else if (json && json.errorcode) {
                if (!json.errormsg)
                    json.errormsg = news_errmsg_map[json.errorcode];
                if (!json.errormsg)
                    json.errormsg = errmsg_default;
                errdiv.innerHTML = json.errormsg;
                if (json.setwarned)
                    post_data.warned = 1;
                if (json.errorcode && json.errorcode.match(/^(protocol|captcha)/))
                    art_post_data[storyid] = Object.clone(ini_post_data[storyid]);
            }
            else {
                errdiv.innerHTML = "Bad response from the server.  Please try again.";
            }
        }
    });
    return;
}

function news_subscribeThread(storyid)
{
    var post_data = art_post_data[storyid];
    $('forumalert-threadid').value = post_data.threadid;
    $('forumalert-artstruct').value = post_data.artstruct;
    $('forumalert-form').submit();
    return false;
}

function news_highlightStory(storyid)
{
    var storyelem = $('storyid-' + storyid);
    news_instantiatePostForm(storyid);
    Element.addClassName(storyelem, 'highlighted');
    var ta = storyelem.down(".postarea").down("textarea");
    if (ta)
        ta.focus();
    return false;
}

function news_toggleHighlightStory(storyid)
{
    var storyelem = $('storyid-' + storyid);
    news_instantiatePostForm(storyid);
    toggleClassSingle(storyelem, 'highlighted');
    if (Element.hasClassName(storyelem, 'highlighted'))
    {
        var ta = storyelem.down(".postarea").down("textarea");
        if (ta)
            ta.focus();
    }
    return false;
}

function news_instantiatePostForm(storyid)
{
    var storyelem = $('storyid-' + storyid);
    var postarea = storyelem.down('.postarea');
    if (postarea.down("form"))
        return;
    var postformhtml = $('proto-postform').innerHTML;
    postarea.innerHTML = postformhtml;
    addLinkTrackerToContainer(postarea);
    postarea.down("form").onsubmit = function() { 
        sendClickEvent("newspage/post-comment", storyelem.down("a.headline").href);
        news_verifyAndSpawnCaptcha(storyid); return false;
    };

    postarea.down("textarea").tabIndex = storyid * 5;
    if (postarea.down("input[name=anon_sn]"))
        postarea.down("input[name=anon_sn]").tabIndex = (storyid * 5) + 1;
    postarea.down("input[name=commentsubmit]").tabIndex = (storyid * 5) + 2;
}

function news_instantiateThanksForm(storyid)
{
    var storyelem = $('storyid-' + storyid);
    var thanksarea = storyelem.down('.thanksarea');
    if (thanksarea.down("a"))
        return;
    var thanksareahtml = $('proto-thanksarea').innerHTML;
    thanksarea.innerHTML = thanksareahtml;
    addLinkTrackerToContainer(thanksarea);

    var post_data = art_post_data[storyid];
    thanksarea.down("a.thanksforumalertlink").onclick = function() { return news_subscribeThread(storyid); };
    
    thanksarea.down("a.thanksthreadlink").href = "/forum/" + page_nnode + "/T" + post_data.threadid;
}
